Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat: company mode — organizations of Agents driven by a calendar, a ticket board and a group chat (#587)

Yaowei Zhenge2c8caf2e59e
diff --git a/README.md b/README.md
index 92d27aaf..d8b57e7f 100644
--- a/README.md
+++ b/README.md
@@ -84,13 +84,14 @@ https://github.com/user-attachments/assets/922d13a6-5ffc-4685-9a39-352f02f9afc0
## Built-in plugins
-Three plugin categories ship in the box ([docs](https://penguin.ooo/docs/skills)) — skills, plus the session hooks that drive goal mode and continual learning; agents can also write and optimize their own skills:
+Four plugin categories ship in the box ([docs](https://penguin.ooo/docs/skills)) — skills, plus the session hooks that drive goal mode and continual learning; agents can also write and optimize their own skills:
| Category | Plugins |
| -------------------- | ----------------------------------------------------------------------------- |
| Office Productivity | `data-analysis`, `use-firecrawl`, `use-bento-slides`, `humanizer`, `goal`, `continual-learning` |
| Software Development | `software-development`, `use-claude-code` |
| AI App Development | `agent-development`, `model-development`, `skill-porting`, `agent-tuning` |
+| Agent Company | `agent-company` |
## Supported Models
diff --git a/README.zh.md b/README.zh.md
index 37ef2564..65b073d2 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -84,13 +84,14 @@ https://github.com/user-attachments/assets/aec49ae9-b743-467b-b247-37bedfeaa36e
## 内置插件库
-开箱内置三类插件([文档](https://penguin.ooo/docs/skills))——Skill,以及驱动目标模式与持续学习的会话钩子;Agent 也能编写并优化自己的 Skill:
+开箱内置四类插件([文档](https://penguin.ooo/docs/skills))——Skill,以及驱动目标模式与持续学习的会话钩子;Agent 也能编写并优化自己的 Skill:
| 分类 | 插件 |
| ----------- | ------------------------------------------------------------------------------- |
| 办公效率 | `data-analysis`、`use-firecrawl`、`use-bento-slides`、`humanizer`、`goal`、`continual-learning` |
| 软件开发 | `software-development`、`use-claude-code` |
| AI 应用开发 | `agent-development`、`model-development`、`skill-porting`、`agent-tuning` |
+| Agent 公司 | `agent-company` |
## 支持的模型
diff --git a/changelog/unreleased/2026-09-02-company-mode.md b/changelog/unreleased/2026-09-02-company-mode.md
new file mode 100644
index 00000000..4bcff419
--- /dev/null
+++ b/changelog/unreleased/2026-09-02-company-mode.md
@@ -0,0 +1,468 @@
+# Company mode: organizations of Agents driven by a calendar, a ticket board and channels
+
+- **Date:** 2026-09-02
+- **Type:** feature
+- **Scope:** `server`, `web`, `cli`, `core`, `skills`, `docs`
+- **PR:** [#587](https://github.com/Prism-Shadow/penguin-harness/pull/587)
+
+[中文版](2026-09-02-company-mode.zh.md)
+
+The Web App gained a second work mode. In company mode a Project's Agents form an
+**organization**: a CEO at the root of a reporting tree, one standing **desk session** per
+employee, a **calendar** that is the only periodic driver, a five-column **ticket board** that
+carries the work, **channels** where only `@` mentions reach anyone, and monthly
+**budgets** per employee that warn at 80% and pause the employee's calendar at 100%. Creating
+an organization takes one sentence — the mission — and produces only the CEO; the CEO hires
+HR, finance and the rest, partitions the shared workspace, schedules everyone and files the
+first tickets from an initialization run on its desk.
+
+Every piece of an organization is a file under
+`<project>/organizations/<org_id>/`: `org_config.toml`, `org_chart.yaml` (the tree with each
+employee's budget, workspace and model), `desks.toml` (the server's ledger of desk sessions),
+`calendar/<agent_id>/<event>.toml` (the scheduled-task format without target fields),
+`tickets/<yyyy-mm>/<column>/<yyyy-mm-dd>-<slug>.md` (an Agent-Notes-style header — Status,
+Initiator, Owner, Parent, Notify, Priority, Due, Blocked, Blocked-by, Sessions — over Goal,
+Acceptance criteria, Progress and Result sections), `channels/<channel_id>/` (one directory
+per channel: a `channel.toml` intent file with its name, purpose and members, and a
+`<yyyy-mm-dd>.jsonl` per day of messages) and the handbook directory `handbook/` (the company's knowledge base, whose
+`README.md` is the index every trigger makes the employee read first; the other documents are
+listed there and read on demand). SQLite holds only caches rebuilt from those files on every pass (desk and ticket
+session ownership, calendar run state, the last noticed ticket state, the per-channel scan
+cursors, budget marks) and each user's read cursor per channel.
+
+## Details
+
+- Server: an organization scheduler shaped like the schedule scheduler reconciles every
+ organization every 30 seconds and immediately after an API write — it projects the ledger
+ and the tickets into the caches, renews a desk whose workspace the chart moved, fires due
+ calendar events to desks (queued behind a running Task, held while the organization or the
+ employee is paused, never backfilled), notices ticket changes once (assigned, blocked,
+ blocker closed, done, rejected — employees on their desks, people through a system line in
+ the all-hands channel), delivers channel mentions with a hop chain that stops at the organization's limit, and
+ recomputes budgets. Every trigger is one user input that starts with an `[org_trigger]`
+ block; ticket sessions are ordinary sessions of the employee's Agent, appended to the
+ ticket's `Sessions` header. Spend is attributed by session: an employee's own sessions plus
+ every subordinate's, a ticket's contributing sessions split between the tickets they serve,
+ rolled up along `Parent`.
+- API: `/api/projects/:projectId/organizations` and its sub-routes for the chart, employees,
+ desks, the handbook, the calendar, tickets (move, block, unblock, progress, start, attach),
+ channels (their members, messages and read cursor), finance and the organization's
+ sessions; user-level events `org_run`, `org_channel`, `org_ticket` and `org_budget`. Any
+ Project member reads and writes; only the owner deletes. Migration 6 adds the seven
+ organization tables.
+- Switches: an admin master switch (`companyMode` in server settings, default on; off stops
+ the scheduler, 404s the routes and hides the mode switch, reported by `GET /api/me`), a
+ personal switch in `ui_prefs`, and an organization's own `status: paused`.
+- Control environment: a desk or ticket session's command subprocesses also receive
+ `PENGUIN_ORG_ID`, so `penguin org` needs no `--org-id` inside one.
+- Core: the marker registry gained `[org_trigger]` (title-noise like `[scheduled_task]`) with
+ `buildOrgTriggerMessage` / `parseOrgTriggerMessage`.
+- CLI: the `penguin org` family — `ls`, `create`, `show`, `chart`, `hire`, `employee set`,
+ `leave`, `desk show|renew`, `calendar ls|add|update|rm`, `ticket
+ ls|show|create|move|assign|block|unblock|progress|start|attach`, `channel
+ ls|create|show|invite|join|leave|remove|archive|unarchive|tail|send` (`--channel` defaults
+ to `default_channel`), `handbook list|show|write|rm`, `finance` — a thin client over the
+ API with `--json` everywhere.
+- Web: a Development | Company mode switch above the Project switcher, an organization
+ switcher with creation and settings, six nav pages (overview, org chart, calendar, tickets,
+ finance, handbook — the knowledge base as a file list beside the rendered document, with
+ editing in place, new documents and deletion) plus the channel view, 频道 / Channels as the
+ sidebar's own list where development mode lists conversations (all-hands pinned, 我的频道,
+ others with a 加入 action, archived folded), the `[org_trigger]` banner in conversations, and
+ the two switches on the settings page. Below the channels the sidebar lists the organization
+ itself: 工位 / Desks, one row per employee in chart order, expanded, opening that employee's
+ desk and creating it when none exists; and 工单会话 / Ticket sessions, collapsed, the
+ sessions attached to tickets, newest first, each with the title of the ticket it
+ contributes to as the row's subtitle. The collapsed
+ rail carries the desks as avatars with their running dots. A desk or ticket conversation is
+ the ORDINARY conversation — the same message list, tool cards, approvals and composer as
+ development mode — with the company sidebar around it and its row marked; company mode has
+ no chat view of its own. The organization the sidebar shows stays the shell's current one
+ while such a conversation is open, so its channels and desks do not blank out at
+ `/chat/:sessionId`. The create-organization dialog keeps what was typed as a draft in
+ `localStorage`, per user and Project: restored when the dialog reopens after an accidental
+ close, a reload or a mode switch, dropped on a successful create or through 清空草稿 / Clear
+ draft, and it carries the CEO budget field. In a channel, a message that names the reader is
+ marked by its mention chip alone (the tinted row is gone), the hop chip appears only from the
+ second hop (hop 1 is an employee answering a trigger and says nothing), and the composer's
+ box and its 发送 button are one row of the same height, bottom-aligned, the button staying
+ anchored as the box grows.
+- Creation options: an organization may be created with a **model** (a configured pair, used
+ by every desk and ticket session whose employee names none) and a **company workspace** (an
+ existing absolute directory used as the shared workspace instead of the organization's own
+ `workspace/`); both are `org_config.toml` fields, editable in the organization settings and
+ through `penguin org create --workspace … --model-id … --provider …`.
+- Decision gate: the CEO proposes and the board decides — the initialization run posts one
+ proposal (mission reading, first tickets, hiring plan with budgets and model, workspace
+ split) and ends; hiring, budgets, rejecting others' tickets, closing P0/P1 tickets without
+ review, anything outside the organization and structural changes wait for the creator's
+ confirmation in the all-hands channel. Employees escalate such matters to the CEO. Encoded in the
+ `company-ceo` / `company-employee` skills, the init run and the handbook.
+- The handbook is a directory, `handbook/`, and the company's knowledge base: its `README.md` is
+ the index every trigger points at (layout, protocols, role conventions, and a list of documents
+ with one line each saying when it matters); board decisions, conventions and how-tos live next
+ to it as Markdown files, read on demand. The API lists, reads, writes and deletes documents,
+ `penguin org handbook list | show | write | rm` does the same from a session, the Web App's
+ Handbook page browses, edits and creates them, and the index cannot be deleted.
+- Scheduling guidance: the CEO/HR skills, the initialization run and the handbook schedule
+ the calendar as a rota — role cadences (CEO daily, HR every three days, finance weekly),
+ a distinct hour per employee, one recurring event per employee, never `--start-at now`.
+- Plugins: a new `agent-company` plugin in its own category (Agent Company / Agent 公司,
+ `preinstall: false`) with the `company-employee`, `company-ceo`, `company-hr` and
+ `company-finance` skills; the CEO and every hired Agent get it together with
+ `agent-development`.
+- Channels: an organization's talk is a set of channels, each a directory under `channels/`
+ with a `channel.toml` intent file. `default_channel` is the all-hands channel created with
+ the organization, that every employee and every Project member is in implicitly and where
+ budget alerts, ticket notices to people and hire notices land. Anyone — a person or an
+ employee — opens more; a new channel holds only its creator, an employee gets in only when
+ a member invites it, and a person may join any channel and read every one of them. Delivery
+ follows membership: `@agent:<id>` wakes a desk only inside the channel, `@all` is that
+ channel's members minus the sender, and a message naming a non-member is refused with
+ `mention_not_member` before anything is written. The `[org_trigger]` block for
+ `kind: mention` carries a `channel:` line, so an employee answers where it was addressed.
+ Archiving (people only) makes a channel read-only; the all-hands channel cannot be
+ archived, left, or have its membership edited. The scan cursor and each person's read
+ cursor are per channel — migration 7 recreates the two tables as `org_channel_state` and
+ `org_channel_reads`. `penguin org channel` is the CLI family, and channels are the Web
+ App's primary list in company mode, with desk and ticket sessions in their own groups below it.
+- CEO budget: creation writes the CEO's monthly budget into `org_chart.yaml` — 100 USD
+ unless it names another (`ceoBudget` in the create request, `--ceo-budget` on
+ `penguin org create`, a CEO budget field in the create dialog). Budgets are compared on
+ the cumulative line, so that one number caps the whole company from the first minute
+ instead of leaving it unbounded; the initialization run's trigger block names it, and the
+ CEO sizes its hiring proposal to it. The org chart raises, lowers or clears it afterwards.
+- Guided creation: `company-setup`, a skill of `agent-development` — the plugin
+ `default_agent` already carries — so an organization can be created by asking the general
+ agent for one. It collects the id, name, mission, shared workspace, model and CEO budget
+ one question at a time in the user's language, shows a one-screen summary, waits for a
+ yes, runs `penguin org create` and hands the user over to company mode. It never hires,
+ schedules or files tickets: that is the CEO's work after the board answers its proposal.
+- Organization sessions stay out of development mode: the session DTO gained `orgId` — the
+ owning organization of a desk session or of a session contributing to one of its tickets,
+ taken from the organization caches (one query per list, never one per row) and served by
+ both the session list and `GET /api/sessions/:sessionId`. Development mode's session list
+ and its time buckets hide every row that carries it, and the Organization folder that used to
+ hold them is gone — company mode's 工位 / 工单会话 groups are where they are listed. The
+ hiding is conditional on company mode being available to that user (the admin's master switch
+ and the user's own): `orgId` is stamped either way, and with company mode off nothing else
+ would list those sessions. The group headers and the "show the rest" row subtract what was
+ hidden, so a group never promises rows it will not draw.
+- Docs: a Company Mode guide with the marketplace walkthrough, the `penguin org` reference,
+ and the organization routes in the server API reference.
+
+### After the first trial round (2026-09-08)
+
+- Working language: `org_config.toml` gained `language` (`zh` / `en`), detected from the mission
+ at creation (one Han character anywhere makes it `zh`) unless the request names one —
+ `language` on `POST /organizations` and `PATCH /:orgId`,
+ `penguin org create --language <zh|en>`, and a Working language select in the Web App's
+ organization settings; `penguin org show` prints it. The handbook index, the CEO's
+ initialization run, the employee briefs (`AGENTS.md`) and the desk session titles are
+ rendered in it, and the skills have every employee write its messages, tickets, documents
+ and reports in it. An organization written
+ before the field has none stored and reads as whatever its mission is written in; nothing
+ was migrated.
+- Relative workspace sub-directories are created: `--workspace hr` (or `./hr`) on `hire` and
+ `employee set` is normalized to `hr` and created under the shared workspace when it is
+ missing, an absolute path must still exist, and a spec climbing out with `..` is 400
+ `invalid_workspace`. Opening a desk or a ticket session creates the directory too, so a
+ hand-edited chart never leaves an employee unable to work over a missing directory.
+- `POST /api/projects/:projectId/organizations/suggest-id` — `{name, kind: "org" | "channel",
+ taken?}` → `{id, source: "model" | "fallback"}`: the Project's default model proposes a short
+ English snake_case id, an ASCII slug of the name answers when it cannot, and 422
+ `id_not_derivable` when neither can name it; the completion belongs to no Session and is not
+ metered. The Web App's create-organization and new-channel dialogs put the display name
+ first and carry a button that generates the id from it.
+- Calendar writes answer with rota advice: `POST /:orgId/calendar`, `PUT
+ /:orgId/calendar/:agentId/:name` and `penguin org calendar add | update` return the stored
+ event plus advisory `warnings` — another employee's recurring event on the same start
+ minute, a second recurring event for the same employee on the same period, a recurring event
+ started at `now`. The CLI prints them as `Rota notice:` lines, the Web calendar dialog puts a
+ stagger hint under the start time and toasts the warnings, and the CEO and HR skills say to
+ fix them rather than move on.
+- Tickets: `--initiator <agent_id|principal>` (`initiator` in the create body) files a ticket
+ in an employee's or a Project member's name — it becomes the `Initiator`, the author of the
+ "created the ticket" progress line and the default `Notify`, the last only when the initiator
+ is an employee: a person filing a ticket is no longer @-mentioned when it closes (list
+ yourself in `--notify` to be told; the completion's system line still goes to the all-hands
+ channel). A session's progress line, body edit or move into `review` books that session as
+ one of the ticket's contributing sessions, so its cost lands on the ticket; accepting,
+ closing, blocking and unblocking book nothing. A `ticket_work` session opens with a
+ `Workspace:` line and the rule that every reference and deliverable is named by its full
+ path, and the `assigned` and `blocker_closed` notices end with the `penguin org ticket start`
+ command to run.
+- Channel `system` lines carry a structured `notice` — a `kind` (`employee_joined`,
+ `employee_left`, `channel_created`, `channel_archived`, `channel_unarchived`,
+ `channel_joined`, `channel_invited`, `channel_left`, `channel_removed`, `budget_warned`,
+ `budget_paused`, `ticket_blocked`, `ticket_done`, `ticket_rejected`) plus string `params` —
+ beside their English `text`; the Web App and `penguin org channel tail` render them in the
+ reader's language with display names, and a kind the client does not know keeps the English.
+ Channel message bodies render as Markdown in the Web App.
+- Web: an organization opens on its overview (`/org/:projectId/:orgId` and the switcher both
+ land there); the pinned "New channel" slot became a "+" beside the channel list's title; a
+ deleted organization no longer strands the sidebar on an error (the nav rows go disabled
+ under a "New organization" prompt, and `/org` resolves to the next organization or to the
+ empty landing, now vertically centred); the create dialog offers three mission examples and
+ the language setting; the overview folds the mission, gives every summary card a jump button
+ instead of a whole-card click, and stacks the inbox (mentions, tickets in review and
+ blocked, the all-hands channel's latest messages), today's calendar and the alerts full
+ width; the empty calendar and board
+ keep one create button under a dismissible hint; the finance page lays the KPI panel beside
+ the trend, then the spend tree beside the ticket table, with the alerts last; and the
+ handbook's file list became an explorer tree with collapsible folders, keyboard navigation,
+ "collapse all" and a new document prefilled with the current folder.
+- Skills: `company-ceo`, `company-hr`, `company-employee` and `company-setup` restate that a
+ desk never does ticket work (it starts a ticket session), that goals, acceptance criteria,
+ progress lines and results name files by their full path, that rota warnings are fixed rather
+ than ignored, that everything is written in the organization's working language, and that a
+ relative workspace is created as it is assigned.
+
+### After the second trial round (2026-09-09)
+
+- A ticket change no longer starts a work run. Assigning an owner, blocking, a blocker
+ closing, done and rejected are recorded as before — the ticket file, the all-hands `system`
+ line where the change has one, the `org_ticket` event — and queued for the employees they
+ concern; the next calendar event of each carries them in its body under `## Since your last
+ sweep`, one line per change naming the ticket, its title, what happened and the reason or
+ blocker the ticket carries (`(ticket removed)` when its file is gone), and a closing line
+ saying what to decide: start a ticket session, verify and unblock, or leave it. A desk
+ session is driven by calendar events, channel mentions and people talking to it — the CEO's
+ creation-time initialization run is the one exception. A queue is written whether or not the
+ organization or the employee is paused and is delivered by the sweep that eventually fires;
+ an employee that leaves takes its undelivered lines with it. Migration 7 adds
+ `org_desk_notices`, the table that holds the queue. `ticket_notice` stays in `OrgTriggerKind`
+ because Traces recorded while it existed carry it; nothing writes it any more. The skills,
+ the handbook templates, the Company Mode guide and the server API reference say so.
+
+### After the third trial round (2026-09-09)
+
+- Company mode's sessions carry a durable marker. A desk or ticket session is created with
+ `client: "org"` on its index row and `SessionInfo` now serves the field, so development
+ mode's session list can leave those rows out whether or not the organization still exists
+ and whether or not company mode is switched on — the `orgId` stamp beside it is projected
+ from the organization caches, which are not read while the mode is off. Every reconcile
+ pass also stamps the sessions the organization's files name — the desk ledger, current and
+ previous, and the tickets' `Sessions` headers — so the sessions of organizations that
+ already exist are marked on the next pass, with no migration (the column exists and takes
+ free text). Sessions of organizations deleted before this change were never named by any
+ surviving file and stay unmarked; they read as development mode's own, and archiving or
+ deleting them is the only cleanup. The backfill and the rest of what this round tolerates
+ are recorded in [backward compatibility](2026-09-09-backward-compatibility.md).
+ `POST .../sessions` still accepts only `"web"` and `"cli"`: `"org"` is written by the
+ organization runtime, which calls the service directly, so no request can claim it.
+- "Generate with AI" always produces an id. `POST /organizations/suggest-id` ran its one-off
+ completion with thinking on and a 48-token cap, and a reasoning model spends its thinking out
+ of that same cap — the request ended at `finish_reason=length` before a single text token, and
+ a Chinese name, whose ASCII fallback is empty by construction, came back as
+ `422 id_not_derivable`. The completion now runs the way core's own out-of-band requests do:
+ thinking off, and the shared meta budget tightened by the entry's pinned per-model cap. An
+ answer that still yields no id buys one retry with the format spelled out, and a name neither
+ the model nor the ASCII slug can name is answered with `co_org_<yyyymmdd>` /
+ `ch_channel_<yyyymmdd>` — `source: "placeholder"` plus a `reason` (`no_default_model`,
+ `model_failed`, `unusable_answer`, `no_ascii`), which the dialog renders as a note asking for
+ a meaningful name in its place. The 422 and its `id_not_derivable` code are gone. Every model
+ dead end is now recorded as an `organization` / `id_suggest_failed` error and logged, instead
+ of being swallowed where nobody could see it.
+- Generated ids carry a prefix that says what they name: `co_` for an organization, `ch_` for
+ a channel. `POST /organizations/suggest-id` asks the model for the semantic core as before
+ and prefixes the answer itself — the ASCII-slug fallback too, before the length cap and the
+ `taken` check, and never twice when the core already starts with the prefix. The `company-setup`
+ skill proposes `co_<slug>`, and the CEO's and employees' channel examples read `ch_site`,
+ `ch_marketing`. The prefix is a convention the server proposes and does not enforce: an id
+ typed by hand is created exactly as written and existing ids keep working.
+- Only a ticket's owner, or a person, starts its sessions.
+ `POST /:orgId/tickets/:ticketId/start` now reads the caller: a person may start a session
+ for any ticket, naming the employee with `agentId`, while a caller writing as an employee
+ (a desk or ticket session quoting its own `sessionId`) may start one only for a ticket it
+ owns and gets `403 not_ticket_owner` for anyone else's — or for a ticket with no employee
+ owner — with the message telling it to assign the ticket instead and let that desk pick it
+ up in its next sweep. An owner may still pass `agentId` to enlist a colleague on its own
+ ticket, and `penguin org ticket start` gained `--agent-id` for exactly that; the command now
+ also sends `PENGUIN_SESSION_ID`, which is what identifies the employee behind it. The CEO
+ skill, the employee skill, the handbook templates, the CEO's initialization run, the Company
+ Mode guide, the server API reference and the CLI reference all describe the rule.
+- The organization overview's detail carries an `inbox`: the all-hands messages of the day's
+ window that mention the caller or `all` (newest first, at most 20), every ticket carrying a
+ `Blocked` reason whoever it waits on (newest first), and the tickets in `done` that closed in
+ the current budget period (newest first, at most 20), each with the `closedAt` its last
+ "moved … → done" progress line records. A ticket whose file was moved into `done` by hand has
+ no such line and is listed with no `closedAt` rather than hidden. `pending` and
+ `recentMessages` are unchanged.
+- An organization is never deleted through the product. `DELETE /api/projects/:p/organizations/:orgId`
+ is gone — the path answers 404 for everyone, the owner included, so a script that called it
+ fails instead of silently doing nothing — and the App's settings dialog has lost its delete
+ button and its confirmation. `status` (`active` / `paused`) is the whole lifecycle: pausing
+ stops every automatic trigger while every desk stays open to talk to, and the pause row's
+ "?" says so. Deleting an organization threw away the only way back to its conversations,
+ employees, desks and tickets. Removing the organization's directory by hand is the only way
+ one goes away, and that case is unchanged: the runtime stops seeing it on the next pass, the
+ App offers to create another in its place, and the Agents and sessions stay — the sessions
+ still marked as the organization's, so they never return to development mode's list. The
+ Company Mode guide and the server API reference say so.
+
+### The mirror-company example (2026-09-14)
+
+- A company can now mirror a real one. The new `company-mirror` skill of the `agent-company`
+ plugin is the protocol for an organization whose employees are digital twins of real
+ colleagues: the CEO's initialization run asks the board for the real org chart — name,
+ title, reporting line and which bot is whose — and ends there; once the board confirms the
+ roster it hires one twin per person with `--reports-to` mirroring the real line, writes each
+ twin's brief and each person's `people/<name>.md` handbook page, and reports the desk
+ sessions the board has to bind. Nothing recurring drives such a company: no calendar events,
+ no tickets, no per-stream channels. A twin runs when its own human writes through the bound
+ bot — it answers from the handbook when it can and otherwise relays the question with an
+ `@` to the right colleague's twin, which makes the question its run's final reply so the bot
+ delivers it — and everything that comes back is written into the handbook so the next such
+ question is answered alone. `company-ceo`'s init checklist and `company-employee`'s desk
+ section route a mirror mission here, and the CEO's initialization run says so in its first
+ line, in both languages.
+- The create-organization dialog and the empty company landing offer a fourth mission example,
+ 「员工数字分身公司」 / "Digital-twin company", whose mission is that mirror company. The
+ Company Mode guide gains a section on what it builds, and `company-setup` proposes it for a
+ user who describes their colleagues rather than work to produce.
+- No desk works in the shared workspace's root. The CEO's chart entry is now written with
+ `workspace: ceo`, and a hire given no `--workspace` gets a sub-directory named after its
+ Agent id instead of the root — the root holds the shared inputs every desk reads and is
+ nobody's desk. `.` is still accepted, it is simply never the default; `employee set
+ --workspace` keeps its meaning and moves a partition only when it is given one. Existing
+ organizations keep the `.` entries their charts already hold: nothing rewrites a chart, and
+ changing an employee's workspace opens a fresh desk session, so the move stays the CEO's to
+ make. The skills, the organization handbook template, the CEO's initialization run, the
+ Company Mode guide, the CLI reference and the server API reference all describe the rule.
+- **Company mode is off until an admin turns it on.** The master switch under System settings ›
+ Server › Company mode now reads off when no row was ever written, instead of on: a server
+ nobody has opted into company mode answers 404 on every organization route, reports
+ `companyMode: false` from `GET /api/me`, keeps the organization scheduler idle and draws no
+ mode switch. An install that never touched the switch had company mode on and now has it
+ off — nothing on disk changes, the organizations stay exactly as they are, and the scheduler
+ simply idles until an admin enables the switch again, which resumes without backfilling what
+ was missed while it was off. The Company Mode guide and the settings page's "?" say so.
+- **An employee's company plugins are kept current.** An Agent's plugins used to be written
+ once, at creation, and only the Agents page's manual per-Agent update ever rewrote them —
+ which is nobody's job in an organization that runs unattended, so a skill added to
+ `agent-company` (`company-mirror`, for instance) never reached the employees already hired.
+ Every reconcile pass now compares each employee's installed `agent-company` and
+ `agent-development` against the library's version and reinstalls the whole plugin where it
+ has fallen behind, the same update the Agents page performs, logging one line per update.
+ Nothing is written while the versions match, a plugin an employee does not carry is left
+ uninstalled, and an update that fails is recorded as an `org_plugin_update_failed` error
+ without stopping the pass. `company-employee` says the server keeps these skills current, so
+ no employee installs one by hand.
+
+### Tickets as frontmatter files (2026-09-14)
+
+- A ticket file is now YAML frontmatter followed by its prose. `title`, `status`, `owner`,
+ `parent`, `notify`, `priority`, `due`, `blocked`, `blocked_by`, `sessions` and `history` are
+ fields; the `# Ticket:` heading and the `Key: value` header block are gone, and fields this
+ server does not know survive a round trip. Tickets written in the old format are still read
+ and convert on their first write — see the
+ [backward-compatibility entry](2026-09-09-backward-compatibility.md).
+- **One owner.** `initiator` is gone from the file, the DTOs and the CLI. A ticket has exactly
+ one responsible principal, `owner`, which defaults to whoever filed it; `POST /tickets` takes
+ `owner` (no `initiator`), `PUT /tickets/:id` takes an `owner` that can be reassigned but never
+ cleared, and the default `notify` follows the owner — `[owner]` when an employee owns it, `[]`
+ when a person does. `penguin org ticket create --initiator` is removed.
+- **`## Progress` is prose.** A progress line is a plain sentence saying what was done and where:
+ no timestamp, no principal, no `session:` tag. `OrgTicketDetail.progress` is `string[]` and
+ `OrgTicketProgressEntry` is gone.
+- **Every write leaves one history entry.** `history` is the ticket's operation log, oldest
+ first: `created`, `assigned`, `moved`, `blocked`, `unblocked`, `progress`, `session_started`,
+ `session_attached`, `edited`, each with the time, the principal and a note. It is required on
+ `OrgTicketDetail`, and `penguin org ticket show` prints it under `History:` after the fields
+ and the prose sections. The overview's `closedAt` now comes from the last `moved`-to-`done`
+ entry instead of the progress log.
+- **Ticket ids carry meaning.** The slug is lowercase English words joined by hyphens, digits
+ dropped, at most six words. A title that yields fewer than two words — every title with no
+ Latin letters in it — is put to the Project's default model for a 2–5 word English slug, with
+ one retry; when there is no model or it cannot name it either, the write is refused with 400
+ `slug_required` and the caller passes `--slug`. A taken id takes a letter (`-b`, `-c`, …),
+ never a digit. `penguin org ticket create --slug <words>` is the explicit form and always wins.
+- **The operator is known from the Agent id.** Write bodies and the identity-carrying reads now
+ take `agentId` beside `sessionId` — the `PENGUIN_AGENT_ID` a Session hands its command
+ subprocesses — honoured only for a request carrying the local API token, like `sessionId`. An
+ `agentId` that names an employee wins over the calling session, so a command run from a nested
+ session or a subagent of an employee is still recorded as that employee. `POST
+ /tickets/:id/start` is the exception: its `agentId` names the employee the ticket session runs
+ as, not the caller.
+- **Ticket changes no longer write into the all-hands channel.** A closed, rejected or blocked
+ ticket used to post a `system` line there; now the employees it concerns hear about it in
+ their own next sweep, as before, and people read it on the board and in the overview's inbox.
+ A channel holds what people and employees say to each other, plus who joined and left and the
+ budget alerts — a board that narrates itself buries the conversation. Lines already written
+ still render; see the backward-compatibility entry.
+
+### company-setup joins the company plugin, and the master switch applies on the flip (2026-09-14)
+
+- **`company-setup` moved from `agent-development` to `agent-company`.** The skill that creates
+ an organization with the user now ships with the rest of company mode rather than with the
+ SDK and orchestration skills. `agent-company` is `preinstall: false`, so the consequence is
+ that `company-setup` is no longer on every Agent by default: an Agent gets it by installing
+ the company plugin — the Plugins field of the create-agent dialog, or the Skills tab of an
+ Agent already in the Project — while a CEO and its employees carry it from the day they are
+ hired, since hiring installs `agent-company`. `agent-development` is four skills again and
+ `agent-company` is six; the plugin's manifest, the Skills documentation, the company-mode
+ guide, the landing page's Skill list and the plugin library README follow.
+- **The admin's company-mode switch applies the moment it is flipped.** System settings ›
+ Server › Company mode has no Save button: the flip is the write (`PUT /api/admin/settings`),
+ the switch is disabled while the request is in flight, and a write that fails puts the switch
+ back on the stored value and names the reason on a line under it. The `?` explaining what the
+ master switch does is unchanged.
+
+### The company pages after user testing (2026-09-15)
+
+- **Titles are the links.** A card, row or panel is never a click target as a whole; its title
+ is — a text button that opens or jumps — and the rest of the surface stays inert. Ticket cards
+ open their drawer from the title and move by dragging anywhere else; inbox rows, today's
+ schedule and the budget alerts on the overview jump from their titles; rows without a title
+ (KPI cards) keep a small corner button. `test/company-click-targets.test.ts` parses the company
+ modules and fails a click handler, a `role="button"` or a `cursor-pointer` on a non-control
+ surface.
+- **Tickets show less and say more.** A card carries the title, priority, blocked and due chips, a
+ plain 「父工单:…」 line and the owner — no session count, no cost, and no live session status
+ anywhere in the ticket UI. The drawer names its costs 本单成本 / 总成本, shows the parent as a
+ labelled field with an open button, and folds three sections: 子工单 (rows with an open button,
+ the count and the total cost in the heading), 关联工单会话 (rows with an open button; the
+ start and attach controls left the drawer, the API and CLI keep them) and 操作历史 (time,
+ principal and action only).
+- **The finance ledger folds its children.** Child tickets hide under their parent until the
+ chevron opens them (the folded row says how many); the roll-up column is called 总成本 / Total
+ cost.
+- **The calendar names its empty slots.** An empty cell or hour slot tints with the accent colour
+ on hover or focus and shows 「新建日程」 on top of whatever the cell holds; the slot is a real
+ button under the events, so a click on an event never opens the create form. Filtering by one
+ employee strikes the others through in the legend.
+- **The handbook explorer is the shared file tree** — the same `FileTree` the conversation page's
+ Workspace browser and the plugin library draw, with the index pinned as the first row and the
+ document meta on the row's trailing edge.
+- **Company mode says it is a beta.** A 内测版 / Beta pill sits beside the name in the
+ organization switcher (the collapsed rail carries the same suffix on "Switch to company mode");
+ a line under the admin's master switch always reads "Beta: it may be unstable; please report
+ what you hit.", and the same sentence joins that page's `?`; the first switch into the mode in a
+ browser raises it once as a toast and never again (remembered in localStorage as
+ `penguin.companyBetaNoticeShown`).
+- **The ticket detail is a dialog, opened in place.** A centered window (the settings dialog's
+ shape) instead of a side drawer, mounted once on the company shell and opened from the board's
+ titles, the finance ledger, the overview's inbox and a channel message's ticket reference; a
+ parent or child row switches the dialog's ticket with a 「返回」 to come back, and the tickets
+ page keeps `?ticket=<id>` for deep links. Pages change only from the menu: the finance ledger
+ and channel ticket references no longer navigate; the overview keeps its cross-menu jumps (it
+ is the dashboard), and opening a Session still goes to the conversation page. The P0 / P1 / P2
+ chip sits after the title on the same line, one size smaller.
+- **A bare URL ends before a closing emphasis run.** `请**打开 http://127.0.0.1:4321/**查看`
+ used to put the `**` (and the CJK that follows) into the link; the autolink boundary pass now
+ trims trailing `*`, `~`, `` ` `` runs, a `_` run when the paragraph opened one, and an unmatched
+ `)` / `]` / `>`, handing them back to the text.
+- **The 内测版 tag** moved from the organization switcher onto the 「公司」 option of the
+ 开发 | 公司 switch, as a small superscript that does not change the control's size; the option's
+ accessible name reads 「公司 · 内测版」.
+- **An employee has a desk session from the moment it is hired.** `hire` opens it inside the
+ same lock that writes the chart — a Session, not a run, so nothing is dispatched — and the
+ hire still succeeds when opening it fails (the reason is recorded as `org_desk_unavailable`).
+ Each reconcile pass then provisions the desks that are missing: an employee added to
+ `org_chart.yaml` by hand, one hired before this, and one whose desk session row is gone
+ (deleted by hand, or with its Agent). A paused organization and a switched-off master switch
+ provision desks just the same. Before this, a desk was opened only on its employee's first
+ calendar trigger, mention or sidebar click, so a fresh hire's 工位 row named no Session and
+ a row left pointing at a deleted one answered "Session does not exist" when it was bound to
+ a messaging bot.
diff --git a/changelog/unreleased/2026-09-02-company-mode.zh.md b/changelog/unreleased/2026-09-02-company-mode.zh.md
new file mode 100644
index 00000000..ce5622f3
--- /dev/null
+++ b/changelog/unreleased/2026-09-02-company-mode.zh.md
@@ -0,0 +1,149 @@
+# 公司模式:由日程、工单看板与频道驱动的 Agent 组织
+
+- **Date:** 2026-09-02
+- **Type:** feature
+- **Scope:** `server`, `web`, `cli`, `core`, `skills`, `docs`
+- **PR:** [#587](https://github.com/Prism-Shadow/penguin-harness/pull/587)
+
+[English](2026-09-02-company-mode.md)
+
+Web App 新增第二种工作模式。公司模式下,一个 Project 的 Agent 组成一个**组织**:以 CEO 为根的汇报树,每位员工一个常设的**工位会话**,作为唯一周期性驱动的**日程**,承载工作的五列**工单看板**,只有 `@` 才会打扰到人的**频道**,以及按员工设定、80% 告警、100% 暂停该员工日程的月度**预算**。创建组织只需一句话使命,且只生成 CEO;CEO 在工位上的初始化会话里招募人事、财务与其余角色,划分公共工作区,为大家安排日程,开出首批工单。
+
+组织的每一部分都是 `<project>/organizations/<org_id>/` 下的文件:`org_config.toml`、`org_chart.yaml`(员工树,含各员工的预算、工作区与 Model)、`desks.toml`(服务端写入的工位台账)、`calendar/<agent_id>/<event>.toml`(去掉目标字段的定时任务格式)、`tickets/<yyyy-mm>/<列>/<yyyy-mm-dd>-<slug>.md`(取法 Agent Notes 的头部——Status、Initiator、Owner、Parent、Notify、Priority、Due、Blocked、Blocked-by、Sessions——以及 Goal、Acceptance criteria、Progress、Result 四节)、`channels/<channel_id>/`(一个频道一个目录:写有名称、用途与成员的 `channel.toml` 意图文件,以及按天分文件的 `<yyyy-mm-dd>.jsonl` 消息)与组织手册目录 `handbook/`(公司知识库,根部 `README.md` 是每轮触发先读的索引,其余文档在索引中列出、按需读取)。SQLite 只保存每轮对账都从这些文件重建的缓存(工位与工单会话的归属、日程运行状态、上次已通知的工单状态、各频道的扫描游标、预算标记)以及每个用户在各频道的已读游标。
+
+## 细节
+
+- 服务端:与定时任务调度器同构的组织调度器每 30 秒、以及每次 API 写入后立即对账每个组织——把台账与工单投影到缓存,为工作区被重新划分的员工换工位,把到期的日程项发往工位(工位忙则排队,组织或员工暂停时搁置,绝不补发),对工单变化只通知一次(指派、阻塞、阻塞解除、完成、拒绝——员工收到发往工位的通知,人收到全员频道里的系统消息),按组织的连锁上限投递频道内的 @ 提及,并重算预算。每次触发都是一条以 `[org_trigger]` 块开头的用户输入;工单会话是员工 Agent 的普通会话,会话 id 追加到工单头部的 `Sessions` 字段。支出按会话归属:员工成本 = 本人会话加全部下属,工单成本 = 其贡献会话在所服务工单之间均分后的份额,沿 `Parent` 上卷。
+- API:`/api/projects/:projectId/organizations` 及其子路由——员工树、员工、工位、手册、日程、工单(移列、阻塞、解除、进展、发起、挂接)、频道(成员、消息与已读游标)、财务与组织会话列表;用户级事件 `org_run`、`org_channel`、`org_ticket`、`org_budget`。Project 成员可读写,仅 owner 可删除。迁移 6 新增七张组织表。
+- 开关:管理员总开关(服务器设置的 `companyMode`,缺省开;关闭即停止调度器、组织路由回 404、隐藏模式切换,并由 `GET /api/me` 报告)、`ui_prefs` 里的个人开关,以及组织自己的 `status: paused`。
+- 控制环境:工位与工单会话的命令子进程额外获得 `PENGUIN_ORG_ID`,在会话内 `penguin org` 不必再传 `--org-id`。
+- Core:标记清单新增 `[org_trigger]`(与 `[scheduled_task]` 同属标题噪声),并提供 `buildOrgTriggerMessage` / `parseOrgTriggerMessage`。
+- CLI:`penguin org` 命令族——`ls`、`create`、`show`、`chart`、`hire`、`employee set`、`leave`、`desk show|renew`、`calendar ls|add|update|rm`、`ticket ls|show|create|move|assign|block|unblock|progress|start|attach`、`channel ls|create|show|invite|join|leave|remove|archive|unarchive|tail|send`(`--channel` 缺省 `default_channel`)、`handbook list|show|write|rm`、`finance`——作为 API 的瘦客户端,处处支持 `--json`。
+- Web:Project 切换器上方的「开发 | 公司」模式切换、带新建与设置的组织切换器、六个导航页面(概览、组织图、日历、工单、财务、手册——以文件列表加渲染正文呈现知识库,支持就地编辑、新建与删除)以及频道视图;开发模式列出会话的位置,公司模式列出「频道」(全员频道置顶、我的频道、其他频道带「加入」、已归档折叠),另有对话中的 `[org_trigger]` 横幅与设置页上的两个开关。频道列表之下是组织自身的两个分组:「工位」按组织图顺序一位员工一行,默认展开,点击打开该员工的工位会话——没有就现开一个;「工单会话」默认折叠,把挂在工单上的会话按最近活动排在前面,工单标题作为副标题。收起后的窄栏把工位画成头像,运行中的带一个圆点。工位会话与工单会话就是**普通对话**——消息列表、工具卡片、审批与输入区都与开发模式相同——外面套公司模式的侧栏,并在分组里标出当前那一行;公司模式没有自己的对话视图。这类对话打开时,侧栏显示的组织仍是当前组织,频道与工位不会在 `/chat/:sessionId` 上变空。新建组织对话框会把填过的内容按用户与 Project 存成 `localStorage` 草稿:误关、刷新或切换模式后重开即恢复,创建成功或点「清空草稿」后清除;对话框里还多了 CEO 预算字段。频道里,@到自己的消息只由提及标记标出(整行底色去掉),跳数标记从第 2 跳起才显示(第 1 跳是员工回应一次触发,说明不了什么),输入框与「发送」按钮等高同排、底边对齐,输入框变高时按钮仍贴着底边。
+- 创建选项:新建组织时可指定 **Model**(已配置的成对引用,员工条目未指定时工位与工单会话都用它)与**公司工作区**(一个已存在的绝对目录,替代组织目录内的 `workspace/` 作为公共工作区);二者都是 `org_config.toml` 的字段,可在组织设置里修改,也可经 `penguin org create --workspace … --model-id … --provider …` 指定。
+- 决策关口:CEO 只提案、董事会拍板——初始化会话先发一份完整提案(使命理解、首批工单、招募角色及预算与 Model、工作区划分)并结束本轮;招募、预算、拒绝他人的工单、跳过审核关闭 P0/P1 工单、任何触及组织之外的动作以及结构变更都要等创建者在全员频道里确认。员工把这类事项上报给 CEO。写进 `company-ceo` / `company-employee` Skill、初始化会话与组织手册。
+- 组织手册是一个目录 `handbook/`,也是公司知识库:根部 `README.md` 是每次触发都指向的索引(目录布局、协议、职责约定,以及一份文档清单——每份一行,写明何时需要读);董事会决策、约定与操作指南以 Markdown 文档放在旁边、按需读取。API 可列出、读写与删除文档,会话里用 `penguin org handbook list | show | write | rm` 做同样的事,Web App 的「手册」页可浏览、编辑与新建;索引不可删除。
+- 排班规则:CEO / 人事 Skill、初始化会话与组织手册把日程当作排班表——按角色定节奏(CEO 每日、人事每三天、财务每周)、每位员工各占一个时刻、每人只有一条常设日程项、绝不 `--start-at now`。
+- 插件:新增独立分类(Agent Company / Agent 公司)下的 `agent-company` 插件(`preinstall: false`),携带 `company-employee`、`company-ceo`、`company-hr`、`company-finance` 四个 Skill;CEO 与每位招募的 Agent 都会连同 `agent-development` 一起安装它。
+- 频道:组织的沟通是一组频道,每个频道是 `channels/` 下的一个目录,带一份 `channel.toml` 意图文件。`default_channel` 是随组织创建的全员频道,全体员工与全体 Project 成员隐式在其中,预算告警、发给人的工单通知与招募通知都落在这里。人和员工都可以再开频道;新频道只有创建者一人,员工只能由成员邀请进入,人可以自行加入任何频道并读到全部频道。投递遵循成员关系:`@agent:<id>` 只在频道成员范围内唤醒工位,`@all` 指该频道成员(不含发送者),提及非成员的消息在写入前即以 `mention_not_member` 拒收。`kind: mention` 的 `[org_trigger]` 块带一行 `channel:`,员工因此回到被 @ 的那个频道作答。归档(仅限人)使频道只读;全员频道不能归档、不能退出、成员不可编辑。扫描游标与每个人的已读游标都按频道计算——迁移 7 把两张表重建为 `org_channel_state` 与 `org_channel_reads`。CLI 侧是 `penguin org channel` 命令族;Web App 的公司模式以频道为主列表,工位会话与工单会话在其下各成一组。
+- CEO 预算:创建时把 CEO 的月预算写进 `org_chart.yaml`——不另行指定即为 100 美元(创建请求的 `ceoBudget`、`penguin org create` 的 `--ceo-budget`、创建对话框里的 CEO 预算字段)。预算按累计线比较,所以这一个数字从第一分钟起就是整家公司的上限,而不是任其无限;初始化会话的触发块会带上它,CEO 据此裁剪自己的招募方案。之后在组织图上随时可调高、调低或清除。
+- 引导式创建:`company-setup`——`agent-development` 插件下的一个 Skill,而 `default_agent` 本就装有该插件,于是「让通用 Agent 帮我开一家公司」成为一条创建路径。它用用户的语言一次只问一个问题,依次收集 id、名称、使命、公共工作区、Model 与 CEO 预算,给出一屏摘要,等到明确的确认后执行 `penguin org create`,再把用户交接给公司模式。它自己从不招募、不排日程、不开工单——那是 CEO 在董事会答复提案之后的事。
+- 组织的会话不进开发模式:会话 DTO 新增 `orgId`——工位会话,或参与该组织某个工单的会话,所属的组织,取自组织缓存(每次列表一次查询,而不是每行一次),会话列表与 `GET /api/sessions/:sessionId` 都带上它。开发模式的会话列表与时间分组一律隐藏带有该字段的会话,原先收纳它们的「组织」子夹随之删除——公司模式的「工位」「工单会话」分组才是它们的去处。隐藏以该用户能用公司模式为前提(管理员总开关与用户自己的开关):`orgId` 无论开关如何都会写上,公司模式关闭时没有别的地方列出这些会话。分组标题与「还有 N 个」一并减去被隐藏的部分,分组不会承诺自己画不出来的行。
+- 文档:新增「公司模式」指南(含 Marketplace 案例走读)、`penguin org` 参考,以及服务端 API 参考里的组织路由。
+
+### 第一轮试用之后(2026-09-08)
+
+- 工作语言:`org_config.toml` 新增 `language`(`zh` / `en`),创建时若请求未指定则从使命判定(正文里出现任一汉字即 `zh`)——`POST /organizations` 与 `PATCH /:orgId` 的 `language`、`penguin org create --language <zh|en>`,以及 Web App 组织设置里的「工作语言」下拉;`penguin org show` 会打印它。组织手册索引、CEO 的初始化会话、员工简介(`AGENTS.md`)与工位会话标题都按它渲染,Skill 也要求每位员工用它写消息、工单、文档与汇报。该字段出现之前写下的组织没有存这一项,读作它使命本身的语言,未做任何迁移。
+- 相对工作区子目录会被创建:`hire` 与 `employee set` 的 `--workspace hr`(或 `./hr`)先归一化为 `hr`,缺失时在公共工作区下建出;绝对路径仍须已经存在;用 `..` 爬出公共工作区的写法回 400 `invalid_workspace`。打开工位会话与工单会话时同样会补建该目录,手工改过的员工树不会因为少一个目录而让员工无法开工。
+- `POST /api/projects/:projectId/organizations/suggest-id`——`{name, kind: "org" | "channel", taken?}` → `{id, source: "model" | "fallback"}`:Project 的缺省 Model 提出一个简短的英文 snake_case id,模型给不出时以名称的 ASCII slug 兜底,两条路都命名不了则回 422 `id_not_derivable`;该次补全不属于任何 Session,也不计量。Web App 的新建组织与新建频道对话框把显示名放在前面,并带一个据名称生成 id 的按钮。
+- 日程写入会附带排班建议:`POST /:orgId/calendar`、`PUT /:orgId/calendar/:agentId/:name` 与 `penguin org calendar add | update` 在写下的事件之外返回一组建议性的 `warnings`——同一起始分钟上已有另一位员工的常设日程项、同一员工已有同周期的常设日程项、常设日程项以 `now` 起算。CLI 以「排班提醒:」逐行打印,Web 的日历对话框在起始时间下给出错峰提示并把这些警告弹成 toast,CEO 与人事 Skill 要求把它们改掉而不是略过。
+- 工单:`--initiator <agent_id|principal>`(创建请求体的 `initiator`)可以以某位员工或某位 Project 成员的名义开工单——它成为 `Initiator`、「created the ticket」那条进展的作者,并在发起人是员工时成为缺省的 `Notify`:人开的工单在完成时不再 @ 他(想收到通知就把自己写进 `--notify`;那条完成的系统消息照样发进全员频道)。会话写下的一条进展、正文编辑或移入 `review`,会把该会话记为这张工单的贡献会话,成本因此落到工单上;接受、关闭、阻塞与解除阻塞都不记。`ticket_work` 会话以一行 `Workspace:` 与「一切引用与交付物都写完整路径」的规则开场,`assigned` 与 `blocker_closed` 两种通知则以下一步要执行的 `penguin org ticket start` 命令收尾。
+- 频道的 `system` 消息在英文 `text` 之外带一份结构化 `notice`——一个 `kind`(`employee_joined`、`employee_left`、`channel_created`、`channel_archived`、`channel_unarchived`、`channel_joined`、`channel_invited`、`channel_left`、`channel_removed`、`budget_warned`、`budget_paused`、`ticket_blocked`、`ticket_done`、`ticket_rejected`)加一组字符串 `params`;Web App 与 `penguin org channel tail` 据此按读者的语言、用显示名渲染,客户端不认识的种类保留英文原文。频道消息正文在 Web App 里按 Markdown 渲染。
+- Web:组织打开时落在概览(`/org/:projectId/:orgId` 与组织切换器都到这里);置顶的「新建频道」槽位改为频道列表标题旁的「+」;组织被删除后侧栏不再停在错误上(导航行置灰,并给出「新建组织」的入口,`/org` 解析到下一个组织或空态落地页——落地页现在垂直居中);创建对话框给出三个使命示例与工作语言设置;概览折起使命,把整卡点击换成每张摘要卡自己的跳转按钮,并把收件箱(@ 我、待审核与被阻塞的工单、最近消息)、今日日程、告警三段通栏堆叠;空的日历与看板只留一个新建按钮,下方提示可永久关掉;财务页把 KPI 面板与趋势排成一行,支出树与工单表左右分列,告警放在最后;手册的文件清单改为资源管理器式的树,支持折叠文件夹、键盘导航、一键全部折叠,新建文档预填当前文件夹。
+- Skill:`company-ceo`、`company-hr`、`company-employee` 与 `company-setup` 重申——工位绝不亲自做工单(改为发起工单会话)、目标与验收标准与进展与结果里的文件一律写完整路径、排班警告必须改掉而不是略过、一切以组织的工作语言书写、相对工作区在指定时即被创建。
+
+### 第二轮试用之后(2026-09-09)
+
+- 工单的变化不再启动任何一轮运行。指派负责人、标记阻塞、阻塞解除、完成、拒绝,仍照旧记录——写进工单文件、该变化在全员频道有系统消息时写进全员频道、并发出 `org_ticket` 事件——同时排入相关员工的队列;每人的下一条日历事件在正文的 `## Since your last sweep` 一节里带上它们:一条变化一行,写明工单、标题、发生了什么,以及工单自身带的理由或阻塞方(文件已不在时写 `(ticket removed)`),最后一行说明该怎么决定——发起工单会话、核验后解除阻塞,或者放着不动。驱动工位会话的只有日程项、频道里的提及与直接找它说话的人,CEO 创建时的初始化运行是唯一例外。组织或员工处于暂停时队列照样写入,由此后真正触发的那次巡检送达;员工离职时,尚未送达的行随之删除。迁移 8 新增存放该队列的 `org_desk_notices` 表。`ticket_notice` 仍留在 `OrgTriggerKind` 中,因为它存在期间写下的 Trace 带着它;现在已没有任何地方再写出这种触发。Skill、组织手册模板、公司模式指南与服务端 API 参考都已照此叙述。
+
+### 第三轮试用之后(2026-09-09)
+
+- 公司模式的会话带上了持久标记。工位会话与工单会话在创建时就写下索引行的 `client: "org"`,`SessionInfo` 也开始返回该字段,于是无论组织是否还在、公司模式是否打开,开发模式的会话列表都能把这些行排除在外——与之并列的 `orgId` 是组织缓存的投影,模式关闭时不再读取。每一轮对账还会给组织文件点名的会话补上这个标记:工位台账里的当前会话与历史会话,以及各工单 `Sessions` 头部里的会话。因此已经存在的组织,其会话在下一轮对账时被标记,且无需迁移(该列本就存在,且是自由文本)。本次改动之前就已删除的组织,其会话不再被任何文件点名,因而保持未标记状态:它们读作开发模式自己的会话,只能靠归档或删除来清理。`POST .../sessions` 仍只接受 `"web"` 与 `"cli"`:`"org"` 由直接调用服务的组织运行时写入,任何请求都无法声称自己是它。回填与本轮容忍的其余旧形态见[向后兼容](2026-09-09-backward-compatibility.zh.md)。
+- 「用 AI 生成」一定给得出 id。`POST /organizations/suggest-id` 背后的一次性补全此前开着思考、输出上限只有 48 token,而推理模型的思考正是从同一个上限里扣的——请求在吐出第一个正文 token 之前就以 `finish_reason=length` 结束,中文名称的 ASCII 兜底又天然为空,于是回的是 `422 id_not_derivable`。该补全现在与 core 自己的带外请求一致:关闭思考,使用共享的元请求预算,并按条目上钉住的 per-model 上限收紧。回答仍拼不出 id 时,会带上「只回答标识符本身」的格式要求再问一次;Model 与 ASCII 兜底都命名不了的名称,则回一个 `co_org_<yyyymmdd>` / `ch_channel_<yyyymmdd>`——`source: "placeholder"` 并附 `reason`(`no_default_model`、`model_failed`、`unusable_answer`、`no_ascii`),对话框据此在字段下方提示改成有含义的名字。422 与 `id_not_derivable` 这个 code 已移除。Model 一侧的每一次落空现在都会写入日志并记为 `organization` / `id_suggest_failed` 错误,不再被无声吞掉。
+- 自动生成的 id 带上了表明其所指的前缀:组织 `co_`,频道 `ch_`。`POST /organizations/suggest-id` 仍照旧向 Model 要语义词干,前缀由服务端自己补上——ASCII slug 兜底路径同样如此,都在截长度与避开 `taken` 之前进行;词干本就以该前缀开头时不会补第二遍。`company-setup` Skill 提议 `co_<slug>`,CEO 与员工 Skill 里的频道示例改为 `ch_site`、`ch_marketing`。前缀只是服务端提议、并不强制的约定:手工输入的 id 一律按原样创建,既有 id 继续有效。
+- 一张工单的会话只能由它的负责人或人发起。`POST /:orgId/tickets/:ticketId/start` 现在会看调用方:人可以为任何工单发起会话,用 `agentId` 指定员工;而以员工身份写入的调用方(工位会话或工单会话在请求体里带上自己的 `sessionId`)只能为自己名下的工单发起,对别人的工单——以及没有员工负责人的工单——一律回 `403 not_ticket_owner`,错误文案提示改用改派,由那名员工的工位在下一次巡检时接手。负责人仍可用 `agentId` 把同事拉进自己名下的工单,`penguin org ticket start` 为此新增了 `--agent-id`;该命令现在同时发送 `PENGUIN_SESSION_ID`,服务端据此识别背后的员工。CEO Skill、员工 Skill、组织手册模板、CEO 的初始化运行、公司模式指南、服务端 API 参考与 CLI 参考都已照此叙述。
+- 组织概览的详情新增 `inbox`:当日窗口内全员频道里 @ 了调用方或 `all` 的消息(最新在前,最多 20 条)、所有带 `Blocked` 理由的工单——无论它在等谁(最新在前),以及本预算周期内关闭的 `done` 工单(最新在前,最多 20 条),每条带上其最后一行「moved … → done」进展所记录的 `closedAt`。手工把文件移进 `done` 的工单没有这样一行,于是列出时不带 `closedAt`,而不是被隐藏。`pending` 与 `recentMessages` 保持不变。
+- 组织不再能通过产品删除。`DELETE /api/projects/:p/organizations/:orgId` 已移除——该路径对所有人(包括 owner)都回 404,于是仍在调用它的脚本会失败,而不是默默什么也没做——App 的组织设置对话框也去掉了删除按钮与那层确认。`status`(`active` / `paused`)就是它的全部生命周期:暂停会停止一切自动触发,而每个工位仍开着可以对话,暂停一行的「?」也照此说明。删除组织会把回到它的对话、员工、工位与工单的唯一入口一并丢掉。手工删掉组织目录是组织唯一的消失方式,这一情形不变:运行时在下一轮对账时不再看见它,App 给出新建一个的入口,Agent 与会话都保留——会话上「属于该组织」的标记仍在,因此不会回到开发模式的列表。公司模式指南与服务端 API 参考都已照此叙述。
+
+### 镜像公司示例(2026-09-14)
+
+- 公司现在可以镜像一家现实公司。`agent-company` 插件新增的 `company-mirror` Skill 是这样一家组织的协议——它的员工是现实同事的数字分身:CEO 的初始化运行向董事会索要现实公司的组织图(姓名、头衔、汇报线,以及哪个机器人归谁),然后就结束本轮;董事会确认花名册之后,才为每人招募一个分身,`--reports-to` 照搬现实汇报线,并写下每个分身的简介与每个人的 `people/<姓名>.md` 手册页,最后汇报董事会需要去绑定的那些工位会话。这样的公司没有任何周期性驱动:不排日程、不开工单、不按工作线开频道。分身只在自己的同事通过绑定的机器人写来消息时运行——能从手册里答就答,答不了就用 `@` 把问题转给相关同事的分身,对方把这个问题作为本轮的最后一句回复,由机器人送达真人——带回来的答复一律写进手册,下次同样的问题就能自己答掉。`company-ceo` 的初始化清单与 `company-employee` 的工位一节都会把镜像使命引到这里,CEO 的初始化运行也在第一句就这么说,中英皆然。
+- 新建组织对话框与公司模式的空状态落地页新增第四个使命示例「员工数字分身公司」(英文 “Digital-twin company”),其使命正是这样一家镜像公司。公司模式指南新增一节讲它建出来的是什么;`company-setup` 在用户谈的是自己的同事、而不是要产出的活时,会主动提议它。
+- 公共工作区的根目录不再是任何人的工位。CEO 的组织图条目现在写入 `workspace: ceo`;招募时不给 `--workspace` 的员工,落在以其 Agent id 命名的子目录里,而不是根目录——根目录放的是每个工位都要读的共享输入,不是谁的工位。`.` 依然接受,只是不再是缺省值;`employee set --workspace` 语义不变,只有给出时才改动分区。已存在的组织保留其组织图里已有的 `.` 条目:没有任何环节会改写组织图,而改动某名员工的工作区会开一个新的工位会话,因此要不要搬由 CEO 自己决定。各 Skill、组织手册模板、CEO 的初始化运行、公司模式指南、CLI 参考与服务端 API 参考都已照此叙述。
+- **公司模式缺省关闭,由管理员打开。** 系统设置 › 服务器 › 公司模式这个总开关,在从未写过设置的服务器上现在读作关闭,而不是打开:没有主动启用公司模式的服务器,所有组织路由回 404,`GET /api/me` 返回 `companyMode: false`,组织调度器保持空转,模式切换也不绘制。此前从未动过这个开关的安装,公司模式本是打开的,本次改动之后变为关闭——磁盘上什么也不改,组织原样保留,调度器只是空转到管理员重新打开为止;重新打开不会补发关闭期间错过的触发。公司模式指南与设置页的「?」都已照此说明。
+- **员工装着的公司插件会被保持在当前版本。** Agent 的插件此前只在创建时写入一次,之后只有 Agents 页面上逐个 Agent 的手工更新会重写它——而在无人值守运转的组织里没人会去点,于是 `agent-company` 新增的 Skill(例如 `company-mirror`)永远到不了早已在岗的员工身上。现在每一轮对账都会把每位员工装着的 `agent-company` 与 `agent-development` 与插件库的版本比对,落后的整包重装——与 Agents 页面执行的是同一次更新——每次更新记一行日志。版本一致时不写任何文件;员工本就没装的插件不会被装上;某次更新失败记为 `org_plugin_update_failed` 错误,不中断该轮对账。`company-employee` 已写明这些 Skill 由服务端保持最新,员工不必自行安装。
+
+### 工单改为 frontmatter 文件(2026-09-14)
+
+- 工单文件现在是 YAML frontmatter 加正文。`title`、`status`、`owner`、`parent`、`notify`、
+ `priority`、`due`、`blocked`、`blocked_by`、`sessions`、`history` 都是字段;`# Ticket:` 标题行与
+ `Key: value` 头部块取消,本版本不认识的字段原样保留。旧格式的工单仍可读取,并在第一次被写入时完成
+ 转换——见[向后兼容条目](2026-09-09-backward-compatibility.zh.md)。
+- **负责人只有一个。** `initiator` 从文件、DTO 与 CLI 中彻底移除。一张工单只有一个责任人 `owner`,
+ 缺省是创建它的人;`POST /tickets` 收 `owner`(不再有 `initiator`),`PUT /tickets/:id` 的 `owner`
+ 可以改派但不能清空,`notify` 的缺省跟着负责人走——负责人是员工时为 `[owner]`,是人时为 `[]`。
+ `penguin org ticket create --initiator` 已移除。
+- **`## Progress` 是大白话。** 一条进展就是一句话:做了什么、东西在哪。不写时间、不写主体、不写
+ `session:` 标记。`OrgTicketDetail.progress` 变为 `string[]`,`OrgTicketProgressEntry` 已删除。
+- **每次写入留下一条 history。** `history` 是工单的操作日志,最早的在前:`created`、`assigned`、
+ `moved`、`blocked`、`unblocked`、`progress`、`session_started`、`session_attached`、`edited`,
+ 每条带时间、主体与备注。它在 `OrgTicketDetail` 上是必填字段;`penguin org ticket show` 在字段与
+ 正文各节之后以 `History:` 打印它。组织概览的 `closedAt` 改从最后一条「moved 到 done」的 history
+ 条目读取,不再依赖进展日志。
+- **工单 id 说得出意思。** slug 是用连字符连接的小写英文单词,丢掉数字,最多六个词。标题推不出两个
+ 词时——任何不含拉丁字母的标题都是如此——交给 Project 的缺省模型取一个 2–5 词的英文 kebab-case
+ slug,失败重试一次;没有模型或模型也取不出,则以 400 `slug_required` 拒绝,请调用方传 `--slug`。
+ id 撞车时加的是字母后缀(`-b`、`-c`……),绝不是数字。`penguin org ticket create --slug <words>`
+ 是显式写法,且永远优先。
+- **操作者由 Agent id 认出。** 写入体与需要身份的读取现在在 `sessionId` 之外还接受 `agentId`——会话
+ 发给其命令子进程的 `PENGUIN_AGENT_ID`——与 `sessionId` 一样,仅对携带本机 API token 的请求生效。
+ `agentId` 指向某名员工时优先于调用会话,于是员工的嵌套会话或子 Agent 里跑出的命令仍记在该员工名下。
+ `POST /tickets/:id/start` 是例外:它的 `agentId` 指的是工单会话以谁的身份运行,不是调用方。
+- **工单的变化不再写进全员频道。** 工单完成、被拒或被阻塞,过去会在全员频道留下一条 `system` 行;
+ 现在与之相关的员工仍在各自下一次巡检里看到,而人则在看板与组织概览的 inbox 里读到。频道装的是人和
+ 员工彼此说的话,加上谁来了谁走了和预算告警——一块自己讲述自己的看板只会把对话淹掉。已经写下的行照常
+ 渲染,见向后兼容条目。
+
+### company-setup 并入公司插件,总开关拨动即生效(2026-09-14)
+
+- **`company-setup` 从 `agent-development` 移入 `agent-company`。** 与用户一起创建组织的这个
+ Skill,现在与公司模式的其余部分同包,而不再与 SDK、编排类 Skill 放在一起。`agent-company` 是
+ `preinstall: false`,因此随之而来的变化是:`company-setup` 不再缺省装在每个 Agent 上——想让某个
+ Agent 能创建组织,就给它装上公司插件(新建 Agent 对话框的「插件」字段,或 Project 里既有 Agent 的
+ 技能标签页);而 CEO 与员工自受雇之日起就带着它,因为招募本来就会装 `agent-company`。于是
+ `agent-development` 回到四个 Skill,`agent-company` 变为六个;插件清单、Skill 文档、公司模式指南、
+ 落地页的 Skill 列表与插件库 README 一并跟上。
+- **管理员的公司模式开关拨动即生效。** 系统设置 › 服务器 › 公司模式不再有保存按钮:拨动即写入
+ (`PUT /api/admin/settings`),请求在途期间开关禁用,写入失败则把开关拨回服务端存着的值,并在其
+ 下方以一行说明原因。解释总开关作用的「?」不变。
+
+### 用户试用后的公司页面(2026-09-15)
+
+- **标题即链接。** 卡片、行、面板整体从来不是点击目标,它的标题才是——一枚文字按钮,点它
+ 展开或跳转,其余表面惰性。工单卡片点标题开抽屉、拖动其他任何地方即移动;概览的收件箱、
+ 今日日程、预算告警都从标题跳转;没有标题的行(KPI 卡)保留角落小按钮。
+ `test/company-click-targets.test.ts` 解析公司模式各模块,非控件表面上的点击处理、
+ `role="button"` 或 `cursor-pointer` 一律判失败。
+- **工单显示得更少、说得更清楚。** 卡片只有标题、优先级 / 阻塞 / 截止角标、一行「父工单:…」
+ 与负责人——不写会话数、不写成本,工单界面任何地方都不再显示会话的运行状态。抽屉把成本叫
+ 本单成本 / 总成本,父工单是带「打开」按钮的字段,其下三节折叠:子工单(行尾打开按钮,节标题
+ 带数量与总成本)、关联工单会话(行尾打开按钮;发起与挂接的入口移出抽屉,API 与 CLI 仍在)、
+ 操作历史(只有时间、主体、操作类型)。
+- **财务台账折叠子工单。** 子工单缺省藏在父工单之下,点 chevron 才展开(折叠行写明几张);
+ 上卷列改称「总成本」。
+- **日历给空格子起名。** 空的日格或小时格悬停 / 聚焦时以强调色铺底,并在最上层显示
+ 「新建日程」;格子是位于日程之下的真按钮,点日程永远不会误开新建表单。按某位员工筛选后,
+ 图例里其余员工加删除线。
+- **手册目录就是共享的目录树**——与对话页 Workspace 浏览、插件库同一个 `FileTree` 组件,
+ 索引固定为第一行,文档的大小与修改时间在行尾。
+- **公司模式标明自己是内测功能。** 组织切换器的名字旁多了一枚「内测版」标签(折叠侧栏则在
+ 「切换到公司模式」的提示后加同样的后缀);管理员总开关下方常驻一行「内测功能:可能有不稳定
+ 的现象,遇到问题请反馈。」,同一句也进了该页的「?」;第一次在某个浏览器里切到公司模式时,
+ 这句话以 toast 弹一次,之后不再出现(记在 localStorage 的 `penguin.companyBetaNoticeShown`)。
+- **工单详情是原地打开的对话框。** 居中窗口(同设置界面的形态),不再是侧栏抽屉;挂在公司壳上
+ 只有一个,看板标题、财务台账、概览收件箱、频道消息里的工单引用都从原地打开它;父 / 子工单
+ 在同一对话框内切换、带「返回」;工单页保留 `?ticket=<id>` 供直达。切页只从菜单发生:财务台账与
+ 频道工单引用不再跳页;概览保留跨菜单跳转(它是仪表盘),打开会话仍去对话页。P0 / P1 / P2
+ 角标紧跟标题同一行、字号小一号。
+- **裸 URL 止于结尾的强调标记。** `请**打开 http://127.0.0.1:4321/**查看` 过去会把 `**`(连同后面
+ 的中文)吞进链接;autolink 边界处理现在裁掉尾部的 `*`、`~`、`` ` `` 串、段落里开过的 `_` 串,
+ 以及无配对的 `)` / `]` / `>`,交还给正文。
+- **「内测版」角标**从组织切换器移到「开发 | 公司」切换里「公司」二字的右上角,小号上标、不改变
+ 控件尺寸;该选项的可访问名为「公司 · 内测版」。
+- **员工自受雇起就有工位会话。** `hire` 在写组织图的同一把锁里把工位开出来——开的是会话、
+ 不是运行轮,因此不派发任何触发——开失败也不影响招募成功(原因记为
+ `org_desk_unavailable`)。此后每轮对账都会为缺工位的员工补开:手工写进 `org_chart.yaml`
+ 的人、此前招募的人,以及工位会话记录已被删掉的人(手工删会话,或随 Agent 一起删)。
+ 暂停的组织与关掉的总开关同样照补。在此之前,工位只在该员工第一次被日程触发、被提及或
+ 被点开侧栏时才打开,于是新招的员工的「工位」行没有会话可指,而指着已删会话的行在绑定
+ 聊天机器人时会答「该 Session 不存在」。
diff --git a/changelog/unreleased/2026-09-09-backward-compatibility.md b/changelog/unreleased/2026-09-09-backward-compatibility.md
new file mode 100644
index 00000000..7a3bc48b
--- /dev/null
+++ b/changelog/unreleased/2026-09-09-backward-compatibility.md
@@ -0,0 +1,88 @@
+# Backward compatibility: company mode's trial rounds
+
+- **Date:** 2026-09-09
+- **Type:** process
+- **Scope:** `server`
+- **PR:** [#587](https://github.com/Prism-Shadow/penguin-harness/pull/587)
+
+[中文版](2026-09-09-backward-compatibility.zh.md)
+
+[Company mode](2026-09-02-company-mode.md) reached its trial rounds with organizations already
+on disk, so five of its later changes had to meet data written before them. None needs a
+migration and none asks the user to do anything; this file says what each one tolerates and
+which of them is a shim with an expiry.
+
+## `sessions.client = "org"`: stamped on creation, backfilled by reconcile
+
+Desk and ticket sessions are now written with `client = "org"` on their `sessions` row, and
+development mode's list hides such rows whether or not the organization still exists or
+company mode is on. Sessions that predate the change carry `web`, `cli` or nothing. Every
+reconcile pass therefore stamps the rows the organization's files name — `desks.toml`
+(current and previous desks) and the tickets' `Sessions` headers — with one idempotent
+`UPDATE … WHERE client IS NOT 'org'`, so every existing organization is marked on the next
+pass after the upgrade.
+
+What stays unmarked: the sessions of an organization deleted **before** this change. No file
+names them any more, so they read as development mode's own until archived or deleted by hand.
+Accepted: the alternative was guessing from session titles.
+
+**This is a shim with an expiry.** The backfill costs one cheap statement per reconcile pass
+and can be dropped once every install has reconciled on a build that carries it — that is,
+from the release after the one that ships it. Whoever bumps the company-mode migrations next
+removes the backfill call in `reconcile.ts` (`markOrgClient`) and its test.
+
+## `language` absent from `org_config.toml`
+
+Organizations created before the working-language field have no `language` line. The server
+reads the language from the mission at read time (a Han character anywhere → `zh`, else
+`en`), so nothing is rewritten and nothing is migrated; the field is written by creation and by
+the settings dialog from now on. Not a shim: the fallback is the field's defined default.
+
+## Channel lines without `notice`
+
+System lines written before the structured notice carry only their English `text`. Every
+reader falls back to that text when `notice` is absent, and the file format accepts both.
+Nothing to remove.
+
+## `ticket_notice` in old Traces
+
+The scheduler no longer produces `kind: ticket_notice` work runs; the marker parser still
+accepts the kind so an older Trace's `[org_trigger]` blocks fold and render as before. The
+enum member stays for as long as those Traces are read. Nothing to remove on a schedule.
+
+## Ticket files in the format that predates the frontmatter
+
+Tickets are now YAML frontmatter plus prose. Every ticket written before that is
+`# Ticket: <title>` followed by `Key: value` header lines, and is still read: `parseLegacyTicket`
+in `packages/server/src/organization/files.ts` maps the old headers onto the new fields, folds
+`Initiator` into the single `owner` (the filer owns a ticket nobody was assigned) and records it
+as the `created` entry of the history, and turns each old progress line
+(`- <time> <principal> <text> session:<id>`) into a plain progress sentence plus one `progress`
+history entry carrying its time and principal. The board lists both formats side by side, and
+every write serializes the new one — so a ticket converts the first time anything writes to it.
+
+What is lost in the conversion: the `moved … → done` progress line an old ticket recorded is a
+`progress` history entry, not a `moved` one, so a ticket closed before this change is listed in
+the overview's inbox without a `closedAt` — the same way a ticket moved by hand always has been.
+
+**This is a shim with an expiry.** `parseLegacyTicket` can be deleted one release after the
+frontmatter format ships, by which time every ticket an organization still writes to has been
+converted; a ticket nobody has written to since is a ticket nobody is working on, and its file
+can be converted by hand or left where it is. Whoever removes it also drops the legacy branch of
+`parseTicket` and the legacy-format test in `organization-files.test.ts`.
+
+## Ticket lines already in the all-hands channel
+
+Ticket changes no longer write a `system` line into a channel, so nothing produces the
+`ticket_blocked`, `ticket_done` and `ticket_rejected` notice kinds any more. The three stay in
+the `OrgChannelNoticeKind` union and in the Web App's and CLI's renderers, so the lines already
+in an organization's message files keep rendering in the reader's language instead of falling
+back to raw English. Not a shim on a schedule: they stay for as long as those files are read.
+
+## Compatibility
+
+Upgrading needs no action. Existing organizations are marked on the first reconcile pass after
+the restart; organizations deleted before the upgrade leave their sessions in development
+mode's list until archived or deleted. Existing tickets are read as they are and rewritten in
+the new format the first time they are written to. The two pieces of compat code are the
+reconcile backfill and `parseLegacyTicket`, both removable from the next release on.
diff --git a/changelog/unreleased/2026-09-09-backward-compatibility.zh.md b/changelog/unreleased/2026-09-09-backward-compatibility.zh.md
new file mode 100644
index 00000000..1253c7cf
--- /dev/null
+++ b/changelog/unreleased/2026-09-09-backward-compatibility.zh.md
@@ -0,0 +1,71 @@
+# 向后兼容:公司模式的几轮试用
+
+- **Date:** 2026-09-09
+- **Type:** process
+- **Scope:** `server`
+- **PR:** [#587](https://github.com/Prism-Shadow/penguin-harness/pull/587)
+
+[English](2026-09-09-backward-compatibility.md)
+
+[公司模式](2026-09-02-company-mode.zh.md)进入试用时,磁盘上已经有组织在跑,于是后来的五项改动
+都得面对早于它们写下的数据。没有一项需要迁移,也没有一项需要用户动手;这里写清楚每项容忍的是什么
+旧形态,以及其中哪些是带有效期的垫片。
+
+## `sessions.client = "org"`:创建时写入,由对账回填
+
+工位会话与工单会话现在在 `sessions` 行上写入 `client = "org"`,开发模式的列表据此隐藏它们——无论
+组织是否还在、公司模式是否开启。早于这项改动的会话行带的是 `web`、`cli` 或空。因此每轮对账都会把
+组织文件点名的会话行——`desks.toml`(当前与历史工位)与各工单的 `Sessions` 头部——用一条幂等的
+`UPDATE … WHERE client IS NOT 'org'` 盖上标记,升级后的下一轮对账即把既有组织全部标好。
+
+仍然没有标记的是:在这项改动**之前**就已删除的组织的会话。再没有文件点名它们,所以它们会继续被当作
+开发模式自己的会话,直到手动归档或删除。接受这一点:另一种做法是按会话标题去猜。
+
+**这是一段带有效期的垫片。**回填每轮对账只多一条便宜的语句,等每个安装都在带这段代码的构建上对账
+过一次之后就可以删——也就是从发布它的下一个版本起。下一个给公司模式加迁移的人顺手删掉
+`reconcile.ts` 里的回填调用(`markOrgClient`)及其测试。
+
+## `org_config.toml` 没有 `language`
+
+工作语言字段出现之前创建的组织没有 `language` 行。服务端在读取时按使命判定语言(任意位置含汉字即
+`zh`,否则 `en`),不改写文件、不做迁移;此后由创建与设置对话框写入该字段。不是垫片:这个回退就是
+字段定义的缺省值。
+
+## 没有 `notice` 的频道消息行
+
+结构化 notice 之前写下的系统行只有英文 `text`。所有读取方在 `notice` 缺席时回退到该文本,文件格式两
+种都接受。没有要删的东西。
+
+## 旧 Trace 里的 `ticket_notice`
+
+调度器不再产生 `kind: ticket_notice` 的工作轮;标记解析器仍接受这个 kind,旧 Trace 的
+`[org_trigger]` 块照旧折叠与渲染。只要这些 Trace 还会被读,枚举成员就留着。没有按计划要删的东西。
+
+## frontmatter 之前格式的工单文件
+
+工单现在是 YAML frontmatter 加正文。在此之前写下的工单都是 `# Ticket: <标题>` 加若干
+`Key: value` 头部行,仍然能读:`packages/server/src/organization/files.ts` 里的
+`parseLegacyTicket` 把旧头部映射到新字段,把 `Initiator` 折进唯一的 `owner`(没有指派过负责人的
+工单归创建者),并把它记成 history 的 `created` 条目;每条旧进展行
+(`- <时间> <主体> <正文> session:<id>`)变成一句纯进展,外加一条带着原时间与原主体的 `progress`
+history 条目。看板上两种格式并列显示,而每一次写入都按新格式序列化——工单在第一次被写入时完成转换。
+
+转换中丢掉的东西:旧工单里那条 `moved … → done` 进展变成的是 `progress` 而不是 `moved` 条目,
+因此这项改动之前关闭的工单在组织概览的 inbox 里不带 `closedAt`——和手工移动的工单一直以来的情形相同。
+
+**这是一段带有效期的垫片。**`parseLegacyTicket` 在 frontmatter 格式发布之后的下一个版本就可以删:
+到那时,凡是组织还在写的工单都已转换过;此后仍未被写过的工单,本就没人在做它,其文件手工转换或原样
+留着都行。删它的人顺手删掉 `parseTicket` 里的旧格式分支与 `organization-files.test.ts` 里的旧格式测试。
+
+## 全员频道里已经存在的工单系统行
+
+工单的变化不再往频道写 `system` 行,于是再没有东西产生 `ticket_blocked`、`ticket_done`、
+`ticket_rejected` 这三种 notice。它们仍保留在 `OrgChannelNoticeKind` 联合类型里,Web App 与 CLI 的
+渲染器也保留,好让组织消息文件里已有的那些行仍按读者的语言渲染,而不是退回成英文原文。不是按计划要
+删的垫片:只要这些文件还会被读,它们就留着。
+
+## 兼容性
+
+升级无需操作。既有组织在重启后的第一轮对账被标记;升级之前删除的组织,其会话会留在开发模式列表里,
+直到归档或删除。既有工单按原样读取,并在第一次被写入时改写为新格式。兼容代码有两处——对账里的回填与
+`parseLegacyTicket`,都从下一个版本起可以移除。
diff --git a/packages/cli/package.json b/packages/cli/package.json
index abb816c2..803f1c16 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -24,6 +24,7 @@
},
"dependencies": {
"@modelcontextprotocol/client": "^2.0.0",
+ "@penguinharness/agent-company": "workspace:*",
"@penguinharness/agent-development": "workspace:*",
"@penguinharness/agent-tuning": "workspace:*",
"@penguinharness/continual-learning": "workspace:*",
diff --git a/packages/cli/src/commands/org.ts b/packages/cli/src/commands/org.ts
new file mode 100644
index 00000000..329d88d1
--- /dev/null
+++ b/packages/cli/src/commands/org.ts
@@ -0,0 +1,1593 @@
+/**
+ * `penguin org` — company mode: a thin client over the organization API. Every
+ * subcommand addresses one organization of one Project. The organization's files under
+ * the Project directory (the employee tree, the desks ledger, calendar, tickets,
+ * channels) stay the single source of truth; each command reads a projection of them or
+ * writes through the route that edits them, with the same validated-writer contract
+ * `schedule` has — API errors surface verbatim, so an agent gets synchronous validation.
+ *
+ * penguin org ls [--project-id <id>] [--json] [--server <url>]
+ * penguin org create --org-id <id> --mission <s> [--name <s>] [--ceo-budget <usd>]
+ * penguin org show | chart
+ * penguin org hire (--agent-id <id> | --new-agent <id> [--name] [--description] [--skills <a,b>])
+ * --title <s> --reports-to <agent_id> [--workspace <path>] [--budget <usd>] [--duties <s>]
+ * penguin org employee set <agent_id> [--title] [--reports-to] [--workspace] [--budget] [--duties]
+ * [--model-id <id> --provider <p>]
+ * penguin org leave <agent_id>
+ * penguin org desk show|renew [<agent_id>]
+ * penguin org calendar ls [--agent-id] | add <name> … | update <name> … | rm <name>
+ * penguin org ticket ls [--status] [--owner] [--blocked] | show <id> | create … | move <id> --to <col>
+ * | assign <id> --owner <p> | block <id> --reason <s> [--by] | unblock <id>
+ * | progress <id> -m <text> | start <id> [-m] [--workspace] [--agent-id]
+ * | attach <id> [--session]
+ * penguin org channel ls | create <id> [--name] [--purpose] | show <id> | invite <id> <principal>...
+ * | join <id> | leave <id> | remove <id> <principal> | archive <id> | unarchive <id>
+ * | tail [--channel <id>] [--date <d>] [-n <count>]
+ * | send -m <text> [--channel <id>] [--ref-ticket] [--ref-session]
+ * penguin org handbook list | show [path] | write <path> (-m <text> | --file <f>) | rm <path>
+ * penguin org finance [--period <yyyy-mm>]
+ *
+ * Every subcommand takes `--org-id` (default: PENGUIN_ORG_ID, the variable company mode
+ * adds to the control environment of desk and ticket sessions; there is no default
+ * organization), `--project-id`, `--json` and `--server`. The same environment
+ * identifies the caller: `--agent-id` on the calendar commands and the desk positional
+ * default to PENGUIN_AGENT_ID; `ticket start` sends it as the employee the ticket
+ * session runs as (its own `--agent-id` enlists a colleague on the caller's own ticket,
+ * and outside a session the server picks the ticket owner); the ticket writes and
+ * the channel writes carry PENGUIN_SESSION_ID in their body so the file records the
+ * employee rather than the token's user, and `ticket attach` attaches that session by
+ * default. The reads that depend on who is asking — `channel ls`, `channel show`,
+ * `channel tail` — and the member DELETE behind `leave` / `remove` carry the same
+ * session as `?sessionId=`, having no body to put it in: without it the server answers
+ * an employee as the signed-in person and shows it every channel. `--json` prints the
+ * response DTO as one line (`ticket ls` its filtered list, `channel tail` the messages
+ * it shows); write commands otherwise print a one-line confirmation.
+ * Docs: /docs/cli § "penguin org".
+ */
+import fs from "node:fs";
+import path from "node:path";
+import type { Command } from "commander";
+import type {
+ MeResponse,
+ OrgCalendarItem,
+ OrgCalendarResponse,
+ OrgCalendarWriteResponse,
+ OrgChartResponse,
+ OrgChannelDetail,
+ OrgChannelItem,
+ OrgChannelMessage,
+ OrgChannelMessagesResponse,
+ OrgChannelsResponse,
+ OrgHandbookFileResponse,
+ OrgHandbookFilesResponse,
+ OrgDeskResponse,
+ OrgEmployeeItem,
+ OrgFinanceResponse,
+ OrgTicketDetail,
+ OrgTicketItem,
+ OrgTicketPriority,
+ OrgTicketStartResponse,
+ OrgTicketStatus,
+ OrgTicketsResponse,
+ OrganizationDetail,
+ OrganizationsResponse,
+} from "@prismshadow/penguin-server/api";
+import {
+ resolveAgentId,
+ resolveConnection,
+ resolveProjectId,
+ resolveSessionRef,
+ ServerClient,
+} from "../client.js";
+import { getSessionInfo } from "../server-session.js";
+import { dim } from "../render.js";
+import { renderTable } from "../table.js";
+import type { Messages } from "../i18n.js";
+
+const enc = encodeURIComponent;
+
+/** The kanban columns in board order (the server's ORG_TICKET_COLUMNS; only its types are imported here). */
+const TICKET_COLUMNS: readonly OrgTicketStatus[] = [
+ "proposed",
+ "in_progress",
+ "review",
+ "done",
+ "rejected",
+];
+const PRIORITIES: readonly OrgTicketPriority[] = ["P0", "P1", "P2"];
+/** `channel tail` without `-n`. */
+const DEFAULT_MESSAGE_COUNT = 20;
+/** The all-hands channel: what `--channel` means when it is not given (the server's own default). */
+const DEFAULT_CHANNEL_ID = "default_channel";
+/**
+ * `create --ceo-budget` when it is not given (the server's own default), in USD per month.
+ * Budgets accumulate along the reporting line, so the CEO's is the whole company's.
+ */
+const DEFAULT_CEO_BUDGET = 100;
+
+// ---------------------------------------------------------------------------
+// Scope: the organization, its Project and the connection
+// ---------------------------------------------------------------------------
+
+interface OrgScope {
+ client: ServerClient;
+ projectId: string;
+ orgId: string;
+ /** `/api/projects/:p/organizations/:orgId`. */
+ base: string;
+}
+
+/** Prints a localized error line and marks the exit code; the caller returns. */
+function fail(t: Messages, message: string): void {
+ process.stderr.write(`${t.error(message)}\n`);
+ process.exitCode = 1;
+}
+
+/**
+ * Refuses a caller-supplied id or handbook path holding a `.` / `..` segment: those survive
+ * encodeURIComponent, and the URL parser then collapses them onto a different route —
+ * `employees/..` addresses the organization itself rather than one employee. True after the
+ * error, and the caller returns.
+ */
+function refuseDotSegments(value: string, t: Messages): boolean {
+ if (!value.split("/").some((segment) => segment === "." || segment === "..")) return false;
+ fail(t, t.org.pathSegmentInvalid(value));
+ return true;
+}
+
+/**
+ * Resolves the organization's coordinates and connects. `--org-id` defaults to
+ * PENGUIN_ORG_ID and to nothing else; it is read before the connection so a missing one
+ * never auto-starts a server. Null after the error.
+ */
+async function orgScope(
+ opts: { orgId?: string; projectId?: string; server?: string },
+ t: Messages,
+): Promise<OrgScope | null> {
+ const orgId = opts.orgId?.trim() || process.env.PENGUIN_ORG_ID?.trim() || "";
+ if (orgId === "") {
+ fail(t, t.org.orgIdMissing());
+ return null;
+ }
+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);
+ const projectId = resolveProjectId(opts.projectId);
+ return {
+ client,
+ projectId,
+ orgId,
+ base: `/api/projects/${enc(projectId)}/organizations/${enc(orgId)}`,
+ };
+}
+
+/** The options every organization-scoped leaf command takes, appended after its own. */
+function scoped(cmd: Command, t: Messages): Command {
+ return cmd
+ .option("--org-id <id>", t.org.orgId)
+ .option("--project-id <id>", t.common.projectId)
+ .option("--json", t.common.json)
+ .option("--server <url>", t.common.server);
+}
+
+/** The calling session (the control environment's PENGUIN_SESSION_ID), when the CLI runs inside one. */
+function callerSessionId(): string | undefined {
+ return process.env.PENGUIN_SESSION_ID?.trim() || undefined;
+}
+
+/**
+ * Who the server records a write as: the calling session and the calling employee, both from
+ * the control environment, so the file names the employee rather than the token's user. The
+ * Agent id is the narrower fact — it names exactly the Agent whose subprocess ran the command —
+ * and the server prefers it; the session answers when there is no Agent id (a signed-in CLI
+ * outside a session sends neither and the write is the person's).
+ */
+function actorFields(): { sessionId?: string; agentId?: string } {
+ const sessionId = callerSessionId();
+ const agentId = process.env.PENGUIN_AGENT_ID?.trim() || undefined;
+ return {
+ ...(sessionId !== undefined ? { sessionId } : {}),
+ ...(agentId !== undefined ? { agentId } : {}),
+ };
+}
+
+/**
+ * A `?`-prefixed query string over the entries that have a value; empty when none has.
+ * `sessionId` and `agentId` ride here on the channel reads and the member DELETE, which have
+ * no body to carry the identity {@link actorFields} puts in one — without them the server
+ * answers an employee as the signed-in person, and `channel ls` shows it every channel.
+ */
+function query(entries: Array<[string, string | undefined]>): string {
+ const parts = entries
+ .filter((entry): entry is [string, string] => entry[1] !== undefined)
+ .map(([key, value]) => `${key}=${enc(value)}`);
+ return parts.length > 0 ? `?${parts.join("&")}` : "";
+}
+
+/** The identity {@link actorFields} carries in a body, as query entries for the reads that have none. */
+function actorQuery(): Array<[string, string | undefined]> {
+ const fields = actorFields();
+ return [
+ ["sessionId", fields.sessionId],
+ ["agentId", fields.agentId],
+ ];
+}
+
+/** `--channel`, trimmed; the all-hands channel when the flag is absent or empty. */
+function channelOf(raw: unknown): string {
+ return (typeof raw === "string" ? raw.trim() : "") || DEFAULT_CHANNEL_ID;
+}
+
+/**
+ * The caller as a channel principal, which `join` and `leave` have to name themselves:
+ * inside a desk or ticket session it is that session's employee — the identity the server
+ * derives from the `sessionId` {@link actorFields} sends — and outside one the signed-in
+ * person, whom only the server knows.
+ */
+async function callerPrincipal(client: ServerClient): Promise<string> {
+ const sessionId = callerSessionId();
+ if (sessionId !== undefined) {
+ return `agent:${(await getSessionInfo(client, sessionId)).agentId}`;
+ }
+ const me = await client.request<MeResponse>("GET", "/api/me");
+ return `user:${me.user.userId}`;
+}
+
+function printJson(value: unknown): void {
+ process.stdout.write(`${JSON.stringify(value)}\n`);
+}
+
+function printLine(text: string): void {
+ process.stdout.write(`${text}\n`);
+}
+
+// ---------------------------------------------------------------------------
+// Value parsing and formatting
+// ---------------------------------------------------------------------------
+
+/** `--start-at` value: the literal `now` becomes the current instant; anything else passes through for the server to validate. */
+function resolveStartAt(raw: string): string {
+ return raw.trim().toLowerCase() === "now" ? new Date().toISOString() : raw;
+}
+
+/** A comma-separated flag value as a trimmed list; undefined when absent or empty. */
+function commaList(raw: unknown): string[] | undefined {
+ if (typeof raw !== "string") return undefined;
+ const items = raw
+ .split(",")
+ .map((s) => s.trim())
+ .filter((s) => s.length > 0);
+ return items.length > 0 ? items : undefined;
+}
+
+/** A budget flag (`--budget`, `--ceo-budget`): a non-negative number. Null after the error, which names the flag. */
+function parseBudget(flag: string, raw: string, t: Messages): number | null {
+ const value = Number(raw);
+ if (raw.trim() === "" || !Number.isFinite(value) || value < 0) {
+ fail(t, t.org.budgetInvalid(flag, raw));
+ return null;
+ }
+ return value;
+}
+
+/** A kanban column name (`--status`, `--to`). Null after the error. */
+function parseColumn(raw: string, t: Messages): OrgTicketStatus | null {
+ if ((TICKET_COLUMNS as readonly string[]).includes(raw)) return raw as OrgTicketStatus;
+ fail(t, t.org.statusInvalid(raw));
+ return null;
+}
+
+/** `--priority`: P0 / P1 / P2. Null after the error. */
+function parsePriority(raw: string, t: Messages): OrgTicketPriority | null {
+ if ((PRIORITIES as readonly string[]).includes(raw)) return raw as OrgTicketPriority;
+ fail(t, t.org.priorityInvalid(raw));
+ return null;
+}
+
+/** `-n <count>`: a positive integer. Null after the error. */
+function parseCount(raw: string, t: Messages): number | null {
+ const value = Number(raw);
+ if (!Number.isInteger(value) || value <= 0) {
+ fail(t, t.org.countInvalid(raw));
+ return null;
+ }
+ return value;
+}
+
+/** Costs print with four decimals (cents matter at these magnitudes), budgets with two. */
+const usd = (cost: number): string => `$${cost.toFixed(4)}`;
+const usdBudget = (budget: number): string => `$${budget.toFixed(2)}`;
+
+/** `$cost / $budget (ratio%)`, or the bare cost without a budget. */
+function spendText(spend: { cost: number; budget?: number; ratio?: number }): string {
+ if (spend.budget === undefined) return usd(spend.cost);
+ return `${usd(spend.cost)} / ${usdBudget(spend.budget)}${ratioText(spend.ratio)}`;
+}
+
+/** Budget cell: `$budget (ratio%)`, or `-` when unbounded. */
+function budgetText(budget: number | undefined, ratio: number | undefined): string {
+ return budget === undefined ? "-" : `${usdBudget(budget)}${ratioText(ratio)}`;
+}
+
+function ratioText(ratio: number | undefined): string {
+ return ratio === undefined ? "" : ` (${Math.round(ratio * 100)}%)`;
+}
+
+function isBlocked(item: { blocked?: string }): boolean {
+ return item.blocked !== undefined && item.blocked !== "";
+}
+
+/**
+ * Depth-first order over a reports-to tree: the roots (no manager) first, each followed by
+ * its subordinates one level deeper, siblings in their listed order. An employee whose
+ * manager is not listed (or sits in a cycle) is appended at the root level so nothing goes
+ * unlisted.
+ */
+function treeOrder<T extends { agentId: string; reportsTo: string | null }>(
+ items: readonly T[],
+): Array<{ item: T; depth: number }> {
+ const out: Array<{ item: T; depth: number }> = [];
+ const seen = new Set<string>();
+ const walk = (parent: string | null, depth: number): void => {
+ for (const item of items) {
+ if (item.reportsTo !== parent || seen.has(item.agentId)) continue;
+ seen.add(item.agentId);
+ out.push({ item, depth });
+ walk(item.agentId, depth + 1);
+ }
+ };
+ walk(null, 0);
+ for (const item of items) {
+ if (seen.has(item.agentId)) continue;
+ seen.add(item.agentId);
+ out.push({ item, depth: 0 });
+ }
+ return out;
+}
+
+const indent = (depth: number, text: string): string => `${" ".repeat(depth)}${text}`;
+
+// ---------------------------------------------------------------------------
+// Human views
+// ---------------------------------------------------------------------------
+
+/** `show`: one line per fact — identity, mission, people, board, money, what waits for the caller. */
+function renderDetail(d: OrganizationDetail, t: Messages): string {
+ const board = TICKET_COLUMNS.map((column) => `${column} ${d.board[column]}`).join(", ");
+ const lines = [
+ t.org.showHead(d.name, d.orgId, d.status),
+ t.org.showMission(d.mission),
+ t.org.showLanguage(d.settings.language ?? "en"),
+ t.org.showEmployees(d.employeeCount, d.runningCount, d.pausedCount),
+ t.org.showBoard(board, d.blockedTickets),
+ t.org.showSpend(d.spend.period, spendText(d.spend)),
+ t.org.showPending(
+ d.pending.mentions,
+ d.pending.reviewTickets.length,
+ d.pending.blockedByMe.length,
+ ),
+ ...(d.invalid !== undefined ? [t.org.invalid(d.invalid)] : []),
+ ];
+ return `${lines.join("\n")}\n`;
+}
+
+/** `chart`: the tree as a table whose first column is indented by depth. */
+function renderChart(res: OrgChartResponse, t: Messages): string {
+ return renderTable(
+ [
+ t.agent.colId(),
+ t.agent.colName(),
+ t.org.colJobTitle(),
+ t.org.colState(),
+ t.org.colOwn(),
+ t.org.colCumulative(),
+ t.org.colBudget(),
+ t.org.colNote(),
+ ],
+ treeOrder(res.employees).map(({ item: e, depth }) => [
+ indent(depth, e.agentId),
+ e.name,
+ e.title,
+ e.state,
+ usd(e.spend.own),
+ usd(e.spend.cumulative),
+ budgetText(e.budget, e.spend.ratio),
+ e.invalid !== undefined ? t.org.invalid(e.invalid) : "",
+ ]),
+ );
+}
+
+/** `ticket show`: the derived figures, the ticket's fields, its prose sections, then its history. */
+function renderTicket(d: OrgTicketDetail, t: Messages): string {
+ const label = t.org.ticketFields();
+ const field = (key: string, value: string): string => `${key}: ${value}`;
+ const head = [
+ t.org.ticketHead(d.ticketId, d.status, d.running, isBlocked(d) ? d.blocked : undefined),
+ t.org.ticketFigures(usd(d.cost), usd(d.rolledUpCost), d.sessions.length, d.children.length),
+ ...(d.invalid !== undefined ? [t.org.invalid(d.invalid)] : []),
+ field(label.title, d.title),
+ field(label.owner, d.owner),
+ ...(d.parent !== undefined ? [field(label.parent, d.parent)] : []),
+ field(label.notify, d.notify.join(", ")),
+ field(label.priority, d.priority),
+ ...(d.due !== undefined ? [field(label.due, d.due)] : []),
+ ...(isBlocked(d) ? [field(label.blocked, d.blocked ?? "")] : []),
+ ...(d.blockedBy !== undefined && d.blockedBy !== ""
+ ? [field(label.blockedBy, d.blockedBy)]
+ : []),
+ field(label.sessions, d.sessions.join(", ")),
+ ];
+ // The section headings are the file's own: what `show` prints and what an employee edits
+ // with its file tools have to read as the same document.
+ const prose = [
+ `## Goal\n${d.goal}`,
+ `## Acceptance criteria\n${d.acceptanceCriteria}`,
+ `## Progress\n${d.progress.map((line) => `- ${line}`).join("\n")}`,
+ `## Result\n${d.result}`,
+ ].map((section) => section.trimEnd());
+ // The actions stay in English: they are field values, like the column and the priority.
+ const history = d.history.map(
+ (h) => `${h.at} ${h.by} ${h.action}${h.note !== undefined ? `: ${h.note}` : ""}`,
+ );
+ const blocks = [
+ head.join("\n"),
+ ...prose,
+ ...(history.length > 0 ? [`${t.org.ticketHistory()}\n${history.join("\n")}`] : []),
+ ];
+ return `${blocks.join("\n\n")}\n`;
+}
+
+/** `finance`: employees along the reporting line, then tickets, then the total. */
+function renderFinance(res: OrgFinanceResponse, t: Messages): string {
+ const employees = renderTable(
+ [
+ t.agent.colId(),
+ t.org.colJobTitle(),
+ t.org.colOwn(),
+ t.org.colCumulative(),
+ t.org.colBudget(),
+ t.schedule.colStatus(),
+ ],
+ treeOrder(res.employees).map(({ item: e, depth }) => [
+ indent(depth, e.agentId),
+ e.title,
+ usd(e.own),
+ usd(e.cumulative),
+ budgetText(e.budget, e.ratio),
+ e.paused ? "paused" : e.warned ? "warned" : "",
+ ]),
+ );
+ const tickets =
+ res.tickets.length === 0
+ ? ""
+ : `\n${renderTable(
+ [
+ t.org.colTicket(),
+ t.schedule.colStatus(),
+ t.cost.colCost(),
+ t.org.colRolledUp(),
+ t.org.colTitle(),
+ ],
+ res.tickets.map((x) => [x.ticketId, x.status, usd(x.cost), usd(x.rolledUp), x.title]),
+ )}`;
+ return `${employees}${tickets}\n${t.org.financeTotal(res.period, usd(res.total))}\n`;
+}
+
+/**
+ * One channel message per line: `time sender text` (a multi-line text keeps its lines).
+ * A `system` line the server wrote with a structured notice is rendered in the reader's
+ * language from that notice; a kind this build does not know falls back to the English text.
+ */
+function messageLine(m: OrgChannelMessage, t: Messages): string {
+ return `${m.time} ${m.sender} ${noticeText(m, t)}`;
+}
+
+/** The notice's sentence in the reader's language, or the message's own text. */
+function noticeText(m: OrgChannelMessage, t: Messages): string {
+ const notice = m.notice;
+ if (notice === undefined) return m.text;
+ // Not every kind is one this build knows: a line a newer server wrote keeps its English.
+ const render = t.org.notices[notice.kind] as ((p: Record<string, string>) => string) | undefined;
+ return render === undefined ? m.text : render(notice.params);
+}
+
+/** A channel's display name: the all-hands channel is labelled here, its stored name never shown. */
+function channelLabel(item: { everyone: boolean; name: string }, t: Messages): string {
+ return item.everyone ? t.org.allHands() : item.name;
+}
+
+/** `channel ls`: one row per channel, the caller's unread counts in the last two columns. */
+function renderChannels(items: readonly OrgChannelItem[], t: Messages): string {
+ return renderTable(
+ [
+ t.agent.colId(),
+ t.agent.colName(),
+ t.org.colMembers(),
+ t.org.colArchived(),
+ t.org.colUnread(),
+ t.org.colMentions(),
+ ],
+ items.map((c) => [
+ c.channelId,
+ channelLabel(c, t),
+ String(c.memberCount),
+ c.archived ? "archived" : "",
+ String(c.unread),
+ String(c.mentionsMe),
+ ]),
+ );
+}
+
+/** `channel show`: the facts the channel carries, then its members. */
+function renderChannelDetail(d: OrgChannelDetail, t: Messages): string {
+ const lines = [
+ t.org.channelHead(channelLabel(d, t), d.channelId, d.memberCount, d.archived),
+ ...(d.purpose !== "" ? [t.org.channelPurposeLine(d.purpose)] : []),
+ t.org.channelCreatedBy(d.createdBy, d.createdAt),
+ ...(d.lastMessageAt !== null ? [t.org.channelLastMessage(d.lastMessageAt)] : []),
+ ];
+ const members = renderTable(
+ [t.org.colPrincipal(), t.agent.colName()],
+ d.members.map((m) => [m.principal, m.name]),
+ );
+ return `${lines.join("\n")}\n\n${members}`;
+}
+
+// ---------------------------------------------------------------------------
+// Registration
+// ---------------------------------------------------------------------------
+
+export function registerOrgCommand(program: Command, t: Messages): void {
+ const org = program.command("org").description(t.org.desc);
+
+ org
+ .command("ls")
+ .description(t.org.lsDesc)
+ .option("--project-id <id>", t.common.projectId)
+ .option("--json", t.common.json)
+ .option("--server <url>", t.common.server)
+ .action(async (opts) => {
+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);
+ const projectId = resolveProjectId(opts.projectId);
+ const res = await client.request<OrganizationsResponse>(
+ "GET",
+ `/api/projects/${enc(projectId)}/organizations`,
+ );
+ if (opts.json === true) {
+ printJson(res);
+ return;
+ }
+ if (res.organizations.length === 0) {
+ printLine(t.org.empty(projectId));
+ return;
+ }
+ process.stdout.write(
+ renderTable(
+ [
+ t.agent.colId(),
+ t.agent.colName(),
+ t.schedule.colStatus(),
+ t.org.colEmployees(),
+ t.org.colRunning(),
+ t.org.colOpen(),
+ t.org.colBlocked(),
+ t.org.colSpend(),
+ t.org.colNote(),
+ ],
+ res.organizations.map((o) => [
+ o.orgId,
+ o.name,
+ o.status,
+ String(o.employeeCount),
+ String(o.runningCount),
+ String(o.openTickets),
+ String(o.blockedTickets),
+ spendText(o.spend),
+ o.invalid !== undefined ? t.org.invalid(o.invalid) : "",
+ ]),
+ ),
+ );
+ });
+
+ org
+ .command("create")
+ .description(t.org.createDesc)
+ .requiredOption("--org-id <id>", t.org.newOrgId)
+ .requiredOption("--mission <text>", t.org.mission)
+ .option("--name <name>", t.org.orgName)
+ .option("--language <zh|en>", t.org.orgLanguageOption)
+ .option("--workspace <path>", t.common.workspace)
+ .option("--ceo-budget <usd>", t.org.ceoBudget, String(DEFAULT_CEO_BUDGET))
+ .option("--model-id <id>", t.common.modelId)
+ .option("--provider <name>", t.common.provider)
+ .option("--project-id <id>", t.common.projectId)
+ .option("--json", t.common.json)
+ .option("--server <url>", t.common.server)
+ .action(async (opts) => {
+ // A model reference is always the complete (provider, modelId) pair, like everywhere else.
+ if ((opts.modelId !== undefined) !== (opts.provider !== undefined)) {
+ fail(t, t.modelRefIncomplete());
+ return;
+ }
+ const ceoBudget = parseBudget("--ceo-budget", String(opts.ceoBudget), t);
+ if (ceoBudget === null) return;
+ if (opts.language !== undefined && opts.language !== "zh" && opts.language !== "en") {
+ fail(t, t.org.languageInvalid(String(opts.language)));
+ return;
+ }
+ const client = new ServerClient(await resolveConnection({ server: opts.server }, t), t);
+ const projectId = resolveProjectId(opts.projectId);
+ const detail = await client.request<OrganizationDetail>(
+ "POST",
+ `/api/projects/${enc(projectId)}/organizations`,
+ {
+ orgId: String(opts.orgId),
+ mission: String(opts.mission),
+ ...(opts.name !== undefined ? { name: String(opts.name) } : {}),
+ ...(opts.language !== undefined ? { language: opts.language as "zh" | "en" } : {}),
+ ...(opts.workspace !== undefined ? { workspace: String(opts.workspace) } : {}),
+ ceoBudget,
+ ...(opts.modelId !== undefined
+ ? { model: { provider: String(opts.provider), modelId: String(opts.modelId) } }
+ : {}),
+ },
+ );
+ if (opts.json === true) printJson(detail);
+ else printLine(t.org.created(detail.orgId, detail.ceoDeskSessionId));
+ });
+
+ scoped(org.command("show").description(t.org.showDesc), t).action(async (opts) => {
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const detail = await scope.client.request<OrganizationDetail>("GET", scope.base);
+ if (opts.json === true) printJson(detail);
+ else process.stdout.write(renderDetail(detail, t));
+ });
+
+ scoped(org.command("chart").description(t.org.chartDesc), t).action(async (opts) => {
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const res = await scope.client.request<OrgChartResponse>("GET", `${scope.base}/chart`);
+ if (opts.json === true) printJson(res);
+ else process.stdout.write(renderChart(res, t));
+ });
+
+ // ---- employees ----
+
+ scoped(
+ org
+ .command("hire")
+ .description(t.org.hireDesc)
+ .option("--agent-id <id>", t.org.hireAgentId)
+ .option("--new-agent <id>", t.org.newAgent)
+ .option("--name <name>", t.org.newAgentName)
+ .option("--description <text>", t.org.newAgentDescription)
+ .option("--skills <names>", t.org.skills)
+ .requiredOption("--title <title>", t.org.title)
+ .requiredOption("--reports-to <agent_id>", t.org.reportsTo)
+ .option("--workspace <path>", t.org.hireWorkspace)
+ .option("--budget <usd>", t.org.budget)
+ .option("--duties <text>", t.org.duties),
+ t,
+ ).action(async (opts) => {
+ // The employee is an existing Agent XOR a new one; the new-Agent fields describe the latter.
+ if ((opts.agentId !== undefined) === (opts.newAgent !== undefined)) {
+ fail(t, t.org.hireTargetConflict());
+ return;
+ }
+ if (
+ opts.newAgent === undefined &&
+ (opts.name !== undefined || opts.description !== undefined || opts.skills !== undefined)
+ ) {
+ fail(t, t.org.newAgentFieldsOnly());
+ return;
+ }
+ const budget =
+ opts.budget !== undefined ? parseBudget("--budget", String(opts.budget), t) : undefined;
+ if (budget === null) return;
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const plugins = commaList(opts.skills);
+ const item = await scope.client.request<OrgEmployeeItem>("POST", `${scope.base}/employees`, {
+ ...(opts.agentId !== undefined ? { agentId: String(opts.agentId) } : {}),
+ ...(opts.newAgent !== undefined
+ ? {
+ newAgent: {
+ agentId: String(opts.newAgent),
+ ...(opts.name !== undefined ? { name: String(opts.name) } : {}),
+ ...(opts.description !== undefined ? { description: String(opts.description) } : {}),
+ ...(plugins !== undefined ? { plugins } : {}),
+ },
+ }
+ : {}),
+ title: String(opts.title),
+ reportsTo: String(opts.reportsTo),
+ ...(opts.workspace !== undefined ? { workspace: String(opts.workspace) } : {}),
+ ...(budget !== undefined ? { budget } : {}),
+ ...(opts.duties !== undefined ? { duties: String(opts.duties) } : {}),
+ });
+ if (opts.json === true) printJson(item);
+ else printLine(t.org.hired(item.agentId, item.title, item.reportsTo));
+ });
+
+ const employee = org.command("employee").description(t.org.employeeDesc);
+
+ scoped(
+ employee
+ .command("set <agent_id>")
+ .description(t.org.employeeSetDesc)
+ .option("--title <title>", t.org.title)
+ .option("--reports-to <agent_id>", t.org.reportsTo)
+ .option("--workspace <path>", t.org.employeeWorkspace)
+ .option("--budget <usd>", t.org.budget)
+ .option("--duties <text>", t.org.duties)
+ .option("--model-id <id>", t.common.modelId)
+ .option("--provider <group>", t.common.provider),
+ t,
+ ).action(async (agentId: string, opts) => {
+ if (refuseDotSegments(agentId, t)) return;
+ if (Boolean(opts.modelId) !== Boolean(opts.provider)) {
+ fail(t, t.modelRefIncomplete());
+ return;
+ }
+ const budget =
+ opts.budget !== undefined ? parseBudget("--budget", String(opts.budget), t) : undefined;
+ if (budget === null) return;
+ const body = {
+ ...(opts.title !== undefined ? { title: String(opts.title) } : {}),
+ ...(opts.reportsTo !== undefined ? { reportsTo: String(opts.reportsTo) } : {}),
+ ...(opts.workspace !== undefined ? { workspace: String(opts.workspace) } : {}),
+ ...(budget !== undefined ? { budget } : {}),
+ ...(opts.duties !== undefined ? { duties: String(opts.duties) } : {}),
+ ...(opts.modelId !== undefined
+ ? { model: { provider: String(opts.provider), modelId: String(opts.modelId) } }
+ : {}),
+ };
+ if (Object.keys(body).length === 0) {
+ fail(t, t.org.nothingToSet());
+ return;
+ }
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const item = await scope.client.request<OrgEmployeeItem>(
+ "PATCH",
+ `${scope.base}/employees/${enc(agentId)}`,
+ body,
+ );
+ if (opts.json === true) printJson(item);
+ else printLine(t.org.employeeUpdated(item.agentId));
+ });
+
+ scoped(org.command("leave <agent_id>").description(t.org.leaveDesc), t).action(
+ async (agentId: string, opts) => {
+ if (refuseDotSegments(agentId, t)) return;
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ await scope.client.request("DELETE", `${scope.base}/employees/${enc(agentId)}`);
+ if (opts.json === true) printJson({ agentId });
+ else printLine(t.org.left(agentId));
+ },
+ );
+
+ // ---- desks ----
+
+ const desk = org.command("desk").description(t.org.deskDesc);
+
+ scoped(desk.command("show [agent_id]").description(t.org.deskShowDesc), t).action(
+ async (agentArg: string | undefined, opts) => {
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const agentId = resolveAgentId(agentArg);
+ const res = await scope.client.request<OrgDeskResponse>(
+ "GET",
+ `${scope.base}/employees/${enc(agentId)}/desk`,
+ );
+ if (opts.json === true) printJson(res);
+ else {
+ printLine(t.org.desk(res.agentId, res.sessionId, res.workspace, res.openedAt, res.created));
+ }
+ },
+ );
+
+ scoped(desk.command("renew [agent_id]").description(t.org.deskRenewDesc), t).action(
+ async (agentArg: string | undefined, opts) => {
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const agentId = resolveAgentId(agentArg);
+ const res = await scope.client.request<OrgDeskResponse>(
+ "POST",
+ `${scope.base}/employees/${enc(agentId)}/desk`,
+ );
+ if (opts.json === true) printJson(res);
+ else printLine(t.org.deskRenewed(res.agentId, res.sessionId));
+ },
+ );
+
+ // ---- calendar ----
+
+ const calendar = org.command("calendar").description(t.org.calendarDesc);
+
+ scoped(
+ calendar
+ .command("ls")
+ .description(t.org.calendarLsDesc)
+ .option("--agent-id <id>", t.org.calendarAgentId),
+ t,
+ ).action(async (opts) => {
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const all = await scope.client.request<OrgCalendarResponse>("GET", `${scope.base}/calendar`);
+ // Without --agent-id the whole organization's calendar; with it, that employee's events.
+ const only = opts.agentId !== undefined ? resolveAgentId(opts.agentId) : undefined;
+ const res: OrgCalendarResponse =
+ only === undefined
+ ? all
+ : {
+ events: all.events.filter((e) => e.agentId === only),
+ invalidFiles: all.invalidFiles.filter((f) => f.agentId === only),
+ };
+ if (opts.json === true) {
+ printJson(res);
+ return;
+ }
+ const rows: string[][] = res.events.map((e) => [
+ e.agentId,
+ e.name,
+ e.enabled ? t.schedule.enabled() : t.schedule.disabled(),
+ e.startAt,
+ e.period ?? t.schedule.oneShot(),
+ e.nextFireAt ?? "-",
+ e.lastFiredAt ?? "-",
+ // Active is the quiet norm; a paused organization or employee skips due slots.
+ e.status !== "active" ? e.status : e.paused ? "paused" : "",
+ ]);
+ for (const f of res.invalidFiles) {
+ rows.push([f.agentId, f.name, "-", "-", "-", "-", "-", "invalid"]);
+ }
+ if (rows.length === 0) {
+ printLine(t.org.calendarEmpty());
+ return;
+ }
+ process.stdout.write(
+ renderTable(
+ [
+ t.agent.colId(),
+ t.schedule.colName(),
+ t.schedule.colEnabled(),
+ t.schedule.colStartAt(),
+ t.schedule.colPeriod(),
+ t.org.colNext(),
+ t.schedule.colLastFired(),
+ t.schedule.colStatus(),
+ ],
+ rows,
+ ),
+ );
+ });
+
+ scoped(
+ calendar
+ .command("add <name>")
+ .description(t.org.calendarAddDesc)
+ .option("--agent-id <id>", t.org.calendarAgentId)
+ .requiredOption("--prompt <text>", t.schedule.prompt)
+ .requiredOption("--start-at <when>", t.schedule.startAt)
+ .option("--period <duration>", t.schedule.period)
+ .option("--end-at <iso>", t.schedule.endAt)
+ .option("--title <title>", t.org.calendarTitle)
+ .option("--disabled", t.schedule.disabledOpt),
+ t,
+ ).action(async (name: string, opts) => {
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const agentId = resolveAgentId(opts.agentId);
+ const item = await scope.client.request<OrgCalendarWriteResponse>(
+ "POST",
+ `${scope.base}/calendar`,
+ {
+ agentId,
+ name,
+ ...(opts.title !== undefined ? { title: String(opts.title) } : {}),
+ prompt: String(opts.prompt),
+ // As `schedule add`: an event added through the CLI is meant to fire; --disabled opts out.
+ enabled: opts.disabled !== true,
+ startAt: resolveStartAt(String(opts.startAt)),
+ ...(opts.period !== undefined ? { period: String(opts.period) } : {}),
+ ...(opts.endAt !== undefined ? { endAt: String(opts.endAt) } : {}),
+ },
+ );
+ if (opts.json === true) printJson(item);
+ else printCalendarWrite(t, item);
+ });
+
+ scoped(
+ calendar
+ .command("update <name>")
+ .description(t.org.calendarUpdateDesc)
+ .option("--agent-id <id>", t.org.calendarAgentId)
+ .option("--prompt <text>", t.schedule.prompt)
+ .option("--start-at <when>", t.schedule.startAt)
+ .option("--period <duration>", t.schedule.period)
+ .option("--end-at <iso>", t.schedule.endAt)
+ .option("--title <title>", t.org.calendarTitle)
+ .option("--enable", t.schedule.enableOpt)
+ .option("--disable", t.schedule.disableOpt),
+ t,
+ ).action(async (name: string, opts) => {
+ if (opts.enable === true && opts.disable === true) {
+ fail(t, t.schedule.enableDisableConflict());
+ return;
+ }
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const agentId = resolveAgentId(opts.agentId);
+ const target = `${scope.base}/calendar/${enc(agentId)}/${enc(name)}`;
+ // Read-modify-write: unspecified fields keep the stored values.
+ const stored = await scope.client.request<OrgCalendarItem>("GET", target);
+ const body: Record<string, unknown> = {
+ enabled: opts.enable === true ? true : opts.disable === true ? false : stored.enabled,
+ prompt: opts.prompt !== undefined ? String(opts.prompt) : stored.prompt,
+ startAt: opts.startAt !== undefined ? resolveStartAt(String(opts.startAt)) : stored.startAt,
+ };
+ const title = opts.title !== undefined ? String(opts.title) : stored.title;
+ if (title !== undefined) body.title = title;
+ const period = opts.period !== undefined ? String(opts.period) : stored.period;
+ if (period !== undefined) body.period = period;
+ const endAt = opts.endAt !== undefined ? String(opts.endAt) : stored.endAt;
+ if (endAt !== undefined) body.endAt = endAt;
+ const item = await scope.client.request<OrgCalendarWriteResponse>("PUT", target, body);
+ if (opts.json === true) printJson(item);
+ else printCalendarWrite(t, item);
+ });
+
+ scoped(
+ calendar
+ .command("rm <name>")
+ .description(t.org.calendarRmDesc)
+ .option("--agent-id <id>", t.org.calendarAgentId),
+ t,
+ ).action(async (name: string, opts) => {
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const agentId = resolveAgentId(opts.agentId);
+ await scope.client.request("DELETE", `${scope.base}/calendar/${enc(agentId)}/${enc(name)}`);
+ if (opts.json === true) printJson({ agentId, name });
+ else printLine(t.org.calendarRemoved(agentId, name));
+ });
+
+ // ---- tickets ----
+
+ const ticket = org.command("ticket").description(t.org.ticketDesc);
+
+ scoped(
+ ticket
+ .command("ls")
+ .description(t.org.ticketLsDesc)
+ .option("--status <column>", t.org.statusFilter)
+ .option("--owner <principal>", t.org.ownerFilter)
+ .option("--blocked", t.org.blockedFilter),
+ t,
+ ).action(async (opts) => {
+ const status = opts.status !== undefined ? parseColumn(String(opts.status), t) : undefined;
+ if (status === null) return;
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const res = await scope.client.request<OrgTicketsResponse>("GET", `${scope.base}/tickets`);
+ // The board comes whole; the filters are local, over every column in board order.
+ const tickets: OrgTicketItem[] = TICKET_COLUMNS.flatMap((column) => res.columns[column]).filter(
+ (item) =>
+ (status === undefined || item.status === status) &&
+ (opts.owner === undefined || item.owner === String(opts.owner)) &&
+ (opts.blocked !== true || isBlocked(item)),
+ );
+ if (opts.json === true) {
+ printJson({ tickets, invalidFiles: res.invalidFiles });
+ return;
+ }
+ const rows: string[][] = tickets.map((item) => [
+ item.ticketId,
+ item.status,
+ item.priority,
+ item.owner ?? "-",
+ isBlocked(item) ? "blocked" : "",
+ String(item.sessions.length),
+ item.title,
+ ]);
+ for (const f of res.invalidFiles) rows.push([f.path, "invalid", "-", "-", "", "-", f.error]);
+ if (rows.length === 0) {
+ printLine(t.org.ticketsEmpty());
+ return;
+ }
+ process.stdout.write(
+ renderTable(
+ [
+ t.agent.colId(),
+ t.schedule.colStatus(),
+ t.org.colPriority(),
+ t.org.colOwner(),
+ t.org.colBlocked(),
+ t.agent.colSessions(),
+ t.org.colTitle(),
+ ],
+ rows,
+ ),
+ );
+ });
+
+ scoped(ticket.command("show <ticket_id>").description(t.org.ticketShowDesc), t).action(
+ async (ticketId: string, opts) => {
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const detail = await scope.client.request<OrgTicketDetail>(
+ "GET",
+ `${scope.base}/tickets/${enc(ticketId)}`,
+ );
+ if (opts.json === true) printJson(detail);
+ else process.stdout.write(renderTicket(detail, t));
+ },
+ );
+
+ scoped(
+ ticket
+ .command("create")
+ .description(t.org.ticketCreateDesc)
+ .requiredOption("--title <title>", t.org.ticketTitle)
+ .option("--slug <slug>", t.org.ticketSlug)
+ .option("--goal <text>", t.org.goal)
+ .option("--criteria <text>", t.org.criteria)
+ .option("--body-file <path>", t.org.bodyFile)
+ .option("--owner <principal>", t.org.owner)
+ .option("--parent <ticket_id>", t.org.parent)
+ .option("--notify <principals>", t.org.notify)
+ .option("--priority <level>", t.org.priority)
+ .option("--due <date>", t.org.due),
+ t,
+ ).action(async (opts) => {
+ // The content is --goal (with --criteria) XOR the whole Markdown body from a file.
+ if ((opts.goal !== undefined) === (opts.bodyFile !== undefined)) {
+ fail(t, t.org.ticketBodyConflict());
+ return;
+ }
+ if (opts.criteria !== undefined && opts.goal === undefined) {
+ fail(t, t.org.criteriaNeedsGoal());
+ return;
+ }
+ const priority =
+ opts.priority !== undefined ? parsePriority(String(opts.priority), t) : undefined;
+ if (priority === null) return;
+ let body: string | undefined;
+ if (opts.bodyFile !== undefined) {
+ try {
+ body = fs.readFileSync(path.resolve(String(opts.bodyFile)), "utf8");
+ } catch {
+ fail(t, t.org.bodyFileUnreadable(String(opts.bodyFile)));
+ return;
+ }
+ }
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const notify = commaList(opts.notify);
+ const detail = await scope.client.request<OrgTicketDetail>("POST", `${scope.base}/tickets`, {
+ title: String(opts.title),
+ ...(opts.slug !== undefined ? { slug: String(opts.slug) } : {}),
+ ...(opts.goal !== undefined ? { goal: String(opts.goal) } : {}),
+ ...(opts.criteria !== undefined ? { acceptanceCriteria: String(opts.criteria) } : {}),
+ ...(body !== undefined ? { body } : {}),
+ ...(opts.owner !== undefined ? { owner: String(opts.owner) } : {}),
+ ...(opts.parent !== undefined ? { parent: String(opts.parent) } : {}),
+ ...(notify !== undefined ? { notify } : {}),
+ ...(priority !== undefined ? { priority } : {}),
+ ...(opts.due !== undefined ? { due: String(opts.due) } : {}),
+ ...actorFields(),
+ });
+ if (opts.json === true) printJson(detail);
+ else printLine(t.org.ticketCreated(detail.ticketId, detail.status));
+ });
+
+ scoped(
+ ticket
+ .command("move <ticket_id>")
+ .description(t.org.ticketMoveDesc)
+ .requiredOption("--to <column>", t.org.moveTo)
+ .option("--reason <text>", t.org.moveReason),
+ t,
+ ).action(async (ticketId: string, opts) => {
+ const status = parseColumn(String(opts.to), t);
+ if (status === null) return;
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const detail = await scope.client.request<OrgTicketDetail>(
+ "POST",
+ `${scope.base}/tickets/${enc(ticketId)}/move`,
+ {
+ status,
+ ...(opts.reason !== undefined ? { reason: String(opts.reason) } : {}),
+ ...actorFields(),
+ },
+ );
+ if (opts.json === true) printJson(detail);
+ else printLine(t.org.ticketMoved(detail.ticketId, detail.status));
+ });
+
+ scoped(
+ ticket
+ .command("assign <ticket_id>")
+ .description(t.org.ticketAssignDesc)
+ .requiredOption("--owner <principal>", t.org.owner),
+ t,
+ ).action(async (ticketId: string, opts) => {
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const detail = await scope.client.request<OrgTicketDetail>(
+ "PUT",
+ `${scope.base}/tickets/${enc(ticketId)}`,
+ { owner: String(opts.owner), ...actorFields() },
+ );
+ if (opts.json === true) printJson(detail);
+ else printLine(t.org.ticketAssigned(detail.ticketId, detail.owner ?? String(opts.owner)));
+ });
+
+ scoped(
+ ticket
+ .command("block <ticket_id>")
+ .description(t.org.ticketBlockDesc)
+ .requiredOption("--reason <text>", t.org.blockReason)
+ .option("--by <principal|ticket_id>", t.org.blockedBy),
+ t,
+ ).action(async (ticketId: string, opts) => {
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const detail = await scope.client.request<OrgTicketDetail>(
+ "POST",
+ `${scope.base}/tickets/${enc(ticketId)}/block`,
+ {
+ reason: String(opts.reason),
+ ...(opts.by !== undefined ? { by: String(opts.by) } : {}),
+ ...actorFields(),
+ },
+ );
+ if (opts.json === true) printJson(detail);
+ else printLine(t.org.ticketBlocked(detail.ticketId));
+ });
+
+ scoped(ticket.command("unblock <ticket_id>").description(t.org.ticketUnblockDesc), t).action(
+ async (ticketId: string, opts) => {
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const detail = await scope.client.request<OrgTicketDetail>(
+ "POST",
+ `${scope.base}/tickets/${enc(ticketId)}/unblock`,
+ { ...actorFields() },
+ );
+ if (opts.json === true) printJson(detail);
+ else printLine(t.org.ticketUnblocked(detail.ticketId));
+ },
+ );
+
+ scoped(
+ ticket
+ .command("progress <ticket_id>")
+ .description(t.org.ticketProgressDesc)
+ .requiredOption("-m, --message <text>", t.org.progressText),
+ t,
+ ).action(async (ticketId: string, opts) => {
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const detail = await scope.client.request<OrgTicketDetail>(
+ "POST",
+ `${scope.base}/tickets/${enc(ticketId)}/progress`,
+ { text: String(opts.message), ...actorFields() },
+ );
+ if (opts.json === true) printJson(detail);
+ else printLine(t.org.progressRecorded(detail.ticketId));
+ });
+
+ scoped(
+ ticket
+ .command("start <ticket_id>")
+ .description(t.org.ticketStartDesc)
+ .option("-m, --message <text>", t.org.startMessage)
+ .option("--workspace <path>", t.org.startWorkspace)
+ .option("--agent-id <id>", t.org.startAgentId),
+ t,
+ ).action(async (ticketId: string, opts) => {
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ // Inside a session the ticket session runs as the calling employee unless --agent-id
+ // enlists a colleague on the caller's own ticket; outside one the server picks the
+ // ticket's owner — so the plain default_agent fallback is not applied. `actorFields`
+ // carries the calling session so the server can tell an employee from a person: an
+ // employee may start a session only on a ticket it owns, and anyone else's is a 403.
+ const agentId =
+ (typeof opts.agentId === "string" ? opts.agentId.trim() : "") ||
+ process.env.PENGUIN_AGENT_ID?.trim() ||
+ undefined;
+ const res = await scope.client.request<OrgTicketStartResponse>(
+ "POST",
+ `${scope.base}/tickets/${enc(ticketId)}/start`,
+ {
+ // `agentId` last: here it is the employee the ticket session RUNS AS, which the
+ // owner may point at a colleague, and it must not be overwritten by the caller's own.
+ ...actorFields(),
+ ...(agentId !== undefined ? { agentId } : {}),
+ ...(opts.message !== undefined ? { message: String(opts.message) } : {}),
+ ...(opts.workspace !== undefined ? { workspace: String(opts.workspace) } : {}),
+ },
+ );
+ // Like `run --background`: the bare session id is what `penguin input` / `penguin logs` address later.
+ if (opts.json === true) printJson({ sessionId: res.sessionId });
+ else printLine(res.sessionId);
+ });
+
+ scoped(
+ ticket
+ .command("attach <ticket_id>")
+ .description(t.org.ticketAttachDesc)
+ .option("--session <session_id>", t.org.attachSession),
+ t,
+ ).action(async (ticketId: string, opts) => {
+ const ref = opts.session !== undefined ? String(opts.session) : callerSessionId();
+ if (ref === undefined) {
+ fail(t, t.org.attachSessionMissing());
+ return;
+ }
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const sessionId = await resolveSessionRef(scope.client, scope.projectId, ref, t);
+ // `sessionId` here is the Session to attach, not the caller's — so only the Agent id of
+ // {@link actorFields} rides along, and it is what the history entry is recorded under.
+ const { agentId } = actorFields();
+ const detail = await scope.client.request<OrgTicketDetail>(
+ "POST",
+ `${scope.base}/tickets/${enc(ticketId)}/attach`,
+ { sessionId, ...(agentId !== undefined ? { agentId } : {}) },
+ );
+ if (opts.json === true) printJson(detail);
+ else printLine(t.org.ticketAttached(detail.ticketId, sessionId));
+ });
+
+ // ---- channels ----
+
+ const channel = org.command("channel").description(t.org.channelDesc);
+
+ /** `archive` / `unarchive`: the same PATCH with the flag flipped. */
+ const setArchived = async (
+ channelId: string,
+ archived: boolean,
+ opts: { orgId?: string; projectId?: string; server?: string; json?: boolean },
+ ): Promise<void> => {
+ if (refuseDotSegments(channelId, t)) return;
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const item = await scope.client.request<OrgChannelItem>(
+ "PATCH",
+ `${scope.base}/channels/${enc(channelId)}`,
+ { archived, ...actorFields() },
+ );
+ if (opts.json === true) printJson(item);
+ else {
+ printLine(
+ archived ? t.org.channelArchived(item.channelId) : t.org.channelUnarchived(item.channelId),
+ );
+ }
+ };
+
+ scoped(channel.command("ls").description(t.org.channelLsDesc), t).action(async (opts) => {
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const res = await scope.client.request<OrgChannelsResponse>(
+ "GET",
+ `${scope.base}/channels${query(actorQuery())}`,
+ );
+ if (opts.json === true) {
+ printJson(res);
+ return;
+ }
+ if (res.channels.length === 0) {
+ printLine(t.org.channelsEmpty());
+ return;
+ }
+ process.stdout.write(renderChannels(res.channels, t));
+ });
+
+ scoped(
+ channel
+ .command("create <channel_id>")
+ .description(t.org.channelCreateDesc)
+ .option("--name <name>", t.org.channelName)
+ .option("--purpose <text>", t.org.channelPurpose),
+ t,
+ ).action(async (channelId: string, opts) => {
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ // The id travels in the body, so the server owns every rule about it; a bad one is its
+ // bad_request, not a second opinion here.
+ const item = await scope.client.request<OrgChannelItem>("POST", `${scope.base}/channels`, {
+ channelId,
+ ...(opts.name !== undefined ? { name: String(opts.name) } : {}),
+ ...(opts.purpose !== undefined ? { purpose: String(opts.purpose) } : {}),
+ ...actorFields(),
+ });
+ if (opts.json === true) printJson(item);
+ else printLine(t.org.channelCreated(item.channelId));
+ });
+
+ scoped(channel.command("show <channel_id>").description(t.org.channelShowDesc), t).action(
+ async (channelId: string, opts) => {
+ if (refuseDotSegments(channelId, t)) return;
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const detail = await scope.client.request<OrgChannelDetail>(
+ "GET",
+ `${scope.base}/channels/${enc(channelId)}${query(actorQuery())}`,
+ );
+ if (opts.json === true) printJson(detail);
+ else process.stdout.write(renderChannelDetail(detail, t));
+ },
+ );
+
+ scoped(
+ channel.command("invite <channel_id> <principals...>").description(t.org.channelInviteDesc),
+ t,
+ ).action(async (channelId: string, principals: string[], opts) => {
+ if (refuseDotSegments(channelId, t)) return;
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ // One POST per principal, in order, each printed as it lands: the route takes one
+ // principal, and a refusal then stops on the one it refused with the rest unsent.
+ for (const principal of principals) {
+ const detail = await scope.client.request<OrgChannelDetail>(
+ "POST",
+ `${scope.base}/channels/${enc(channelId)}/members`,
+ { principal, ...actorFields() },
+ );
+ if (opts.json === true) printJson(detail);
+ else printLine(t.org.channelInvited(detail.channelId, principal));
+ }
+ });
+
+ scoped(channel.command("join <channel_id>").description(t.org.channelJoinDesc), t).action(
+ async (channelId: string, opts) => {
+ if (refuseDotSegments(channelId, t)) return;
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ // The principal is the caller's own, so joining is never an invitation of someone
+ // else: a person adds itself, and an employee asks for itself and is refused — an
+ // employee reaches a channel only when a member invites it.
+ const principal = await callerPrincipal(scope.client);
+ const detail = await scope.client.request<OrgChannelDetail>(
+ "POST",
+ `${scope.base}/channels/${enc(channelId)}/members`,
+ { principal, ...actorFields() },
+ );
+ if (opts.json === true) printJson(detail);
+ else printLine(t.org.channelJoined(detail.channelId));
+ },
+ );
+
+ scoped(channel.command("leave <channel_id>").description(t.org.channelLeaveDesc), t).action(
+ async (channelId: string, opts) => {
+ if (refuseDotSegments(channelId, t)) return;
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const principal = await callerPrincipal(scope.client);
+ await scope.client.request(
+ "DELETE",
+ `${scope.base}/channels/${enc(channelId)}/members/${enc(principal)}${query(actorQuery())}`,
+ );
+ if (opts.json === true) printJson({ channelId, principal });
+ else printLine(t.org.channelLeft(channelId));
+ },
+ );
+
+ scoped(
+ channel.command("remove <channel_id> <principal>").description(t.org.channelRemoveDesc),
+ t,
+ ).action(async (channelId: string, principal: string, opts) => {
+ if (refuseDotSegments(channelId, t) || refuseDotSegments(principal, t)) return;
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ await scope.client.request(
+ "DELETE",
+ `${scope.base}/channels/${enc(channelId)}/members/${enc(principal)}${query(actorQuery())}`,
+ );
+ if (opts.json === true) printJson({ channelId, principal });
+ else printLine(t.org.channelMemberRemoved(channelId, principal));
+ });
+
+ scoped(channel.command("archive <channel_id>").description(t.org.channelArchiveDesc), t).action(
+ async (channelId: string, opts) => setArchived(channelId, true, opts),
+ );
+
+ scoped(
+ channel.command("unarchive <channel_id>").description(t.org.channelUnarchiveDesc),
+ t,
+ ).action(async (channelId: string, opts) => setArchived(channelId, false, opts));
+
+ scoped(
+ channel
+ .command("tail")
+ .description(t.org.channelTailDesc)
+ .option("--channel <id>", t.org.channelOpt)
+ .option("--date <date>", t.org.channelDate)
+ .option("-n, --count <count>", t.org.channelCount),
+ t,
+ ).action(async (opts) => {
+ const count =
+ opts.count !== undefined ? parseCount(String(opts.count), t) : DEFAULT_MESSAGE_COUNT;
+ if (count === null) return;
+ const channelId = channelOf(opts.channel);
+ if (refuseDotSegments(channelId, t)) return;
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const res = await scope.client.request<OrgChannelMessagesResponse>(
+ "GET",
+ `${scope.base}/channels/${enc(channelId)}/messages${query([
+ ["date", opts.date !== undefined ? String(opts.date) : undefined],
+ ...actorQuery(),
+ ])}`,
+ );
+ const messages = res.messages.slice(-count);
+ if (opts.json === true) {
+ printJson({ ...res, messages });
+ return;
+ }
+ if (messages.length === 0) {
+ printLine(t.org.channelEmpty(res.channelId, res.date));
+ return;
+ }
+ // Message lines carry the sender, never the channel; name it above them whenever the
+ // reader did not get the default one.
+ if (res.channelId !== DEFAULT_CHANNEL_ID) printLine(dim(t.org.channelHeader(res.channelId)));
+ process.stdout.write(`${messages.map((m) => messageLine(m, t)).join("\n")}\n`);
+ });
+
+ scoped(
+ channel
+ .command("send")
+ .description(t.org.channelSendDesc)
+ .requiredOption("-m, --message <text>", t.org.channelText)
+ .option("--channel <id>", t.org.channelOpt)
+ .option("--ref-ticket <ticket_id>", t.org.refTicket)
+ .option("--ref-session <session_id>", t.org.refSession),
+ t,
+ ).action(async (opts) => {
+ const channelId = channelOf(opts.channel);
+ if (refuseDotSegments(channelId, t)) return;
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const refs = {
+ ...(opts.refTicket !== undefined ? { ticket: String(opts.refTicket) } : {}),
+ ...(opts.refSession !== undefined ? { session: String(opts.refSession) } : {}),
+ };
+ const msg = await scope.client.request<OrgChannelMessage>(
+ "POST",
+ `${scope.base}/channels/${enc(channelId)}/messages`,
+ {
+ text: String(opts.message),
+ ...(Object.keys(refs).length > 0 ? { refs } : {}),
+ ...actorFields(),
+ },
+ );
+ if (opts.json === true) printJson(msg);
+ else printLine(t.org.messageSent(msg.id));
+ });
+
+ // ---- handbook ----
+
+ const handbook = org.command("handbook").description(t.org.handbookDesc);
+ /** A handbook path keeps its `/` separators; each segment is encoded on its own. */
+ const encPath = (rel: string): string => rel.split("/").map(enc).join("/");
+
+ scoped(handbook.command("list").description(t.org.handbookListDesc), t).action(async (opts) => {
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const res = await scope.client.request<OrgHandbookFilesResponse>(
+ "GET",
+ `${scope.base}/handbook/files`,
+ );
+ if (opts.json === true) {
+ printJson(res);
+ return;
+ }
+ process.stdout.write(
+ `${res.files.map((f) => `${f.path}\t${f.size}\t${f.updatedAt}`).join("\n")}\n`,
+ );
+ });
+
+ scoped(
+ handbook
+ .command("show")
+ .description(t.org.handbookShowDesc)
+ .argument("[path]", t.org.handbookPath),
+ t,
+ ).action(async (relArg: string | undefined, opts) => {
+ const rel = relArg ?? "README.md";
+ if (refuseDotSegments(rel, t)) return;
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const res = await scope.client.request<OrgHandbookFileResponse>(
+ "GET",
+ `${scope.base}/handbook/files/${encPath(rel)}`,
+ );
+ if (opts.json === true) printJson(res);
+ else process.stdout.write(res.content.endsWith("\n") ? res.content : `${res.content}\n`);
+ });
+
+ scoped(
+ handbook
+ .command("write")
+ .description(t.org.handbookWriteDesc)
+ .argument("<path>", t.org.handbookPath)
+ .option("-m, --message <text>", t.org.handbookText)
+ .option("--file <file>", t.org.handbookFile),
+ t,
+ ).action(async (rel: string, opts) => {
+ if (refuseDotSegments(rel, t)) return;
+ if ((opts.message === undefined) === (opts.file === undefined)) {
+ fail(t, t.org.handbookOneSource);
+ return;
+ }
+ const content =
+ opts.file !== undefined ? fs.readFileSync(String(opts.file), "utf8") : String(opts.message);
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const res = await scope.client.request<OrgHandbookFileResponse>(
+ "PUT",
+ `${scope.base}/handbook/files/${encPath(rel)}`,
+ { content },
+ );
+ if (opts.json === true) printJson(res);
+ else printLine(t.org.handbookWritten(res.path));
+ });
+
+ scoped(
+ handbook.command("rm").description(t.org.handbookRmDesc).argument("<path>", t.org.handbookPath),
+ t,
+ ).action(async (rel: string, opts) => {
+ if (refuseDotSegments(rel, t)) return;
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ await scope.client.request("DELETE", `${scope.base}/handbook/files/${encPath(rel)}`);
+ if (opts.json === true) printJson({ ok: true, path: rel });
+ else printLine(t.org.handbookRemoved(rel));
+ });
+
+ // ---- finance ----
+
+ scoped(
+ org
+ .command("finance")
+ .description(t.org.financeDesc)
+ .option("--period <yyyy-mm>", t.org.period),
+ t,
+ ).action(async (opts) => {
+ const scope = await orgScope(opts, t);
+ if (scope === null) return;
+ const qs = opts.period !== undefined ? `?period=${enc(String(opts.period))}` : "";
+ const res = await scope.client.request<OrgFinanceResponse>("GET", `${scope.base}/finance${qs}`);
+ if (opts.json === true) {
+ printJson(res);
+ return;
+ }
+ process.stdout.write(renderFinance(res, t));
+ // Tokens were counted but some model had no pricing: the figures are a lower bound.
+ if (res.unpriced) process.stderr.write(`${t.org.unpriced()}\n`);
+ });
+}
+
+/**
+ * A written calendar event: the confirmation line, then the rota advice the server answered
+ * with — one line each, so a desk that now shares a minute with another is visible at the
+ * moment the event is written rather than at the month's bill. The warnings stay in the
+ * server's English; only the label is localized.
+ */
+function printCalendarWrite(t: Messages, item: OrgCalendarWriteResponse): void {
+ printLine(
+ t.org.calendarWritten(
+ item.agentId,
+ item.name,
+ item.enabled ? t.schedule.enabled() : t.schedule.disabled(),
+ item.nextFireAt,
+ ),
+ );
+ for (const warning of item.warnings ?? []) printLine(t.org.calendarWarning(warning));
+}
diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.ts
index 46727e75..7f3c82ce 100644
--- a/packages/cli/src/i18n.ts
+++ b/packages/cli/src/i18n.ts
@@ -1,3 +1,5 @@
+import type { OrgChannelNoticeKind } from "@prismshadow/penguin-server/api";
+
/**
* CLI text internationalization (i18n).
*
@@ -247,6 +249,278 @@ export interface Messages {
colLastFired(): string;
colStatus(): string;
};
+ /** `penguin org`: company mode — a thin client over the organization API (the organization's files stay the single source of truth; every DTO is a projection). */
+ org: {
+ desc: string;
+ lsDesc: string;
+ createDesc: string;
+ showDesc: string;
+ chartDesc: string;
+ hireDesc: string;
+ employeeDesc: string;
+ employeeSetDesc: string;
+ leaveDesc: string;
+ deskDesc: string;
+ deskShowDesc: string;
+ deskRenewDesc: string;
+ calendarDesc: string;
+ calendarLsDesc: string;
+ calendarAddDesc: string;
+ calendarUpdateDesc: string;
+ calendarRmDesc: string;
+ ticketDesc: string;
+ ticketLsDesc: string;
+ ticketShowDesc: string;
+ ticketCreateDesc: string;
+ ticketMoveDesc: string;
+ ticketAssignDesc: string;
+ ticketBlockDesc: string;
+ ticketUnblockDesc: string;
+ ticketProgressDesc: string;
+ ticketStartDesc: string;
+ ticketAttachDesc: string;
+ channelDesc: string;
+ channelLsDesc: string;
+ channelCreateDesc: string;
+ channelShowDesc: string;
+ channelInviteDesc: string;
+ channelJoinDesc: string;
+ channelLeaveDesc: string;
+ channelRemoveDesc: string;
+ channelArchiveDesc: string;
+ channelUnarchiveDesc: string;
+ channelTailDesc: string;
+ channelSendDesc: string;
+ handbookDesc: string;
+ handbookListDesc: string;
+ handbookShowDesc: string;
+ handbookWriteDesc: string;
+ handbookRmDesc: string;
+ financeDesc: string;
+ /** --org-id: the organization (defaults to PENGUIN_ORG_ID, the control environment of desk and ticket sessions). */
+ orgId: string;
+ /** create's --org-id: the id to create (never taken from the environment). */
+ newOrgId: string;
+ mission: string;
+ orgName: string;
+ /** create's --language: the organization's working language (default: detected from the mission). */
+ orgLanguageOption: string;
+ /** hire's --agent-id: employ an existing Agent (XOR --new-agent). */
+ hireAgentId: string;
+ /** hire's --new-agent: create the Agent and employ it. */
+ newAgent: string;
+ newAgentName: string;
+ newAgentDescription: string;
+ /** --skills: extra library plugins for the new Agent, comma-separated (added to the required pair). */
+ skills: string;
+ title: string;
+ reportsTo: string;
+ /** Employee workspace: a sub-directory of the shared workspace (`.` = all of it) or an absolute path, written as given. */
+ employeeWorkspace: string;
+ /** hire's --workspace: the same spec, with the default the employee's own sub-directory. */
+ hireWorkspace: string;
+ /** --budget: monthly USD for the employee plus every subordinate. */
+ budget: string;
+ /** create's --ceo-budget: the CEO's monthly USD, which is the whole company's. */
+ ceoBudget: string;
+ duties: string;
+ /** calendar's --agent-id: the employee the event belongs to (defaults to PENGUIN_AGENT_ID); a filter on `ls`. */
+ calendarAgentId: string;
+ calendarTitle: string;
+ /** ticket ls filters. */
+ statusFilter: string;
+ ownerFilter: string;
+ blockedFilter: string;
+ ticketTitle: string;
+ /** create's --slug: the words of the ticket id, for a title that yields none. */
+ ticketSlug: string;
+ goal: string;
+ criteria: string;
+ /** --body-file: the whole Markdown body from a file (XOR --goal). */
+ bodyFile: string;
+ /** --owner: the ONE responsible principal; defaults to the caller on `create`. */
+ owner: string;
+ parent: string;
+ /** --notify: principals told when the ticket ends, comma-separated. */
+ notify: string;
+ priority: string;
+ due: string;
+ /** move's --to: the target column. */
+ moveTo: string;
+ /** move's --reason: required when moving into rejected. */
+ moveReason: string;
+ blockReason: string;
+ /** block's --by: who or which ticket the ticket waits for. */
+ blockedBy: string;
+ progressText: string;
+ /** start's -m: a note appended to the ticket text the session opens with. */
+ startMessage: string;
+ /** start's --workspace: another directory inside the shared workspace (default: the employee's desk workspace). */
+ startWorkspace: string;
+ /** start's --agent-id: which employee the ticket session runs as (default: the caller inside a session, else the ticket's owner). */
+ startAgentId: string;
+ /** attach's --session: the session to attach (default: the calling session). */
+ attachSession: string;
+ /** tail / send's --channel: which channel to read or write in (default: the all-hands channel). */
+ channelOpt: string;
+ /** create's --name / --purpose. */
+ channelName: string;
+ channelPurpose: string;
+ channelDate: string;
+ channelCount: string;
+ channelText: string;
+ handbookPath: string;
+ handbookText: string;
+ handbookFile: string;
+ handbookOneSource: string;
+ refTicket: string;
+ refSession: string;
+ /** finance's --period: yyyy-mm (default: the current month). */
+ period: string;
+ /** No --org-id and no PENGUIN_ORG_ID: there is no default organization. */
+ orgIdMissing(): string;
+ /** hire: --agent-id XOR --new-agent. */
+ hireTargetConflict(): string;
+ /** hire: --name / --description / --skills describe the new Agent only. */
+ newAgentFieldsOnly(): string;
+ /** A non-numeric or negative budget on any of the budget flags (named, since there are several). */
+ budgetInvalid(flag: string, value: string): string;
+ /** employee set with no field to change. */
+ nothingToSet(): string;
+ /** A --language value that is neither zh nor en. */
+ languageInvalid(value: string): string;
+ /** A --status / --to value that is not a kanban column. */
+ statusInvalid(value: string): string;
+ priorityInvalid(value: string): string;
+ /** ticket create: --goal XOR --body-file. */
+ ticketBodyConflict(): string;
+ criteriaNeedsGoal(): string;
+ bodyFileUnreadable(file: string): string;
+ countInvalid(value: string): string;
+ /** An id or handbook path with a `.` / `..` segment: the URL would collapse onto another route. */
+ pathSegmentInvalid(value: string): string;
+ /** ticket attach outside a session and without --session. */
+ attachSessionMissing(): string;
+ /** Confirmations of the write commands. */
+ created(orgId: string, ceoDeskSessionId: string | undefined): string;
+ hired(agentId: string, title: string, reportsTo: string | null): string;
+ employeeUpdated(agentId: string): string;
+ left(agentId: string): string;
+ desk(
+ agentId: string,
+ sessionId: string,
+ workspace: string,
+ openedAt: string,
+ created: boolean,
+ ): string;
+ deskRenewed(agentId: string, sessionId: string): string;
+ calendarWritten(
+ agentId: string,
+ name: string,
+ enabledText: string,
+ nextFireAt: string | undefined,
+ ): string;
+ /** One advisory rota line the server answered a calendar write with (its text stays English). */
+ calendarWarning(warning: string): string;
+ calendarRemoved(agentId: string, name: string): string;
+ ticketCreated(ticketId: string, status: string): string;
+ ticketMoved(ticketId: string, status: string): string;
+ ticketAssigned(ticketId: string, owner: string): string;
+ ticketBlocked(ticketId: string): string;
+ ticketUnblocked(ticketId: string): string;
+ progressRecorded(ticketId: string): string;
+ ticketAttached(ticketId: string, sessionId: string): string;
+ channelCreated(channelId: string): string;
+ channelInvited(channelId: string, principal: string): string;
+ channelJoined(channelId: string): string;
+ channelLeft(channelId: string): string;
+ channelMemberRemoved(channelId: string, principal: string): string;
+ channelArchived(channelId: string): string;
+ channelUnarchived(channelId: string): string;
+ messageSent(id: string): string;
+ handbookWritten(path: string): string;
+ handbookRemoved(path: string): string;
+ /** Empty states. */
+ empty(projectId: string): string;
+ calendarEmpty(): string;
+ ticketsEmpty(): string;
+ channelsEmpty(): string;
+ channelEmpty(channelId: string, date: string): string;
+ /** `show`: one line per fact. */
+ showHead(name: string, orgId: string, status: string): string;
+ showMission(mission: string): string;
+ showLanguage(language: string): string;
+ showEmployees(count: number, running: number, paused: number): string;
+ showBoard(counts: string, blocked: number): string;
+ showSpend(period: string, spend: string): string;
+ showPending(mentions: number, review: number, blockedByMe: number): string;
+ /** An invalid organization / employee / ticket, with the reason (a line in `show`, a cell in tables). */
+ invalid(reason: string): string;
+ /** `ticket show`: the derived state above the file. */
+ ticketHead(
+ ticketId: string,
+ status: string,
+ running: boolean,
+ blocked: string | undefined,
+ ): string;
+ ticketFigures(cost: string, rolledUp: string, sessions: number, children: number): string;
+ /** `ticket show`: the labels of the ticket's frontmatter fields, above the prose sections. */
+ ticketFields(): Record<
+ | "title"
+ | "owner"
+ | "parent"
+ | "notify"
+ | "priority"
+ | "due"
+ | "blocked"
+ | "blockedBy"
+ | "sessions",
+ string
+ >;
+ /** `ticket show`: the heading above the operation history; the actions themselves stay in English. */
+ ticketHistory(): string;
+ /**
+ * A `system` line rendered from its structured notice, in the reader's language; a kind
+ * this build does not know falls back to the message's English `text`.
+ */
+ notices: Record<OrgChannelNoticeKind, (p: Record<string, string>) => string>;
+ /** The all-hands channel's label; its stored name is never shown. */
+ allHands(): string;
+ /** `channel tail` on any channel but the default one: a dim line naming it above the messages. */
+ channelHeader(channelId: string): string;
+ /** `channel show`: the head line, then the lines the channel actually has. */
+ channelHead(name: string, channelId: string, members: number, archived: boolean): string;
+ channelPurposeLine(purpose: string): string;
+ channelCreatedBy(principal: string, createdAt: string): string;
+ channelLastMessage(time: string): string;
+ financeTotal(period: string, total: string): string;
+ /** stderr note under `finance`: some usage had no pricing, so the total is a lower bound. */
+ unpriced(): string;
+ colEmployees(): string;
+ colRunning(): string;
+ colOpen(): string;
+ colBlocked(): string;
+ colSpend(): string;
+ colNote(): string;
+ /** Chart / finance: the employee's job title. */
+ colJobTitle(): string;
+ /** Tickets: the ticket title. */
+ colTitle(): string;
+ colState(): string;
+ colOwn(): string;
+ colCumulative(): string;
+ colBudget(): string;
+ colNext(): string;
+ colPriority(): string;
+ colOwner(): string;
+ colTicket(): string;
+ colRolledUp(): string;
+ colMembers(): string;
+ colArchived(): string;
+ colUnread(): string;
+ colMentions(): string;
+ colPrincipal(): string;
+ };
/** Server-connection layer: resolution, auto-start, tokens, streams. */
client: {
invalidServerUrl(value: string): string;
@@ -781,6 +1055,262 @@ const en: Messages = {
colLastFired: () => "LAST FIRED",
colStatus: () => "STATUS",
},
+ org: {
+ desc: "Company mode: manage an organization (employees, desks, calendar, tickets, channels, finance)",
+ lsDesc: "List the project's organizations",
+ createDesc:
+ "Create an organization: its CEO Agent, the CEO's desk session and the initialization run",
+ showDesc:
+ "Overview: employees and their states, board counts, spend against budget, pending items",
+ chartDesc: "The employee tree with titles, states, spend and budgets",
+ hireDesc:
+ "Employ an Agent: an existing one (--agent-id) or a new one (--new-agent), under --reports-to",
+ employeeDesc: "Manage employees",
+ employeeSetDesc: "Update an employee's entry in the tree (only the given fields change)",
+ leaveDesc: "Remove an employee from the organization (not the CEO); the Agent itself stays",
+ deskDesc: "Desk sessions (one standing session per employee)",
+ deskShowDesc: "The employee's desk session id and Workspace (opens the desk if it has none)",
+ deskRenewDesc: "Open a fresh desk session for the employee (resets its context)",
+ calendarDesc: "Calendar events (schedules that fire into the employee's desk session)",
+ calendarLsDesc: "List the organization's calendar events (one employee's with --agent-id)",
+ calendarAddDesc:
+ "Create a calendar event (writes the event file through the API; enabled by default — use --disabled to opt out)",
+ calendarUpdateDesc:
+ "Update a calendar event (read-modify-write: unspecified fields keep their stored values)",
+ calendarRmDesc: "Delete a calendar event (no prompt)",
+ ticketDesc: "Tickets on the kanban board",
+ ticketLsDesc: "List the board's tickets (filtered locally by --status / --owner / --blocked)",
+ ticketShowDesc: "Show a ticket: the derived figures, then the ticket file",
+ ticketCreateDesc: "Create a ticket in the proposed column",
+ ticketMoveDesc: "Move a ticket to another column (a reason is required for rejected)",
+ ticketAssignDesc: "Set a ticket's owner",
+ ticketBlockDesc: "Mark a ticket blocked (it stays in its column)",
+ ticketUnblockDesc: "Clear a ticket's blocked state",
+ ticketProgressDesc: "Append a progress entry (attributed to the calling session)",
+ ticketStartDesc:
+ "Open a ticket session that works on the ticket in the background; prints the session id. Only the ticket's owner (its desk) or a person may start one — assign the ticket to move it to another employee",
+ ticketAttachDesc:
+ "Attach an existing session as a contributor (defaults to the calling session)",
+ channelDesc:
+ "The organization's channels (default_channel is the all-hands one everybody is in)",
+ channelLsDesc: "List the channels: every one of them for a person, its own for an employee",
+ channelCreateDesc:
+ "Open a channel; only its creator is in it, everyone else arrives by invitation",
+ channelShowDesc: "Show a channel and its members",
+ channelInviteDesc: "Invite principals into a channel (any member may)",
+ channelJoinDesc: "Join a channel yourself (people only; an employee waits to be invited)",
+ channelLeaveDesc: "Leave a channel",
+ channelRemoveDesc: "Remove another member from a channel (people only)",
+ channelArchiveDesc: "Archive a channel: read-only until it is unarchived (people only)",
+ channelUnarchiveDesc: "Unarchive a channel (people only)",
+ channelTailDesc: "Print a channel's last messages of a day (20 unless -n is given)",
+ channelSendDesc:
+ "Send a message to a channel (@agent:<id> / @all mention its members and trigger their desks)",
+ handbookDesc:
+ "The organization handbook: the knowledge base under handbook/, whose README.md is the index every run reads first",
+ handbookListDesc: "List the handbook files (path, size, updated), the index first",
+ handbookShowDesc: "Print a handbook document (the index when no path is given)",
+ handbookWriteDesc: "Create or replace a handbook document from -m or --file",
+ handbookRmDesc: "Delete a handbook document (the index cannot be deleted)",
+ financeDesc: "Spend per employee (along the reporting line) and per ticket, against budgets",
+ orgId:
+ "Organization id (defaults to PENGUIN_ORG_ID, set inside desk and ticket sessions; no other default)",
+ newOrgId:
+ "Id of the organization to create (letters, digits, underscores; also its directory name)",
+ mission: "The organization's mission",
+ orgName: "Display name (defaults to the id)",
+ orgLanguageOption:
+ "Working language of everything the organization writes: zh or en (defaults to the mission's own language)",
+ hireAgentId: "Employ this existing Agent (mutually exclusive with --new-agent)",
+ newAgent: "Create an Agent with this id and employ it (mutually exclusive with --agent-id)",
+ newAgentName: "Display name of the new Agent",
+ newAgentDescription: "Description of the new Agent",
+ skills:
+ "Extra library plugins for the new Agent, comma-separated (added to agent-company,agent-development)",
+ title: "Job title",
+ reportsTo: "Agent id of the manager",
+ employeeWorkspace:
+ "Workspace: a sub-directory of the shared workspace (. = all of it) or an absolute path, written as given",
+ hireWorkspace:
+ "Workspace: a sub-directory of the shared workspace or an absolute path, written as given (defaults to a sub-directory named after the employee)",
+ budget: "Monthly budget in USD for the employee plus everyone below it",
+ ceoBudget:
+ "The CEO's monthly budget in USD, which is the whole company's (budgets accumulate along the reporting line)",
+ duties: "Duties, in prose",
+ calendarAgentId:
+ "Employee the event belongs to (defaults to PENGUIN_AGENT_ID); on ls, list only this employee's events",
+ calendarTitle: "Event title",
+ statusFilter: "Only this column: proposed, in_progress, review, done or rejected",
+ ownerFilter: "Only tickets owned by this principal (agent:<id> / user:<id>)",
+ blockedFilter: "Only blocked tickets",
+ ticketTitle: "Ticket title",
+ ticketSlug: "The ticket id's words: lowercase English words joined by hyphens",
+ goal: "The goal, naming every input it relies on by full path (mutually exclusive with --body-file)",
+ criteria: "Acceptance criteria, naming the expected deliverables by full path (with --goal)",
+ bodyFile: "Read the whole Markdown body from this file (the header is still generated)",
+ owner: "The responsible principal (agent:<id> / user:<id>); defaults to you on create",
+ parent: "Parent ticket id",
+ notify: "Principals notified when the ticket ends, comma-separated",
+ priority: "Priority: P0, P1 or P2",
+ due: "Due date (yyyy-mm-dd)",
+ moveTo: "Target column: proposed, in_progress, review, done or rejected",
+ moveReason: "Why (required when moving into rejected; recorded under Result)",
+ blockReason: "Why the ticket is blocked",
+ blockedBy: "Who or which ticket it waits for (a principal or a ticket id)",
+ progressText: "The progress entry, naming the files it refers to by full path",
+ startMessage: "A note appended to the ticket text the session opens with",
+ startWorkspace:
+ "Another directory inside the shared workspace (defaults to the employee's desk workspace)",
+ startAgentId:
+ "Which employee the session runs as: a colleague you enlist on your own ticket (defaults to you inside a session, otherwise the ticket's owner)",
+ attachSession:
+ "The session to attach, full id or unique fragment (defaults to PENGUIN_SESSION_ID)",
+ channelOpt: "Channel to read or write in (default: default_channel, the all-hands channel)",
+ channelName: "Display name (defaults to the id)",
+ channelPurpose: "What the channel is for",
+ channelDate: "Day to read (yyyy-mm-dd in the organization's timezone; defaults to today)",
+ channelCount: "Number of messages to print (default 20)",
+ channelText: "Message text (@agent:<id> or @all to mention, inside the channel's membership)",
+ handbookPath:
+ "Path relative to handbook/ (plain segments, e.g. decisions/2026-09-02-hire-plan.md)",
+ handbookText: "Document text",
+ handbookFile: "Read the document text from a local file",
+ handbookOneSource: "Give exactly one of -m <text> or --file <file>.",
+ refTicket: "Ticket the message refers to",
+ refSession: "Session the message refers to",
+ period: "Month to report (yyyy-mm; defaults to the current month)",
+ orgIdMissing: () =>
+ "No organization given: pass --org-id <id>, or set PENGUIN_ORG_ID (desk and ticket sessions carry it in their environment).",
+ hireTargetConflict: () =>
+ "Pass exactly one of --agent-id (an existing Agent) and --new-agent (create one).",
+ newAgentFieldsOnly: () => "--name, --description and --skills describe --new-agent only.",
+ budgetInvalid: (flag, value) =>
+ `Invalid ${flag} value "${value}": expected a non-negative amount in USD.`,
+ nothingToSet: () => "Nothing to update: pass at least one field.",
+ languageInvalid: (value) => `Invalid --language value "${value}": expected zh or en.`,
+ statusInvalid: (value) =>
+ `Invalid column "${value}": expected proposed, in_progress, review, done or rejected.`,
+ priorityInvalid: (value) => `Invalid --priority value "${value}": expected P0, P1 or P2.`,
+ ticketBodyConflict: () => "Pass exactly one of --goal and --body-file.",
+ criteriaNeedsGoal: () => "--criteria goes with --goal.",
+ bodyFileUnreadable: (file) => `Cannot read --body-file ${file}.`,
+ countInvalid: (value) => `Invalid -n value "${value}": expected a positive integer.`,
+ pathSegmentInvalid: (value) =>
+ `Invalid name "${value}": "." and ".." are neither an id nor a handbook path.`,
+ attachSessionMissing: () =>
+ "No session to attach: pass --session <id>, or run inside a session (PENGUIN_SESSION_ID).",
+ created: (orgId, ceoDeskSessionId) =>
+ `Organization ${orgId} created${ceoDeskSessionId !== undefined ? ` (CEO desk session ${ceoDeskSessionId})` : ""}.`,
+ hired: (agentId, title, reportsTo) =>
+ `Employee ${agentId} hired as ${title}${reportsTo !== null ? `, reporting to ${reportsTo}` : ""}.`,
+ employeeUpdated: (agentId) => `Employee ${agentId} updated.`,
+ left: (agentId) => `Employee ${agentId} left the organization.`,
+ desk: (agentId, sessionId, workspace, openedAt, created) =>
+ `Desk of ${agentId}: session ${sessionId} (workspace ${workspace}, opened ${openedAt})${created ? " — opened just now" : ""}`,
+ deskRenewed: (agentId, sessionId) => `Desk of ${agentId} renewed: session ${sessionId}.`,
+ calendarWritten: (agentId, name, enabledText, nextFireAt) =>
+ `Calendar event ${agentId}/${name} written (${enabledText}${nextFireAt !== undefined ? `, next fire ${nextFireAt}` : ""}).`,
+ calendarWarning: (warning) => `Rota notice: ${warning}`,
+ calendarRemoved: (agentId, name) => `Calendar event ${agentId}/${name} removed.`,
+ ticketCreated: (ticketId, status) => `Ticket ${ticketId} created (${status}).`,
+ ticketMoved: (ticketId, status) => `Ticket ${ticketId} moved to ${status}.`,
+ ticketAssigned: (ticketId, owner) => `Ticket ${ticketId} assigned to ${owner}.`,
+ ticketBlocked: (ticketId) => `Ticket ${ticketId} marked blocked.`,
+ ticketUnblocked: (ticketId) => `Ticket ${ticketId} unblocked.`,
+ progressRecorded: (ticketId) => `Progress recorded on ticket ${ticketId}.`,
+ ticketAttached: (ticketId, sessionId) => `Session ${sessionId} attached to ticket ${ticketId}.`,
+ channelCreated: (channelId) => `Channel ${channelId} created.`,
+ channelInvited: (channelId, principal) => `${principal} invited to ${channelId}.`,
+ channelJoined: (channelId) => `Joined ${channelId}.`,
+ channelLeft: (channelId) => `Left ${channelId}.`,
+ channelMemberRemoved: (channelId, principal) => `${principal} removed from ${channelId}.`,
+ channelArchived: (channelId) => `Channel ${channelId} archived.`,
+ channelUnarchived: (channelId) => `Channel ${channelId} unarchived.`,
+ messageSent: (id) => `Message ${id} sent.`,
+ handbookWritten: (path) => `Handbook document ${path} written.`,
+ handbookRemoved: (path) => `Handbook document ${path} removed.`,
+ empty: (projectId) => `No organizations in project ${projectId}.`,
+ calendarEmpty: () => "No calendar events.",
+ ticketsEmpty: () => "No tickets match.",
+ channelsEmpty: () => "No channels.",
+ channelEmpty: (channelId, date) => `No messages in ${channelId} on ${date}.`,
+ showHead: (name, orgId, status) => `${name} (${orgId}) — ${status}`,
+ showMission: (mission) => `Mission: ${mission}`,
+ showLanguage: (language) => `Working language: ${language}`,
+ showEmployees: (count, running, paused) =>
+ `Employees: ${count} (${running} running, ${paused} paused)`,
+ showBoard: (counts, blocked) => `Board: ${counts} (${blocked} blocked)`,
+ showSpend: (period, spend) => `Spend (${period}): ${spend}`,
+ showPending: (mentions, review, blockedByMe) =>
+ `Pending: ${mentions} mentions, ${review} tickets to review, ${blockedByMe} blocked by me`,
+ invalid: (reason) => `invalid: ${reason}`,
+ ticketHead: (ticketId, status, running, blocked) =>
+ `Ticket ${ticketId}: ${status}${running ? ", running" : ""}${blocked !== undefined ? `, blocked (${blocked})` : ""}`,
+ ticketFigures: (cost, rolledUp, sessions, children) =>
+ `Cost ${cost} (rolled up ${rolledUp}), ${sessions} sessions, ${children} child tickets`,
+ ticketFields: () => ({
+ title: "Title",
+ owner: "Owner",
+ parent: "Parent",
+ notify: "Notify",
+ priority: "Priority",
+ due: "Due",
+ blocked: "Blocked",
+ blockedBy: "Blocked by",
+ sessions: "Sessions",
+ }),
+ ticketHistory: () => "History:",
+ notices: {
+ employee_joined: (p) => `${p.agent} joined as ${p.title}, reporting to ${p.reportsTo}.`,
+ employee_left: (p) => `${p.agent} left the organization; reports now go to ${p.reportsTo}.`,
+ channel_created: (p) => `${p.by} created the channel.`,
+ channel_archived: (p) => `${p.by} archived the channel.`,
+ channel_unarchived: (p) => `${p.by} unarchived the channel.`,
+ channel_joined: (p) => `${p.principal} joined the channel.`,
+ channel_invited: (p) => `${p.by} invited ${p.principal} to the channel.`,
+ channel_left: (p) => `${p.principal} left the channel.`,
+ channel_removed: (p) => `${p.by} removed ${p.principal} from the channel.`,
+ budget_warned: (p) =>
+ `Budget warning: ${p.agent} has used ${p.percent}% of its ${p.period} budget (${p.cost} / ${p.budget} USD).`,
+ budget_paused: (p) =>
+ `Budget pause: ${p.agent} reached ${p.percent}% of its ${p.period} budget (${p.cost} / ${p.budget} USD); its calendar and its subordinates' are paused.`,
+ ticket_blocked: (p) => `Ticket ${p.ticket} (${p.title}) is now blocked.`,
+ ticket_done: (p) => `Ticket ${p.ticket} (${p.title}) is now done.`,
+ ticket_rejected: (p) => `Ticket ${p.ticket} (${p.title}) is now rejected.`,
+ },
+ allHands: () => "All hands",
+ channelHeader: (channelId) => `[channel ${channelId}]`,
+ channelHead: (name, channelId, members, archived) =>
+ `${name} (${channelId}) — ${members} members${archived ? ", archived" : ""}`,
+ channelPurposeLine: (purpose) => `Purpose: ${purpose}`,
+ channelCreatedBy: (principal, createdAt) => `Created by ${principal} on ${createdAt}`,
+ channelLastMessage: (time) => `Last message: ${time}`,
+ financeTotal: (period, total) => `Total (${period}): ${total}`,
+ unpriced: () =>
+ "[unpriced] some usage ran on a model without pricing: the figures are a lower bound",
+ colEmployees: () => "EMPLOYEES",
+ colRunning: () => "RUNNING",
+ colOpen: () => "OPEN",
+ colBlocked: () => "BLOCKED",
+ colSpend: () => "SPEND",
+ colNote: () => "NOTE",
+ colJobTitle: () => "TITLE",
+ colTitle: () => "TITLE",
+ colState: () => "STATE",
+ colOwn: () => "OWN",
+ colCumulative: () => "CUMULATIVE",
+ colBudget: () => "BUDGET",
+ colNext: () => "NEXT",
+ colPriority: () => "PRIORITY",
+ colOwner: () => "OWNER",
+ colTicket: () => "TICKET",
+ colRolledUp: () => "ROLLED UP",
+ colMembers: () => "MEMBERS",
+ colArchived: () => "ARCHIVED",
+ colUnread: () => "UNREAD",
+ colMentions: () => "@ME",
+ colPrincipal: () => "PRINCIPAL",
+ },
client: {
invalidServerUrl: (value) => `Invalid server URL "${value}": expected http(s)://host[:port].`,
remoteNeedsToken: (url) =>
@@ -1300,6 +1830,239 @@ const zh: Messages = {
colLastFired: () => "最近触发",
colStatus: () => "状态",
},
+ org: {
+ desc: "公司模式:管理组织(员工、工位、日程、工单、频道、财务)",
+ lsDesc: "列出 Project 的组织",
+ createDesc: "创建组织:生成 CEO Agent、开 CEO 的工位会话并发起初始化会话",
+ showDesc: "概览:员工与状态、看板计数、预算占用、待处理事项",
+ chartDesc: "员工树:头衔、状态、支出与预算",
+ hireDesc: "招募员工:既有 Agent(--agent-id)或新建 Agent(--new-agent),汇报给 --reports-to",
+ employeeDesc: "管理员工",
+ employeeSetDesc: "更新员工树条目(只改动给出的字段)",
+ leaveDesc: "将员工移出组织(CEO 不可);Agent 本身保留",
+ deskDesc: "工位会话(每位员工一个常设会话)",
+ deskShowDesc: "员工的工位会话 id 与 Workspace(尚无工位时开一个)",
+ deskRenewDesc: "为员工换一个新的工位会话(重置上下文)",
+ calendarDesc: "日程项(定时发往员工工位会话的任务)",
+ calendarLsDesc: "列出组织的日程项(--agent-id 限定为某位员工)",
+ calendarAddDesc: "创建日程项(经 API 写入日程文件;缺省即启用——用 --disabled 关闭)",
+ calendarUpdateDesc: "更新日程项(读改写:未指定的字段保留存储值)",
+ calendarRmDesc: "删除日程项(不做确认)",
+ ticketDesc: "看板上的工单",
+ ticketLsDesc: "列出看板工单(--status / --owner / --blocked 在本地过滤)",
+ ticketShowDesc: "查看工单:先打印派生数据,再打印工单文件",
+ ticketCreateDesc: "在 proposed 列创建工单",
+ ticketMoveDesc: "把工单移到另一列(移入 rejected 须给 --reason)",
+ ticketAssignDesc: "设置工单负责人",
+ ticketBlockDesc: "标记工单为阻塞(留在所在列)",
+ ticketUnblockDesc: "清除工单的阻塞状态",
+ ticketProgressDesc: "追加一条进展(记为当前会话所写)",
+ ticketStartDesc:
+ "新开一个在后台处理该工单的工单会话;打印会话 id。只有工单的负责人(其工位)或人可以发起——要交给别的员工,改派负责人",
+ ticketAttachDesc: "把既有会话挂为贡献会话(缺省当前会话)",
+ channelDesc: "组织的频道(default_channel 是全员频道,所有人都在其中)",
+ channelLsDesc: "列出频道:人看到全部频道,员工只看到自己所在的",
+ channelCreateDesc: "新建频道;初始成员只有创建者,其余人经邀请加入",
+ channelShowDesc: "查看频道及其成员",
+ channelInviteDesc: "邀请若干 principal 加入频道(任一成员均可)",
+ channelJoinDesc: "自行加入频道(仅限人;员工只能等成员邀请)",
+ channelLeaveDesc: "退出频道",
+ channelRemoveDesc: "把另一位成员移出频道(仅限人)",
+ channelArchiveDesc: "归档频道:在取消归档前只读(仅限人)",
+ channelUnarchiveDesc: "取消频道的归档(仅限人)",
+ channelTailDesc: "打印某个频道某一天的最后若干条消息(未给 -n 时 20 条)",
+ channelSendDesc: "向频道发送消息(@agent:<id> / @all 提及频道成员并触发其工位)",
+ handbookDesc: "组织手册:handbook/ 下的知识库,其 README.md 是每轮先读的索引",
+ handbookListDesc: "列出手册文件(路径、大小、更新时间),索引在前",
+ handbookShowDesc: "打印一份手册文档(不给路径时打印索引)",
+ handbookWriteDesc: "用 -m 或 --file 的内容创建或替换一份手册文档",
+ handbookRmDesc: "删除一份手册文档(索引不可删)",
+ financeDesc: "支出:按员工(沿汇报线累计)与按工单,对照预算",
+ orgId: "组织 id(缺省取 PENGUIN_ORG_ID,工位会话与工单会话内自带;此外没有缺省值)",
+ newOrgId: "要创建的组织 id(字母、数字、下划线;同时是目录名)",
+ mission: "组织的使命",
+ orgName: "显示名(缺省同 id)",
+ orgLanguageOption: "组织书写一切内容所用的工作语言:zh 或 en(缺省取使命本身的语言)",
+ hireAgentId: "招募这个既有 Agent(与 --new-agent 互斥)",
+ newAgent: "以此 id 新建 Agent 并招募(与 --agent-id 互斥)",
+ newAgentName: "新 Agent 的显示名",
+ newAgentDescription: "新 Agent 的描述",
+ skills: "新 Agent 额外的插件库插件,逗号分隔(在 agent-company,agent-development 之上追加)",
+ title: "头衔",
+ reportsTo: "上级的 Agent id",
+ employeeWorkspace: "Workspace:公共工作区的子目录(. 即整个工作区)或绝对路径,原样写入",
+ hireWorkspace:
+ "Workspace:公共工作区的子目录或绝对路径,原样写入(缺省为以该员工命名的子目录)",
+ budget: "月预算(美元),含该员工及其全部下属",
+ ceoBudget: "CEO 的月预算(美元);预算沿汇报线累计,CEO 的预算就是整家公司的",
+ duties: "职责描述",
+ calendarAgentId: "日程项所属员工(缺省 PENGUIN_AGENT_ID);ls 上只列该员工的日程项",
+ calendarTitle: "日程项标题",
+ statusFilter: "只看这一列:proposed、in_progress、review、done 或 rejected",
+ ownerFilter: "只看该负责人的工单(agent:<id> / user:<id>)",
+ blockedFilter: "只看被阻塞的工单",
+ ticketTitle: "工单标题",
+ ticketSlug: "工单 id 的词:小写英文单词,用连字符连接",
+ goal: "目标,所依赖的输入一律写完整路径(与 --body-file 互斥)",
+ criteria: "验收标准,预期交付物一律写完整路径(与 --goal 配合)",
+ bodyFile: "从文件读取整个 Markdown 正文(头部仍由服务端生成)",
+ owner: "负责人(agent:<id> / user:<id>);create 时缺省为调用方",
+ parent: "父工单 id",
+ notify: "工单结束时通知的对象,逗号分隔",
+ priority: "优先级:P0、P1 或 P2",
+ due: "截止日期(yyyy-mm-dd)",
+ moveTo: "目标列:proposed、in_progress、review、done 或 rejected",
+ moveReason: "原因(移入 rejected 时必填;记入 Result)",
+ blockReason: "阻塞原因",
+ blockedBy: "在等谁或等哪个工单(principal 或工单 id)",
+ progressText: "进展内容,涉及的文件一律写完整路径",
+ startMessage: "附在工单正文之后、随会话首条输入发出的附言",
+ startWorkspace: "公共工作区内的另一个目录(缺省为该员工工位的 Workspace)",
+ startAgentId:
+ "会话以哪名员工的身份运行:可以拉同事来做自己名下的工单(会话内缺省为你自己,否则为工单负责人)",
+ attachSession: "要挂接的会话,完整 id 或唯一片段(缺省 PENGUIN_SESSION_ID)",
+ channelOpt: "要读取或写入的频道(缺省 default_channel,即全员频道)",
+ channelName: "显示名(缺省同 id)",
+ channelPurpose: "频道用途",
+ channelDate: "要读的日期(组织时区的 yyyy-mm-dd;缺省今天)",
+ channelCount: "打印的消息条数(缺省 20)",
+ channelText: "消息内容(@agent:<id> 或 @all 表示提及,只能提及频道内的成员)",
+ handbookPath: "相对 handbook/ 的路径(普通片段,如 decisions/2026-09-02-hire-plan.md)",
+ handbookText: "文档内容",
+ handbookFile: "从本地文件读取文档内容",
+ handbookOneSource: "-m <text> 与 --file <file> 只能给一个。",
+ refTicket: "消息关联的工单",
+ refSession: "消息关联的会话",
+ period: "统计月份(yyyy-mm;缺省当月)",
+ orgIdMissing: () =>
+ "未指定组织:请传 --org-id <id>,或设置 PENGUIN_ORG_ID(工位会话与工单会话的环境里自带)。",
+ hireTargetConflict: () =>
+ "--agent-id(既有 Agent)与 --new-agent(新建)二选一,且必须给一个。",
+ newAgentFieldsOnly: () => "--name、--description 与 --skills 只用于描述 --new-agent。",
+ budgetInvalid: (flag, value) => `${flag} 值「${value}」无效:应为非负的美元金额。`,
+ nothingToSet: () => "没有要更新的内容:至少给出一个字段。",
+ languageInvalid: (value) => `--language 值「${value}」无效:应为 zh 或 en。`,
+ statusInvalid: (value) =>
+ `列名「${value}」无效:应为 proposed、in_progress、review、done 或 rejected。`,
+ priorityInvalid: (value) => `--priority 值「${value}」无效:应为 P0、P1 或 P2。`,
+ ticketBodyConflict: () => "--goal 与 --body-file 二选一,且必须给一个。",
+ criteriaNeedsGoal: () => "--criteria 须与 --goal 一起使用。",
+ bodyFileUnreadable: (file) => `无法读取 --body-file ${file}。`,
+ countInvalid: (value) => `-n 值「${value}」无效:应为正整数。`,
+ pathSegmentInvalid: (value) => `名称「${value}」无效:「.」与「..」既不是 id,也不是手册路径。`,
+ attachSessionMissing: () =>
+ "没有可挂接的会话:请传 --session <id>,或在会话内运行(PENGUIN_SESSION_ID)。",
+ created: (orgId, ceoDeskSessionId) =>
+ `已创建组织 ${orgId}${ceoDeskSessionId !== undefined ? `(CEO 工位会话 ${ceoDeskSessionId})` : ""}。`,
+ hired: (agentId, title, reportsTo) =>
+ `已招募员工 ${agentId},头衔 ${title}${reportsTo !== null ? `,汇报给 ${reportsTo}` : ""}。`,
+ employeeUpdated: (agentId) => `已更新员工 ${agentId}。`,
+ left: (agentId) => `员工 ${agentId} 已离开组织。`,
+ desk: (agentId, sessionId, workspace, openedAt, created) =>
+ `${agentId} 的工位:会话 ${sessionId}(Workspace ${workspace},开于 ${openedAt})${created ? "——刚刚新开" : ""}`,
+ deskRenewed: (agentId, sessionId) => `${agentId} 的工位已换新:会话 ${sessionId}。`,
+ calendarWritten: (agentId, name, enabledText, nextFireAt) =>
+ `日程项 ${agentId}/${name} 已写入(${enabledText}${nextFireAt !== undefined ? `,下次触发 ${nextFireAt}` : ""})。`,
+ calendarWarning: (warning) => `排班提醒:${warning}`,
+ calendarRemoved: (agentId, name) => `日程项 ${agentId}/${name} 已删除。`,
+ ticketCreated: (ticketId, status) => `已创建工单 ${ticketId}(${status})。`,
+ ticketMoved: (ticketId, status) => `工单 ${ticketId} 已移到 ${status}。`,
+ ticketAssigned: (ticketId, owner) => `工单 ${ticketId} 已指派给 ${owner}。`,
+ ticketBlocked: (ticketId) => `工单 ${ticketId} 已标记为阻塞。`,
+ ticketUnblocked: (ticketId) => `工单 ${ticketId} 已解除阻塞。`,
+ progressRecorded: (ticketId) => `已在工单 ${ticketId} 记录进展。`,
+ ticketAttached: (ticketId, sessionId) => `会话 ${sessionId} 已挂接到工单 ${ticketId}。`,
+ channelCreated: (channelId) => `已创建频道 ${channelId}。`,
+ channelInvited: (channelId, principal) => `已邀请 ${principal} 加入 ${channelId}。`,
+ channelJoined: (channelId) => `已加入 ${channelId}。`,
+ channelLeft: (channelId) => `已退出 ${channelId}。`,
+ channelMemberRemoved: (channelId, principal) => `已把 ${principal} 移出 ${channelId}。`,
+ channelArchived: (channelId) => `频道 ${channelId} 已归档。`,
+ channelUnarchived: (channelId) => `频道 ${channelId} 已取消归档。`,
+ messageSent: (id) => `消息 ${id} 已发送。`,
+ handbookWritten: (path) => `手册文档 ${path} 已写入。`,
+ handbookRemoved: (path) => `手册文档 ${path} 已删除。`,
+ empty: (projectId) => `Project ${projectId} 没有组织。`,
+ calendarEmpty: () => "没有日程项。",
+ ticketsEmpty: () => "没有匹配的工单。",
+ channelsEmpty: () => "没有频道。",
+ channelEmpty: (channelId, date) => `${channelId} 在 ${date} 没有消息。`,
+ showHead: (name, orgId, status) => `${name}(${orgId})——${status}`,
+ showMission: (mission) => `使命:${mission}`,
+ showLanguage: (language) => `工作语言:${language}`,
+ showEmployees: (count, running, paused) =>
+ `员工:${count}(运行中 ${running},已暂停 ${paused})`,
+ showBoard: (counts, blocked) => `看板:${counts}(阻塞 ${blocked})`,
+ showSpend: (period, spend) => `支出(${period}):${spend}`,
+ showPending: (mentions, review, blockedByMe) =>
+ `待处理:@我 ${mentions} 条,待审核工单 ${review} 个,等我的阻塞 ${blockedByMe} 个`,
+ invalid: (reason) => `invalid: ${reason}`,
+ ticketHead: (ticketId, status, running, blocked) =>
+ `工单 ${ticketId}:${status}${running ? ",运行中" : ""}${blocked !== undefined ? `,已阻塞(${blocked})` : ""}`,
+ ticketFigures: (cost, rolledUp, sessions, children) =>
+ `成本 ${cost}(含子工单 ${rolledUp}),贡献会话 ${sessions} 个,子工单 ${children} 个`,
+ ticketFields: () => ({
+ title: "标题",
+ owner: "负责人",
+ parent: "父工单",
+ notify: "通知",
+ priority: "优先级",
+ due: "截止",
+ blocked: "阻塞原因",
+ blockedBy: "阻塞于",
+ sessions: "贡献会话",
+ }),
+ ticketHistory: () => "操作历史:",
+ notices: {
+ employee_joined: (p) => `${p.agent} 加入,职位 ${p.title},汇报给 ${p.reportsTo}。`,
+ employee_left: (p) => `${p.agent} 已离开组织,其汇报关系转由 ${p.reportsTo} 承接。`,
+ channel_created: (p) => `${p.by} 创建了该频道。`,
+ channel_archived: (p) => `${p.by} 归档了该频道。`,
+ channel_unarchived: (p) => `${p.by} 取消归档了该频道。`,
+ channel_joined: (p) => `${p.principal} 加入了该频道。`,
+ channel_invited: (p) => `${p.by} 邀请 ${p.principal} 加入该频道。`,
+ channel_left: (p) => `${p.principal} 退出了该频道。`,
+ channel_removed: (p) => `${p.by} 将 ${p.principal} 移出该频道。`,
+ budget_warned: (p) =>
+ `预算预警:${p.agent} 已用掉 ${p.period} 预算的 ${p.percent}%(${p.cost} / ${p.budget} USD)。`,
+ budget_paused: (p) =>
+ `预算暂停:${p.agent} 达到 ${p.period} 预算的 ${p.percent}%(${p.cost} / ${p.budget} USD),其本人与下属的日程已暂停。`,
+ ticket_blocked: (p) => `工单 ${p.ticket}(${p.title})已被阻塞。`,
+ ticket_done: (p) => `工单 ${p.ticket}(${p.title})已完成。`,
+ ticket_rejected: (p) => `工单 ${p.ticket}(${p.title})已被否决。`,
+ },
+ allHands: () => "全员频道",
+ channelHeader: (channelId) => `[频道 ${channelId}]`,
+ channelHead: (name, channelId, members, archived) =>
+ `${name}(${channelId})——成员 ${members}${archived ? ",已归档" : ""}`,
+ channelPurposeLine: (purpose) => `用途:${purpose}`,
+ channelCreatedBy: (principal, createdAt) => `由 ${principal} 创建于 ${createdAt}`,
+ channelLastMessage: (time) => `最后一条消息:${time}`,
+ financeTotal: (period, total) => `合计(${period}):${total}`,
+ unpriced: () => "[unpriced] 部分用量所用模型未配置价格:以上数字是下限",
+ colEmployees: () => "员工数",
+ colRunning: () => "运行中",
+ colOpen: () => "未结",
+ colBlocked: () => "阻塞",
+ colSpend: () => "支出",
+ colNote: () => "备注",
+ colJobTitle: () => "头衔",
+ colTitle: () => "标题",
+ colState: () => "状态",
+ colOwn: () => "自身",
+ colCumulative: () => "累计",
+ colBudget: () => "预算",
+ colNext: () => "下次触发",
+ colPriority: () => "优先级",
+ colOwner: () => "负责人",
+ colTicket: () => "工单",
+ colRolledUp: () => "含子工单",
+ colMembers: () => "成员数",
+ colArchived: () => "归档",
+ colUnread: () => "未读",
+ colMentions: () => "@我",
+ colPrincipal: () => "主体",
+ },
client: {
invalidServerUrl: (value) => `服务器地址「${value}」无效:应为 http(s)://host[:port]。`,
remoteNeedsToken: (url) =>
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 38b19672..c429453c 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -19,6 +19,7 @@ import { registerAgentCommand } from "./commands/agent.js";
import { registerProjectCommand } from "./commands/project.js";
import { registerCostCommand } from "./commands/cost.js";
import { registerScheduleCommand } from "./commands/schedule.js";
+import { registerOrgCommand } from "./commands/org.js";
import { registerServeCommands } from "./commands/serve.js";
import { registerUpdateCommand } from "./commands/update.js";
import { registerVersionCommand } from "./commands/version.js";
@@ -58,6 +59,7 @@ export async function cli(argv: string[]): Promise<number> {
registerProjectCommand(program, t);
registerCostCommand(program, t);
registerScheduleCommand(program, t);
+ registerOrgCommand(program, t);
registerServeCommands(program, t);
registerUpdateCommand(program, t);
registerVersionCommand(program, t);
diff --git a/packages/cli/test/fake-server.ts b/packages/cli/test/fake-server.ts
index 62945cfc..8edbae20 100644
--- a/packages/cli/test/fake-server.ts
+++ b/packages/cli/test/fake-server.ts
@@ -1,10 +1,10 @@
/**
* In-process fake PenguinHarness server for CLI tests: stubs `globalThis.fetch` with a
- * handler covering exactly the endpoints the server-backed commands touch (session
- * create/get/patch, tasks/steer/compact/abort, SSE stream, messages, agents, projects,
- * usage, schedules). Connection resolution is pinned via PENGUIN_API_URL (a loopback
- * URL, so no token gate) and PENGUIN_HOME points at a scratch directory so nothing of
- * the developer's real data root is read.
+ * handler covering exactly the endpoints the server-backed commands touch (the current
+ * user, session create/get/patch, tasks/steer/compact/abort, SSE stream, messages, agents,
+ * projects, usage, schedules, organizations and their channels). Connection resolution is pinned via PENGUIN_API_URL
+ * (a loopback URL, so no token gate) and PENGUIN_HOME points at a scratch directory so
+ * nothing of the developer's real data root is read.
*
* The SSE stream is real: a ReadableStream whose frames follow the server's wire shape
* (default-event OmniMessage frames, `event: server_event` control frames, incrementing
@@ -40,6 +40,71 @@ export interface FakeSessionState {
aborts: number;
}
+/**
+ * One channel of a fake organization: the `channel.toml` fields plus the day files, which
+ * the fake keeps as one flat list per channel. `everyone` is the all-hands channel's
+ * implicit membership — `members` is unused there and resolved from the employee tree and
+ * the Project's people, exactly as the server resolves it.
+ */
+export interface FakeChannelState {
+ channelId: string;
+ name: string;
+ purpose: string;
+ everyone: boolean;
+ archived: boolean;
+ createdBy: string;
+ createdAt: string;
+ members: string[];
+ messages: Json[];
+ /** What a person is told is unread here; an employee caller is always told 0, as on the server. */
+ unread: number;
+ mentionsMe: number;
+}
+
+/**
+ * One organization of the fake (company mode). Employees, calendar events, tickets and
+ * channels are kept in the DTO shapes the server projects from its files; a ticket
+ * record is the detail shape minus `body`, which is rendered on read the way the server
+ * serializes the file.
+ */
+export interface FakeOrgState {
+ orgId: string;
+ projectId: string;
+ name: string;
+ mission: string;
+ status: "active" | "paused";
+ createdBy: string;
+ timezone: string;
+ /** The working language the settings DTO always carries. */
+ language: "zh" | "en";
+ invalid?: string;
+ ceoAgentId: string;
+ ceoDeskSessionId?: string;
+ spend: { period: string; cost: number; budget?: number; ratio?: number };
+ employees: Json[];
+ /** Calendar events keyed `<agentId>/<name>`. */
+ calendar: Map<string, Json>;
+ calendarInvalidFiles: Json[];
+ /** Rota advice a calendar write answers with (`OrgCalendarWriteResponse.warnings`). */
+ calendarWarnings: string[];
+ /** Ticket records keyed by ticket id, in creation order. */
+ tickets: Map<string, Json>;
+ ticketInvalidFiles: Json[];
+ /** Channels keyed by id; the all-hands channel is seeded with the organization. */
+ channels: Map<string, FakeChannelState>;
+ /** Handbook files keyed by path relative to `handbook/` (the index is seeded). */
+ handbook: Map<string, string>;
+ /** Desk sessions keyed by employee. */
+ desks: Map<string, Json>;
+ /** The `unpriced` flag of the finance response. */
+ unpriced: boolean;
+}
+
+/** Who a fake request is attributed to, or the error response that settles it. */
+type FakeCaller =
+ | { ok: true; principal: string; agentId: string | null; sessionId?: string }
+ | { ok: false; res: Response };
+
interface Subscriber {
controller: ReadableStreamDefaultController<Uint8Array>;
closed: boolean;
@@ -47,8 +112,65 @@ interface Subscriber {
const encoder = new TextEncoder();
+/** The fake's fixed clock for company mode (the day file, the period, minted ids). */
+const ORG_NOW = "2026-09-02T10:00:00.000Z";
+const ORG_TODAY = "2026-09-02";
+const DEFAULT_CHANNEL_ID = "default_channel";
+/** The server's default for the CEO's monthly budget when creation names none. */
+const DEFAULT_CEO_BUDGET = 100;
+const ORG_PERIOD = "2026-09";
+const TICKET_COLUMNS = ["proposed", "in_progress", "review", "done", "rejected"] as const;
+const OPEN_COLUMNS: readonly string[] = ["proposed", "in_progress", "review"];
+/** The server's TICKET_ID_PATTERN: a date and a letters-only slug. */
+const TICKET_ID_RE = /^\d{4}-\d{2}-\d{2}-[a-z]+(?:-[a-z]+)*$/;
+/** The server's TICKET_SLUG_PATTERN. */
+const TICKET_SLUG_RE = /^[a-z]+(?:-[a-z]+)*$/;
+/** The server's CHANNEL_ID_PATTERN. */
+const CHANNEL_ID_RE = /^[a-z][a-z0-9_]{1,63}$/;
+/** `agent:<id>` / `user:<id>`, the only two principal kinds a channel holds. */
+const PRINCIPAL_RE = /^(agent|user):([A-Za-z0-9_-]+)$/;
+/** The keys of an OrgTicketItem (the list shape) within a ticket record. */
+const TICKET_ITEM_KEYS = [
+ "ticketId",
+ "title",
+ "status",
+ "owner",
+ "parent",
+ "notify",
+ "priority",
+ "due",
+ "blocked",
+ "blockedBy",
+ "sessions",
+ "running",
+ "cost",
+ "invalid",
+] as const;
+
+/** The server's slugify: ASCII letters only, at most six words of at most twenty characters. */
+function slugify(title: string): string {
+ return title
+ .toLowerCase()
+ .replace(/[^a-z]+/g, " ")
+ .trim()
+ .split(/\s+/)
+ .filter((w) => w !== "")
+ .slice(0, 6)
+ .map((w) => w.slice(0, 20))
+ .join("-");
+}
+
+/** The principals a chat text mentions (`@all`, `@agent:<id>`, `@user:<id>`). */
+function mentionsOf(text: string): string[] {
+ return [...text.matchAll(/@(all|agent:[A-Za-z0-9_]+|user:[A-Za-z0-9_]+)/g)].map((m) => m[1]!);
+}
+
+const isNonEmptyString = (value: unknown): value is string =>
+ typeof value === "string" && value !== "";
+
export class FakeServer {
- readonly requests: Array<{ method: string; path: string; body?: Json }> = [];
+ /** Every request, in order: the path without its query, the query on its own, and the parsed body. */
+ readonly requests: Array<{ method: string; path: string; search: string; body?: Json }> = [];
readonly sessions = new Map<string, FakeSessionState>();
agents: Array<Json> = [
{
@@ -63,6 +185,8 @@ export class FakeServer {
projects: Array<Json> = [
{ projectId: "default_project", name: "Default", role: "owner", ownerUserId: "admin" },
];
+ /** The signed-in user behind the API token: what GET /api/me reports and whom a body-less write is attributed to. */
+ userId = "admin";
/** Messages a task emits between running and idle (default: one assistant echo). */
onTask: (session: FakeSessionState, body: Json) => unknown[] = () => [];
/** Messages GET /messages returns. */
@@ -92,6 +216,8 @@ export class FakeServer {
schedules: Json = { schedules: [], invalidFiles: [] };
/** Named schedule store behind add/update/rm: name -> the stored item (single-agent tests). */
readonly scheduleItems = new Map<string, Json>();
+ /** Company mode: organizations keyed by org id. */
+ readonly orgs = new Map<string, FakeOrgState>();
private nextSessionOrdinal = 1;
private nextEventId = 1;
@@ -141,6 +267,7 @@ export class FakeServer {
"PENGUIN_SESSION_ID",
"PENGUIN_PROJECT_ID",
"PENGUIN_AGENT_ID",
+ "PENGUIN_ORG_ID",
]) {
this.savedEnv.set(key, process.env[key]);
}
@@ -151,6 +278,7 @@ export class FakeServer {
delete process.env.PENGUIN_SESSION_ID;
delete process.env.PENGUIN_PROJECT_ID;
delete process.env.PENGUIN_AGENT_ID;
+ delete process.env.PENGUIN_ORG_ID;
globalThis.fetch = ((input: string | URL | Request, init?: RequestInit) =>
this.handle(input, init)) as typeof globalThis.fetch;
return () => this.uninstall();
@@ -234,6 +362,1215 @@ export class FakeServer {
return this.json({ error: { code, message } }, status);
}
+ private badRequest(message: string): Response {
+ return this.error(400, "bad_request", message);
+ }
+
+ // ---- company mode: state ----
+
+ /** Adds an organization whose CEO (`ceoAgentId`, default `ceo`) is its first employee; `overrides` win. */
+ addOrg(overrides: Partial<FakeOrgState> & { orgId: string }): FakeOrgState {
+ const org: FakeOrgState = {
+ projectId: "default_project",
+ name: overrides.orgId,
+ mission: "",
+ status: "active",
+ createdBy: "user:admin",
+ timezone: "UTC",
+ language: "en",
+ ceoAgentId: "ceo",
+ spend: { period: ORG_PERIOD, cost: 0 },
+ employees: [],
+ calendar: new Map(),
+ calendarInvalidFiles: [],
+ calendarWarnings: [],
+ tickets: new Map(),
+ ticketInvalidFiles: [],
+ channels: new Map(),
+ handbook: new Map([["README.md", `# ${overrides.name ?? "Org"} — organization handbook\n`]]),
+ desks: new Map(),
+ unpriced: false,
+ ...overrides,
+ };
+ this.orgs.set(org.orgId, org);
+ // The all-hands channel is created with the organization and holds everyone implicitly.
+ if (!org.channels.has(DEFAULT_CHANNEL_ID)) {
+ this.addChannel(org.orgId, DEFAULT_CHANNEL_ID, {
+ name: "All hands",
+ everyone: true,
+ createdBy: "system",
+ });
+ }
+ if (!org.employees.some((e) => e.agentId === org.ceoAgentId)) {
+ this.addEmployee(org.orgId, { agentId: org.ceoAgentId, title: "CEO", reportsTo: null });
+ }
+ return org;
+ }
+
+ /** Adds a channel (the `channel.toml` shape); the creator is its only member unless `members` says otherwise. */
+ addChannel(
+ orgId: string,
+ channelId: string,
+ overrides: Partial<FakeChannelState> = {},
+ ): FakeChannelState {
+ const org = this.orgs.get(orgId)!;
+ const channel: FakeChannelState = {
+ channelId,
+ name: channelId,
+ purpose: "",
+ everyone: false,
+ archived: false,
+ createdBy: "user:admin",
+ createdAt: ORG_NOW,
+ members: [],
+ messages: [],
+ unread: 0,
+ mentionsMe: 0,
+ ...overrides,
+ };
+ org.channels.set(channelId, channel);
+ return channel;
+ }
+
+ /**
+ * Adds an employee (OrgEmployeeItem shape; `reportsTo` defaults to the CEO). An employee
+ * is an Agent, so one is listed under /agents as well when it is not already. The workspace
+ * defaults the way the server does: the CEO's partition is `ceo`, everyone else's is named
+ * after its Agent id, and the shared root is nobody's desk.
+ */
+ addEmployee(orgId: string, item: Json & { agentId: string }): Json {
+ const org = this.orgs.get(orgId)!;
+ if (!this.agents.some((a) => a.agentId === item.agentId)) {
+ this.agents.push({
+ agentId: item.agentId,
+ name: String(item.name ?? item.agentId),
+ description: "",
+ sessionCount: 0,
+ activeSessionCount: 0,
+ sessionActivity: [],
+ });
+ }
+ const employee: Json = {
+ name: item.agentId,
+ title: "Employee",
+ reportsTo: item.agentId === org.ceoAgentId ? null : org.ceoAgentId,
+ workspace: item.agentId === org.ceoAgentId ? "ceo" : item.agentId,
+ resolvedWorkspace: `/shared/${item.agentId}`,
+ state: "idle",
+ spend: { own: 0, cumulative: 0 },
+ ...item,
+ };
+ org.employees.push(employee);
+ return employee;
+ }
+
+ /** Adds a ticket record (the detail shape minus `body`; a `rawBody` stands in for a body supplied whole). */
+ addTicket(orgId: string, item: Json & { ticketId: string }): Json {
+ const org = this.orgs.get(orgId)!;
+ const ticket: Json = {
+ title: item.ticketId,
+ status: "proposed",
+ owner: "user:admin",
+ notify: ["user:admin"],
+ priority: "P1",
+ sessions: [],
+ history: [],
+ running: false,
+ cost: 0,
+ goal: "",
+ acceptanceCriteria: "",
+ progress: [],
+ result: "",
+ rolledUpCost: 0,
+ ...item,
+ };
+ org.tickets.set(item.ticketId, ticket);
+ return ticket;
+ }
+
+ /** Appends a channel message (OrgChannelMessage shape) at the fake's clock unless `time` is given. */
+ addMessage(
+ orgId: string,
+ msg: Json & { sender: string; text: string },
+ channelId: string = DEFAULT_CHANNEL_ID,
+ ): Json {
+ const channel = this.orgs.get(orgId)!.channels.get(channelId)!;
+ const message: Json = {
+ id: `msg-2026-09-02-10-00-00-${(channel.messages.length + 1).toString(16).padStart(8, "0")}`,
+ time: ORG_NOW,
+ hop: 0,
+ mentions: mentionsOf(msg.text),
+ ...msg,
+ };
+ channel.messages.push(message);
+ return message;
+ }
+
+ private orgSummary(org: FakeOrgState): Json {
+ const tickets = [...org.tickets.values()];
+ const inState = (state: string): number =>
+ org.employees.filter((e) => e.state === state).length;
+ return {
+ projectId: org.projectId,
+ orgId: org.orgId,
+ name: org.name,
+ mission: org.mission,
+ status: org.status,
+ employeeCount: org.employees.length,
+ runningCount: inState("running"),
+ pausedCount: inState("paused"),
+ openTickets: tickets.filter((x) => OPEN_COLUMNS.includes(String(x.status))).length,
+ blockedTickets: tickets.filter((x) => isNonEmptyString(x.blocked)).length,
+ createdBy: org.createdBy,
+ spend: org.spend,
+ ...(org.invalid !== undefined ? { invalid: org.invalid } : {}),
+ };
+ }
+
+ private orgDetail(org: FakeOrgState): Json {
+ const tickets = [...org.tickets.values()];
+ return {
+ ...this.orgSummary(org),
+ settings: {
+ name: org.name,
+ mission: org.mission,
+ status: org.status,
+ timezone: org.timezone,
+ approvalMode: "allow-all",
+ mentionChainLimit: 3,
+ budgetWarnRatio: 0.8,
+ budgetPauseRatio: 1,
+ createdBy: org.createdBy,
+ language: org.language,
+ },
+ board: Object.fromEntries(
+ TICKET_COLUMNS.map((column) => [column, tickets.filter((x) => x.status === column).length]),
+ ),
+ today: [],
+ pending: {
+ mentions: 0,
+ reviewTickets: tickets.filter((x) => x.status === "review").map((x) => this.ticketItem(x)),
+ blockedByMe: [],
+ },
+ recentMessages: (org.channels.get(DEFAULT_CHANNEL_ID)?.messages ?? []).slice(-5),
+ alerts: [],
+ ...(org.ceoDeskSessionId !== undefined ? { ceoDeskSessionId: org.ceoDeskSessionId } : {}),
+ };
+ }
+
+ private ticketItem(rec: Json): Json {
+ return Object.fromEntries(
+ TICKET_ITEM_KEYS.filter((key) => rec[key] !== undefined).map((key) => [key, rec[key]]),
+ );
+ }
+
+ private ticketDetail(org: FakeOrgState, rec: Json): Json {
+ return {
+ ...this.ticketItem(rec),
+ goal: rec.goal,
+ acceptanceCriteria: rec.acceptanceCriteria,
+ progress: rec.progress,
+ result: rec.result,
+ history: rec.history,
+ body: this.ticketBody(rec),
+ children: [...org.tickets.values()]
+ .filter((x) => x.parent === rec.ticketId)
+ .map((x) => x.ticketId),
+ rolledUpCost: rec.rolledUpCost,
+ sessionItems: (rec.sessions as string[]).map((sessionId) => {
+ const s = this.sessions.get(sessionId);
+ return { sessionId, agentId: s?.agentId ?? "", status: s?.status ?? "idle" };
+ }),
+ };
+ }
+
+ /** The ticket file as the server writes it: YAML frontmatter, then the sections (or the supplied body). */
+ private ticketBody(rec: Json): string {
+ const front = [
+ `title: ${rec.title}`,
+ `status: ${rec.status}`,
+ `owner: ${rec.owner}`,
+ ...(rec.parent !== undefined ? [`parent: ${rec.parent}`] : []),
+ `notify: [${(rec.notify as string[]).join(", ")}]`,
+ `priority: ${rec.priority}`,
+ ...(rec.due !== undefined ? [`due: ${rec.due}`] : []),
+ ...(isNonEmptyString(rec.blocked) ? [`blocked: ${rec.blocked}`] : []),
+ ...(isNonEmptyString(rec.blockedBy) ? [`blocked_by: ${rec.blockedBy}`] : []),
+ `sessions: [${(rec.sessions as string[]).join(", ")}]`,
+ `history:`,
+ ...(rec.history as Json[]).map(
+ (h) =>
+ ` - {at: ${h.at}, by: ${h.by}, action: ${h.action}${h.note !== undefined ? `, note: ${h.note}` : ""}}`,
+ ),
+ ].join("\n");
+ const sections =
+ typeof rec.rawBody === "string"
+ ? rec.rawBody.trimEnd()
+ : [
+ `## Goal\n${rec.goal}`,
+ `## Acceptance criteria\n${rec.acceptanceCriteria}`,
+ `## Progress\n${(rec.progress as string[]).map((line) => `- ${line}`).join("\n")}`,
+ `## Result\n${rec.result}`,
+ ].join("\n\n");
+ return `---\n${front}\n---\n\n${sections}\n`;
+ }
+
+ /**
+ * Who a write is attributed to: the calling employee when the body names one, else the
+ * calling session's Agent (an unknown session is a 404, never a silent fallback), else the
+ * token's user. `agentId` wins, as it does on the server.
+ */
+ private actorOf(body: Json | undefined): FakeCaller {
+ return this.callerOf(body?.agentId, body?.sessionId);
+ }
+
+ /**
+ * The same claim on a read, where there is no body to carry it: `?sessionId=` / `?agentId=`
+ * are how a desk or ticket session asks "which channels am I in". The CLI appends them on
+ * every channel read and on the member DELETE.
+ */
+ private callerOfQuery(url: URL): FakeCaller {
+ return this.callerOf(
+ url.searchParams.get("agentId") ?? undefined,
+ url.searchParams.get("sessionId") ?? undefined,
+ );
+ }
+
+ /** The Agent id first, the session second: the order the server resolves an operator in. */
+ private callerOf(agentId: unknown, sessionId: unknown): FakeCaller {
+ if (isNonEmptyString(agentId)) {
+ return {
+ ok: true,
+ principal: `agent:${agentId}`,
+ agentId,
+ ...(isNonEmptyString(sessionId) ? { sessionId } : {}),
+ };
+ }
+ return this.callerOfSession(sessionId);
+ }
+
+ /**
+ * Who a call is attributed to: the named session's Agent, else the token's user. An unknown
+ * session is a 404 here where the server would quietly fall back to the user — the fake is
+ * strict on purpose, so a test that mistypes a session id says so.
+ */
+ private callerOfSession(sessionId: unknown): FakeCaller {
+ const me = { ok: true, principal: `user:${this.userId}`, agentId: null } as const;
+ if (sessionId === undefined) return me;
+ if (!isNonEmptyString(sessionId))
+ return { ok: false, res: this.badRequest("sessionId must be a string.") };
+ const session = this.sessions.get(sessionId);
+ if (!session) {
+ return {
+ ok: false,
+ res: this.error(404, "session_not_found", `Session does not exist: ${sessionId}`),
+ };
+ }
+ return {
+ ok: true,
+ principal: `agent:${session.agentId}`,
+ agentId: session.agentId,
+ sessionId,
+ };
+ }
+
+ /** A calendar body's validated fields (POST and PUT share them), or the 400. */
+ private calendarFields(
+ body: Json | undefined,
+ ): { ok: true; value: Json } | { ok: false; res: Response } {
+ if (typeof body?.enabled !== "boolean")
+ return { ok: false, res: this.badRequest("enabled must be a boolean.") };
+ if (!isNonEmptyString(body.prompt))
+ return { ok: false, res: this.badRequest("prompt is required.") };
+ if (!isNonEmptyString(body.startAt))
+ return { ok: false, res: this.badRequest("startAt is required.") };
+ const value: Json = { prompt: body.prompt, enabled: body.enabled, startAt: body.startAt };
+ for (const key of ["title", "period", "endAt"]) {
+ if (isNonEmptyString(body[key])) value[key] = body[key];
+ }
+ return { ok: true, value };
+ }
+
+ private openDesk(org: FakeOrgState, employee: Json, created: boolean): Json {
+ const s = this.addSession({ agentId: String(employee.agentId) });
+ const desk = {
+ sessionId: s.sessionId,
+ workspace: String(employee.resolvedWorkspace ?? "/shared"),
+ openedAt: ORG_NOW,
+ };
+ org.desks.set(String(employee.agentId), desk);
+ return { agentId: employee.agentId, ...desk, created };
+ }
+
+ // ---- company mode: routes (the contract of the server's organizations.ts) ----
+
+ private handleOrganizations(
+ method: string,
+ projectId: string,
+ rest: string,
+ url: URL,
+ body: Json | undefined,
+ ): Response {
+ if (rest === "") {
+ if (method === "POST") {
+ const orgId = body?.orgId;
+ if (!isNonEmptyString(orgId) || orgId.length < 2)
+ return this.badRequest("orgId is required.");
+ if (!isNonEmptyString(body?.mission)) return this.badRequest("mission is required.");
+ if (this.orgs.has(orgId)) {
+ return this.error(409, "org_exists", `Organization id is already taken: ${orgId}`);
+ }
+ const org = this.addOrg({
+ orgId,
+ projectId,
+ mission: body.mission,
+ ...(isNonEmptyString(body.name) ? { name: body.name } : {}),
+ ...(body.language === "zh" || body.language === "en" ? { language: body.language } : {}),
+ });
+ // Creation opens the CEO's desk and starts the initialization run.
+ const ceo = org.employees.find((e) => e.agentId === org.ceoAgentId)!;
+ // The CEO's chart entry carries the whole company's budget: the request's value,
+ // or the server's default when the caller sent none.
+ if (body.ceoBudget !== undefined && typeof body.ceoBudget !== "number") {
+ return this.badRequest("ceoBudget must be a number.");
+ }
+ if (typeof body.ceoBudget === "number" && body.ceoBudget < 0) {
+ return this.badRequest("ceoBudget must not be negative.");
+ }
+ ceo.budget = typeof body.ceoBudget === "number" ? body.ceoBudget : DEFAULT_CEO_BUDGET;
+ org.ceoDeskSessionId = String(this.openDesk(org, ceo, true).sessionId);
+ return this.json(this.orgDetail(org), 201);
+ }
+ const organizations = [...this.orgs.values()]
+ .filter((o) => o.projectId === projectId)
+ .map((o) => this.orgSummary(o));
+ return this.json({ organizations });
+ }
+
+ const segments = rest.split("/").map(decodeURIComponent);
+ const orgId = segments[0]!;
+ const org = this.orgs.get(orgId);
+ if (!org || org.projectId !== projectId) {
+ return this.error(404, "org_not_found", `Organization does not exist: ${orgId}`);
+ }
+ const [, a, b, c] = segments;
+
+ if (a === undefined) {
+ if (method === "GET") return this.json(this.orgDetail(org));
+ if (method === "PATCH") {
+ for (const key of ["name", "mission", "timezone"] as const) {
+ if (isNonEmptyString(body?.[key])) org[key] = body[key];
+ }
+ if (body?.status === "active" || body?.status === "paused") org.status = body.status;
+ return this.json(this.orgDetail(org).settings);
+ }
+ if (method === "DELETE") {
+ this.orgs.delete(orgId);
+ return new Response(null, { status: 204 });
+ }
+ }
+
+ if (a === "chart" && b === undefined && method === "GET") {
+ return this.json({ ceoAgentId: org.ceoAgentId, employees: org.employees });
+ }
+
+ if (a === "employees") {
+ if (b === undefined) {
+ if (method !== "POST")
+ return this.error(404, "not_found", `No fake route for ${method} ${url.pathname}`);
+ const agentId = body?.agentId;
+ const newAgent = body?.newAgent as Json | undefined;
+ if ((agentId === undefined) === (newAgent === undefined)) {
+ return this.badRequest("Pass exactly one of agentId and newAgent.");
+ }
+ if (!isNonEmptyString(body?.title)) return this.badRequest("title is required.");
+ if (!isNonEmptyString(body?.reportsTo)) return this.badRequest("reportsTo is required.");
+ const id = agentId !== undefined ? agentId : newAgent?.agentId;
+ if (!isNonEmptyString(id) || id.length < 2) return this.badRequest("agentId is required.");
+ if (org.employees.some((e) => e.agentId === id)) {
+ return this.error(409, "employee_exists", `${id} is already an employee.`);
+ }
+ if (agentId !== undefined && !this.agents.some((x) => x.agentId === id)) {
+ return this.error(404, "agent_not_found", `Agent does not exist: ${id}`);
+ }
+ if (!org.employees.some((e) => e.agentId === body?.reportsTo)) {
+ return this.badRequest(
+ `Invalid employee tree: ${String(body?.reportsTo)} is not an employee.`,
+ );
+ }
+ const employee = this.addEmployee(orgId, {
+ agentId: id,
+ ...(isNonEmptyString(newAgent?.name) ? { name: newAgent.name } : {}),
+ title: body.title,
+ reportsTo: body.reportsTo,
+ ...(isNonEmptyString(body.workspace) ? { workspace: body.workspace } : {}),
+ ...(typeof body.budget === "number" ? { budget: body.budget } : {}),
+ ...(typeof body.duties === "string" ? { duties: body.duties } : {}),
+ ...(body.model !== undefined && body.model !== null ? { model: body.model } : {}),
+ });
+ return this.json(employee, 201);
+ }
+ const employee = org.employees.find((e) => e.agentId === b);
+ if (!employee) return this.error(404, "employee_not_found", `${b} is not an employee.`);
+ if (c === undefined && method === "PATCH") {
+ for (const key of ["title", "reportsTo", "workspace", "duties"]) {
+ if (typeof body?.[key] === "string") employee[key] = body[key];
+ }
+ if (body?.budget === null) delete employee.budget;
+ else if (typeof body?.budget === "number") employee.budget = body.budget;
+ if (body?.model === null) delete employee.model;
+ else if (body?.model !== undefined) employee.model = body.model;
+ return this.json(employee);
+ }
+ if (c === undefined && method === "DELETE") {
+ if (b === org.ceoAgentId)
+ return this.error(409, "ceo_cannot_leave", "The CEO cannot leave.");
+ org.employees.splice(org.employees.indexOf(employee), 1);
+ return new Response(null, { status: 204 });
+ }
+ if (c === "desk" && method === "GET") {
+ const existing = org.desks.get(String(b));
+ if (existing) return this.json({ agentId: b, ...existing, created: false });
+ return this.json(this.openDesk(org, employee, true));
+ }
+ if (c === "desk" && method === "POST")
+ return this.json(this.openDesk(org, employee, true), 201);
+ }
+
+ if (a === "calendar") {
+ if (b === undefined) {
+ if (method === "POST") {
+ const agentId = body?.agentId;
+ const name = body?.name;
+ if (!isNonEmptyString(agentId) || !isNonEmptyString(name)) {
+ return this.badRequest("agentId and name are required.");
+ }
+ if (!org.employees.some((e) => e.agentId === agentId)) {
+ return this.error(404, "employee_not_found", `${agentId} is not an employee.`);
+ }
+ const fields = this.calendarFields(body);
+ if (!fields.ok) return fields.res;
+ const key = `${agentId}/${name}`;
+ if (org.calendar.has(key)) {
+ return this.error(
+ 409,
+ "calendar_event_exists",
+ `Calendar event already exists: ${key}`,
+ );
+ }
+ const item = this.calendarItem(org, agentId, name, fields.value);
+ org.calendar.set(key, item);
+ return this.json(this.calendarWrite(org, item), 201);
+ }
+ return this.json({
+ events: [...org.calendar.values()],
+ invalidFiles: org.calendarInvalidFiles,
+ });
+ }
+ if (c !== undefined) {
+ const key = `${b}/${c}`;
+ const stored = org.calendar.get(key);
+ if (!stored) {
+ return this.error(
+ 404,
+ "calendar_event_not_found",
+ `Calendar event does not exist: ${key}`,
+ );
+ }
+ if (method === "GET") return this.json(stored);
+ if (method === "PUT") {
+ const fields = this.calendarFields(body);
+ if (!fields.ok) return fields.res;
+ const item = this.calendarItem(org, b!, c, fields.value);
+ org.calendar.set(key, item);
+ return this.json(this.calendarWrite(org, item));
+ }
+ if (method === "DELETE") {
+ org.calendar.delete(key);
+ return new Response(null, { status: 204 });
+ }
+ }
+ }
+
+ if (a === "tickets") {
+ if (b === undefined) {
+ if (method === "POST") return this.createTicket(org, body ?? {});
+ const columns = Object.fromEntries(
+ TICKET_COLUMNS.map((column) => [
+ column,
+ [...org.tickets.values()]
+ .filter((x) => x.status === column)
+ .map((x) => this.ticketItem(x)),
+ ]),
+ );
+ return this.json({ columns, invalidFiles: org.ticketInvalidFiles });
+ }
+ if (!TICKET_ID_RE.test(b)) return this.badRequest("Invalid ticket id.");
+ const rec = org.tickets.get(b);
+ if (!rec) return this.error(404, "ticket_not_found", `Ticket does not exist: ${b}`);
+ if (c === undefined && method === "GET") return this.json(this.ticketDetail(org, rec));
+ if (c === undefined && method === "PUT") {
+ const actor = this.actorOf(body);
+ if (!actor.ok) return actor.res;
+ for (const key of ["title", "notify", "priority", "goal", "acceptanceCriteria", "result"]) {
+ if (body?.[key] !== undefined) rec[key] = body[key];
+ }
+ for (const key of ["owner", "parent", "due"]) {
+ if (body?.[key] === null) delete rec[key];
+ else if (typeof body?.[key] === "string") rec[key] = body[key];
+ }
+ return this.json(this.ticketDetail(org, rec));
+ }
+ if (c !== undefined && method === "POST") return this.ticketAction(org, rec, c, body);
+ }
+
+ if (a === "handbook" && b === "files") {
+ const rel = segments.slice(3).join("/");
+ if (rel === "") {
+ if (method !== "GET") return this.error(404, "not_found", "No such route.");
+ const files = [...org.handbook.entries()]
+ .map(([path, content]) => ({
+ path,
+ size: Buffer.byteLength(content),
+ updatedAt: "2026-09-02T10:00:00.000Z",
+ }))
+ .sort((x, y) =>
+ x.path === "README.md" ? -1 : y.path === "README.md" ? 1 : x.path.localeCompare(y.path),
+ );
+ return this.json({ files });
+ }
+ if (
+ !/^(?:[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/){0,7}[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(rel)
+ ) {
+ return this.badRequest(`${rel} is not a handbook path.`);
+ }
+ if (method === "GET") {
+ const content = org.handbook.get(rel);
+ if (content === undefined) {
+ return this.error(404, "handbook_file_not_found", `${rel} is not in the handbook.`);
+ }
+ return this.json({ path: rel, content });
+ }
+ if (method === "PUT") {
+ if (typeof body?.content !== "string") return this.badRequest("content is required.");
+ org.handbook.set(rel, body.content);
+ return this.json({ path: rel, content: body.content });
+ }
+ if (method === "DELETE") {
+ if (rel === "README.md") {
+ return this.error(
+ 400,
+ "handbook_index_required",
+ "The handbook index (README.md) cannot be deleted.",
+ );
+ }
+ if (!org.handbook.has(rel)) {
+ return this.error(404, "handbook_file_not_found", `${rel} is not in the handbook.`);
+ }
+ org.handbook.delete(rel);
+ return new Response(null, { status: 204 });
+ }
+ }
+
+ if (a === "channels") return this.handleChannels(method, org, segments.slice(2), url, body);
+
+ if (a === "finance" && b === undefined && method === "GET") {
+ const period = url.searchParams.get("period") ?? ORG_PERIOD;
+ if (!/^\d{4}-(?:0[1-9]|1[0-2])$/.test(period))
+ return this.badRequest("period must be yyyy-mm.");
+ const employees = org.employees.map((e) => {
+ const spend = e.spend as { own: number; cumulative: number; ratio?: number };
+ return {
+ agentId: e.agentId,
+ name: e.name,
+ title: e.title,
+ reportsTo: e.reportsTo,
+ own: spend.own,
+ cumulative: spend.cumulative,
+ ...(e.budget !== undefined ? { budget: e.budget } : {}),
+ ...(spend.ratio !== undefined ? { ratio: spend.ratio } : {}),
+ warned: false,
+ paused: e.state === "paused",
+ };
+ });
+ const tickets = [...org.tickets.values()].map((x) => ({
+ ticketId: x.ticketId,
+ title: x.title,
+ status: x.status,
+ ...(x.parent !== undefined ? { parent: x.parent } : {}),
+ cost: x.cost,
+ rolledUp: x.rolledUpCost,
+ }));
+ return this.json({
+ period,
+ currency: "USD",
+ employees,
+ tickets,
+ daily: [],
+ alerts: [],
+ total: employees.reduce((sum, e) => sum + e.own, 0),
+ unpriced: org.unpriced,
+ });
+ }
+
+ return this.error(404, "not_found", `No fake route for ${method} ${url.pathname}`);
+ }
+
+ // ---- company mode: channels ----
+
+ /** The Project's people: its owner, the `user:` half of the all-hands channel. */
+ private projectUserIds(org: FakeOrgState): string[] {
+ const project = this.projects.find((p) => p.projectId === org.projectId);
+ return project === undefined ? [] : [String(project.ownerUserId)];
+ }
+
+ /** A channel's membership as principals: the all-hands channel resolves to everyone, the rest to their list. */
+ private channelMembers(org: FakeOrgState, channel: FakeChannelState): string[] {
+ if (!channel.everyone) return channel.members;
+ return [
+ ...org.employees.map((e) => `agent:${String(e.agentId)}`),
+ ...this.projectUserIds(org).map((id) => `user:${id}`),
+ ];
+ }
+
+ /** An employee's display name, a person's own id. */
+ private principalName(org: FakeOrgState, principal: string): string {
+ if (!principal.startsWith("agent:")) return principal.slice("user:".length);
+ const agentId = principal.slice("agent:".length);
+ return String(org.employees.find((e) => e.agentId === agentId)?.name ?? agentId);
+ }
+
+ private channelItem(
+ org: FakeOrgState,
+ channel: FakeChannelState,
+ caller: { principal: string; agentId: string | null },
+ ): Json {
+ const members = this.channelMembers(org, channel);
+ const last = channel.messages.at(-1);
+ return {
+ channelId: channel.channelId,
+ name: channel.name,
+ purpose: channel.purpose,
+ everyone: channel.everyone,
+ archived: channel.archived,
+ createdBy: channel.createdBy,
+ createdAt: channel.createdAt,
+ memberCount: members.length,
+ isMember: members.includes(caller.principal),
+ // Read cursors belong to people; an employee reads its channel through its trigger.
+ unread: caller.agentId === null ? channel.unread : 0,
+ mentionsMe: caller.agentId === null ? channel.mentionsMe : 0,
+ lastMessageAt: last !== undefined ? last.time : null,
+ };
+ }
+
+ private channelDetail(
+ org: FakeOrgState,
+ channel: FakeChannelState,
+ caller: { principal: string; agentId: string | null },
+ ): Json {
+ return {
+ ...this.channelItem(org, channel, caller),
+ members: this.channelMembers(org, channel).map((principal) => ({
+ principal,
+ name: this.principalName(org, principal),
+ kind: principal.startsWith("agent:") ? "agent" : "user",
+ })),
+ };
+ }
+
+ /** People read every channel; an employee only the ones it belongs to. */
+ private canRead(
+ org: FakeOrgState,
+ channel: FakeChannelState,
+ caller: { principal: string; agentId: string | null },
+ ): boolean {
+ return caller.agentId === null || this.channelMembers(org, channel).includes(caller.principal);
+ }
+
+ private notAMember(channelId: string, principal: string, why?: string): Response {
+ return this.error(
+ 403,
+ "not_a_member",
+ why ?? `${principal} is not a member of the channel ${channelId}.`,
+ );
+ }
+
+ private channelArchived(channelId: string): Response {
+ return this.error(
+ 409,
+ "channel_archived",
+ `Channel ${channelId} is archived: unarchive it before writing to it.`,
+ );
+ }
+
+ /** `agent:<id>` must be an employee and `user:<id>` a Project member — nobody else joins a channel. */
+ private resolveChannelPrincipal(org: FakeOrgState, raw: string): string | null {
+ const m = PRINCIPAL_RE.exec(raw);
+ if (m === null) return null;
+ const [, kind, id] = m as unknown as [string, string, string];
+ if (kind === "agent" && org.employees.some((e) => e.agentId === id)) return `agent:${id}`;
+ if (kind === "user" && this.projectUserIds(org).includes(id)) return `user:${id}`;
+ return null;
+ }
+
+ /**
+ * `…/channels` and everything under it: the membership contract of the server's channel
+ * routes, including which errors each rule answers with. `rest` is the path after
+ * `channels`: `[channelId?, "members" | "messages" | "read"?, principal?]`.
+ */
+ private handleChannels(
+ method: string,
+ org: FakeOrgState,
+ rest: Array<string | undefined>,
+ url: URL,
+ body: Json | undefined,
+ ): Response {
+ const [channelId, sub, principalArg] = rest;
+ if (channelId === undefined) {
+ if (method === "POST") return this.createChannel(org, body);
+ if (method !== "GET") return this.error(404, "not_found", "No such route.");
+ const caller = this.callerOfQuery(url);
+ if (!caller.ok) return caller.res;
+ const channels = [...org.channels.values()]
+ .map((channel) => this.channelItem(org, channel, caller))
+ .filter((item) => caller.agentId === null || item.isMember === true)
+ .sort((x, y) =>
+ x.channelId === DEFAULT_CHANNEL_ID
+ ? -1
+ : y.channelId === DEFAULT_CHANNEL_ID
+ ? 1
+ : String(x.name).localeCompare(String(y.name)) ||
+ String(x.channelId).localeCompare(String(y.channelId)),
+ );
+ return this.json({ channels });
+ }
+
+ // A malformed id names no channel, and neither does an id no channel has.
+ const channel = CHANNEL_ID_RE.test(channelId) ? org.channels.get(channelId) : undefined;
+ if (channel === undefined) {
+ return this.error(404, "channel_not_found", `Channel does not exist: ${channelId}`);
+ }
+
+ if (sub === undefined) {
+ if (method === "GET") {
+ const caller = this.callerOfQuery(url);
+ if (!caller.ok) return caller.res;
+ if (!this.canRead(org, channel, caller)) {
+ return this.notAMember(channelId, caller.principal);
+ }
+ return this.json(this.channelDetail(org, channel, caller));
+ }
+ if (method === "PATCH") return this.patchChannel(org, channel, body);
+ }
+
+ if (sub === "members") {
+ if (principalArg === undefined && method === "POST") {
+ return this.addChannelMember(org, channel, body);
+ }
+ if (principalArg !== undefined && method === "DELETE") {
+ return this.removeChannelMember(org, channel, principalArg, url);
+ }
+ }
+
+ if (sub === "messages") {
+ if (method === "GET") return this.channelMessages(org, channel, url);
+ if (method === "POST") return this.sendChannelMessage(org, channel, body);
+ }
+
+ if (sub === "read" && method === "POST") {
+ if (!isNonEmptyString(body?.upTo)) return this.badRequest("upTo is required.");
+ return new Response(null, { status: 204 });
+ }
+
+ return this.error(404, "not_found", `No fake route for ${method} ${url.pathname}`);
+ }
+
+ /** A new channel holds exactly its creator; everyone else arrives by invitation. */
+ private createChannel(org: FakeOrgState, body: Json | undefined): Response {
+ const channelId = body?.channelId;
+ if (!isNonEmptyString(channelId) || channelId.length < 2 || channelId.length > 64) {
+ return this.badRequest("channelId is required.");
+ }
+ if (!CHANNEL_ID_RE.test(channelId)) return this.badRequest("Invalid channel id.");
+ const actor = this.actorOf(body);
+ if (!actor.ok) return actor.res;
+ if (org.channels.has(channelId)) {
+ return this.error(409, "channel_exists", `Channel id is already taken: ${channelId}`);
+ }
+ const channel = this.addChannel(org.orgId, channelId, {
+ name: isNonEmptyString(body?.name) ? body.name.trim() : channelId,
+ purpose: typeof body?.purpose === "string" ? body.purpose.trim() : "",
+ createdBy: actor.principal,
+ members: [actor.principal],
+ });
+ this.addMessage(
+ org.orgId,
+ { sender: "system", text: `${actor.principal} created the channel.` },
+ channelId,
+ );
+ return this.json(this.channelItem(org, channel, actor), 201);
+ }
+
+ /** Rename and change of purpose are any member's; archiving is a person's, and never of the all-hands channel. */
+ private patchChannel(
+ org: FakeOrgState,
+ channel: FakeChannelState,
+ body: Json | undefined,
+ ): Response {
+ const actor = this.actorOf(body);
+ if (!actor.ok) return actor.res;
+ const archived = body?.archived;
+ if (archived !== undefined) {
+ if (typeof archived !== "boolean") return this.badRequest("archived must be a boolean.");
+ if (channel.channelId === DEFAULT_CHANNEL_ID) {
+ return this.error(400, "all_hands_immutable", "The all-hands channel cannot be archived.");
+ }
+ if (actor.agentId !== null) {
+ return this.notAMember(
+ channel.channelId,
+ actor.principal,
+ "Only people archive a channel.",
+ );
+ }
+ }
+ // Everything but lifting the archive itself is refused while the channel is archived.
+ if (channel.archived && archived !== false) return this.channelArchived(channel.channelId);
+ if (body?.name !== undefined || body?.purpose !== undefined) {
+ if (!this.channelMembers(org, channel).includes(actor.principal)) {
+ return this.notAMember(channel.channelId, actor.principal);
+ }
+ }
+ if (body?.name !== undefined) {
+ if (!isNonEmptyString(body.name) || body.name.trim() === "") {
+ return this.badRequest("name must not be empty.");
+ }
+ channel.name = body.name.trim();
+ }
+ if (typeof body?.purpose === "string") channel.purpose = body.purpose.trim();
+ if (archived !== undefined && archived !== channel.archived) {
+ this.addMessage(
+ org.orgId,
+ {
+ sender: "system",
+ text: `${actor.principal} ${archived ? "archived" : "unarchived"} the channel.`,
+ },
+ channel.channelId,
+ );
+ channel.archived = archived;
+ }
+ return this.json(this.channelItem(org, channel, actor));
+ }
+
+ /** Any member invites; a person may also join by itself, an employee may not. */
+ private addChannelMember(
+ org: FakeOrgState,
+ channel: FakeChannelState,
+ body: Json | undefined,
+ ): Response {
+ const raw = body?.principal;
+ if (!isNonEmptyString(raw) || PRINCIPAL_RE.exec(raw) === null) {
+ return this.error(400, "invalid_principal", "principal must be agent:<id> or user:<id>.");
+ }
+ const actor = this.actorOf(body);
+ if (!actor.ok) return actor.res;
+ if (channel.channelId === DEFAULT_CHANNEL_ID) {
+ return this.error(
+ 400,
+ "all_hands_immutable",
+ "Everyone is in the all-hands channel already.",
+ );
+ }
+ if (channel.archived) return this.channelArchived(channel.channelId);
+ const principal = this.resolveChannelPrincipal(org, raw);
+ if (principal === null) {
+ return this.error(
+ 400,
+ "invalid_principal",
+ `Not an employee of ${org.orgId} or a member of this Project: ${raw}`,
+ );
+ }
+ if (principal === actor.principal) {
+ if (actor.agentId !== null) {
+ return this.notAMember(
+ channel.channelId,
+ actor.principal,
+ "An employee joins a channel only when a member invites it.",
+ );
+ }
+ } else if (!channel.members.includes(actor.principal)) {
+ return this.notAMember(channel.channelId, actor.principal);
+ }
+ // Adding an existing member changes nothing and still answers with the detail.
+ if (!channel.members.includes(principal)) {
+ channel.members.push(principal);
+ this.addMessage(
+ org.orgId,
+ {
+ sender: "system",
+ text:
+ principal === actor.principal
+ ? `${principal} joined the channel.`
+ : `${actor.principal} invited ${principal} to the channel.`,
+ },
+ channel.channelId,
+ );
+ }
+ return this.json(this.channelDetail(org, channel, actor), 201);
+ }
+
+ /** A member removes itself; a person may remove anyone. Removing a non-member changes nothing. */
+ private removeChannelMember(
+ org: FakeOrgState,
+ channel: FakeChannelState,
+ rawPrincipal: string,
+ url: URL,
+ ): Response {
+ if (PRINCIPAL_RE.exec(rawPrincipal) === null) {
+ return this.error(400, "invalid_principal", "principal must be agent:<id> or user:<id>.");
+ }
+ const caller = this.callerOfQuery(url);
+ if (!caller.ok) return caller.res;
+ if (channel.channelId === DEFAULT_CHANNEL_ID) {
+ return this.error(400, "all_hands_immutable", "Nobody leaves the all-hands channel.");
+ }
+ if (channel.archived) return this.channelArchived(channel.channelId);
+ if (caller.agentId !== null && rawPrincipal !== caller.principal) {
+ return this.notAMember(
+ channel.channelId,
+ caller.principal,
+ "An employee removes only itself from a channel.",
+ );
+ }
+ const at = channel.members.indexOf(rawPrincipal);
+ if (at >= 0) {
+ channel.members.splice(at, 1);
+ this.addMessage(
+ org.orgId,
+ {
+ sender: "system",
+ text:
+ rawPrincipal === caller.principal
+ ? `${rawPrincipal} left the channel.`
+ : `${caller.principal} removed ${rawPrincipal} from the channel.`,
+ },
+ channel.channelId,
+ );
+ }
+ return new Response(null, { status: 204 });
+ }
+
+ private channelMessages(org: FakeOrgState, channel: FakeChannelState, url: URL): Response {
+ const caller = this.callerOfQuery(url);
+ if (!caller.ok) return caller.res;
+ if (!this.canRead(org, channel, caller)) {
+ return this.notAMember(channel.channelId, caller.principal);
+ }
+ const date = url.searchParams.get("date") ?? ORG_TODAY;
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return this.badRequest("date must be yyyy-mm-dd.");
+ const days = [...new Set(channel.messages.map((m) => String(m.time).slice(0, 10)))]
+ .sort()
+ .reverse();
+ return this.json({
+ channelId: channel.channelId,
+ date,
+ days,
+ messages: channel.messages.filter((m) => String(m.time).startsWith(date)),
+ unread: caller.agentId === null ? channel.unread : 0,
+ mentionsMe: caller.agentId === null ? channel.mentionsMe : 0,
+ });
+ }
+
+ /** Members post; a message naming a non-member is refused before anything is written. */
+ private sendChannelMessage(
+ org: FakeOrgState,
+ channel: FakeChannelState,
+ body: Json | undefined,
+ ): Response {
+ if (!isNonEmptyString(body?.text)) return this.badRequest("text is required.");
+ const actor = this.actorOf(body);
+ if (!actor.ok) return actor.res;
+ if (channel.archived) return this.channelArchived(channel.channelId);
+ const members = this.channelMembers(org, channel);
+ if (!members.includes(actor.principal)) {
+ return this.notAMember(channel.channelId, actor.principal);
+ }
+ // `@all` is the channel's own membership, so only named principals can be outsiders.
+ const outsiders = mentionsOf(body.text).filter((m) => m !== "all" && !members.includes(m));
+ if (outsiders.length > 0) {
+ return this.error(
+ 400,
+ "mention_not_member",
+ `Not a member of ${channel.channelId}: ${outsiders.join(", ")}. Invite them first, or write in a channel they are in.`,
+ );
+ }
+ const msg = this.addMessage(
+ org.orgId,
+ {
+ sender: actor.principal,
+ text: body.text,
+ ...(body.refs !== undefined ? { refs: body.refs } : {}),
+ },
+ channel.channelId,
+ );
+ return this.json(msg, 201);
+ }
+
+ private calendarItem(org: FakeOrgState, agentId: string, name: string, fields: Json): Json {
+ return {
+ agentId,
+ name,
+ ...fields,
+ status: fields.enabled === true ? "active" : "disabled",
+ paused: org.status === "paused",
+ ...(fields.enabled === true ? { nextFireAt: fields.startAt } : {}),
+ };
+ }
+
+ /** What a calendar write answers: the stored event plus the rota advice the test staged. */
+ private calendarWrite(org: FakeOrgState, item: Json): Json {
+ return {
+ ...item,
+ ...(org.calendarWarnings.length > 0 ? { warnings: org.calendarWarnings } : {}),
+ };
+ }
+
+ private createTicket(org: FakeOrgState, body: Json): Response {
+ if (!isNonEmptyString(body.title)) return this.badRequest("title is required.");
+ const actor = this.actorOf(body);
+ if (!actor.ok) return actor.res;
+ if (body.priority !== undefined && !["P0", "P1", "P2"].includes(String(body.priority))) {
+ return this.badRequest("priority must be P0, P1 or P2.");
+ }
+ if (body.parent !== undefined && !TICKET_ID_RE.test(String(body.parent))) {
+ return this.badRequest("parent must be a ticket id.");
+ }
+ if (typeof body.slug === "string" && !TICKET_SLUG_RE.test(body.slug)) {
+ return this.badRequest("slug must be lowercase English words joined by hyphens.");
+ }
+ const slug = typeof body.slug === "string" ? body.slug : slugify(body.title);
+ if (slug === "") {
+ return this.error(
+ 400,
+ "slug_required",
+ "pass --slug: lowercase English words joined by hyphens",
+ );
+ }
+ const ticketId = `${ORG_TODAY}-${slug}`;
+ if (org.tickets.has(ticketId))
+ return this.error(409, "ticket_exists", `Ticket already exists: ${ticketId}`);
+ // One owner: `--owner` when it is given, the caller otherwise.
+ const owner = isNonEmptyString(body.owner) ? body.owner : actor.principal;
+ const rec = this.addTicket(org.orgId, {
+ ticketId,
+ title: body.title,
+ owner,
+ notify: Array.isArray(body.notify) ? body.notify : [],
+ history: [
+ { at: ORG_NOW, by: actor.principal, action: "created" },
+ ...(owner !== actor.principal
+ ? [{ at: ORG_NOW, by: actor.principal, action: "assigned", note: owner }]
+ : []),
+ ],
+ ...(typeof body.parent === "string" ? { parent: body.parent } : {}),
+ ...(typeof body.priority === "string" ? { priority: body.priority } : {}),
+ ...(typeof body.due === "string" ? { due: body.due } : {}),
+ goal: typeof body.goal === "string" ? body.goal : "",
+ acceptanceCriteria:
+ typeof body.acceptanceCriteria === "string" ? body.acceptanceCriteria : "",
+ ...(typeof body.body === "string" ? { rawBody: body.body } : {}),
+ });
+ return this.json(this.ticketDetail(org, rec), 201);
+ }
+
+ /** POST …/tickets/:id/(move|block|unblock|progress|start|attach). */
+ private ticketAction(
+ org: FakeOrgState,
+ rec: Json,
+ action: string,
+ body: Json | undefined,
+ ): Response {
+ const sessions = rec.sessions as string[];
+ switch (action) {
+ case "move": {
+ const status = String(body?.status ?? "");
+ if (!(TICKET_COLUMNS as readonly string[]).includes(status)) {
+ return this.badRequest("status must be a column.");
+ }
+ if (status === "rejected" && !isNonEmptyString(body?.reason)) {
+ return this.badRequest("reason is required when moving into rejected.");
+ }
+ const actor = this.actorOf(body);
+ if (!actor.ok) return actor.res;
+ rec.status = status;
+ if (typeof body?.reason === "string") rec.result = body.reason;
+ return this.json(this.ticketDetail(org, rec));
+ }
+ case "block": {
+ if (!isNonEmptyString(body?.reason)) return this.badRequest("reason is required.");
+ const actor = this.actorOf(body);
+ if (!actor.ok) return actor.res;
+ rec.blocked = body.reason;
+ if (isNonEmptyString(body.by)) rec.blockedBy = body.by;
+ else delete rec.blockedBy;
+ return this.json(this.ticketDetail(org, rec));
+ }
+ case "unblock": {
+ const actor = this.actorOf(body);
+ if (!actor.ok) return actor.res;
+ delete rec.blocked;
+ delete rec.blockedBy;
+ return this.json(this.ticketDetail(org, rec));
+ }
+ case "progress": {
+ if (!isNonEmptyString(body?.text)) return this.badRequest("text is required.");
+ const actor = this.actorOf(body);
+ if (!actor.ok) return actor.res;
+ (rec.progress as string[]).push(body.text);
+ (rec.history as Json[]).push({
+ at: ORG_NOW,
+ by: actor.principal,
+ action: "progress",
+ note: body.text.slice(0, 80),
+ });
+ if (actor.sessionId !== undefined && !sessions.includes(actor.sessionId)) {
+ sessions.push(actor.sessionId);
+ }
+ return this.json(this.ticketDetail(org, rec));
+ }
+ case "start": {
+ const owner =
+ typeof rec.owner === "string" && rec.owner.startsWith("agent:")
+ ? rec.owner.slice(6)
+ : undefined;
+ const agentId = isNonEmptyString(body?.agentId) ? body.agentId : owner;
+ if (agentId === undefined)
+ return this.badRequest("The ticket has no employee owner; pass agentId.");
+ const employee = org.employees.find((e) => e.agentId === agentId);
+ if (!employee)
+ return this.error(404, "employee_not_found", `${agentId} is not an employee.`);
+ const s = this.addSession({
+ agentId,
+ workspace: isNonEmptyString(body?.workspace)
+ ? body.workspace
+ : String(employee.resolvedWorkspace ?? "/shared"),
+ });
+ sessions.push(s.sessionId);
+ rec.running = true;
+ return this.json({ sessionId: s.sessionId }, 202);
+ }
+ case "attach": {
+ if (!isNonEmptyString(body?.sessionId)) return this.badRequest("sessionId is required.");
+ const actor = this.actorOf(body);
+ if (!actor.ok) return actor.res;
+ if (!sessions.includes(body.sessionId)) sessions.push(body.sessionId);
+ return this.json(this.ticketDetail(org, rec));
+ }
+ default:
+ return this.error(404, "not_found", `No fake route for POST tickets/${action}`);
+ }
+ }
+
private async handle(input: string | URL | Request, init?: RequestInit): Promise<Response> {
const url = new URL(
typeof input === "string" ? input : input instanceof URL ? input.href : input.url,
@@ -244,7 +1581,12 @@ export class FakeServer {
if (typeof init?.body === "string" && init.body.length > 0) {
body = JSON.parse(init.body) as Json;
}
- this.requests.push({ method, path: apiPath, ...(body !== undefined ? { body } : {}) });
+ this.requests.push({
+ method,
+ path: apiPath,
+ search: url.search,
+ ...(body !== undefined ? { body } : {}),
+ });
// Session create
let m = /^\/api\/projects\/([^/]+)\/agents\/([^/]+)\/sessions$/.exec(apiPath);
@@ -294,6 +1636,23 @@ export class FakeServer {
return this.json({ projects: this.projects });
}
+ // The signed-in user: how a command that has to name the caller as `user:<id>` learns it.
+ if (apiPath === "/api/me" && method === "GET") {
+ return this.json({
+ user: {
+ userId: this.userId,
+ isAdmin: true,
+ passwordIsInitial: false,
+ createdAt: "2026-08-01T00:00:00.000Z",
+ },
+ previewIsolated: true,
+ desktopMode: false,
+ sessionVia: "token",
+ uploadLimits: {},
+ companyMode: true,
+ });
+ }
+
m = /^\/api\/projects\/([^/]+)\/usage$/.exec(apiPath);
if (m) {
const groupBy = url.searchParams.get("groupBy") ?? "date";
@@ -344,6 +1703,11 @@ export class FakeServer {
}
}
+ // Company mode, nested under a Project
+ m = /^\/api\/projects\/([^/]+)\/organizations(?:\/(.*))?$/.exec(apiPath);
+ if (m)
+ return this.handleOrganizations(method, decodeURIComponent(m[1]!), m[2] ?? "", url, body);
+
// Session-level endpoints
m = /^\/api\/sessions\/([^/]+)(\/.*)?$/.exec(apiPath);
if (m) {
diff --git a/packages/cli/test/i18n.test.ts b/packages/cli/test/i18n.test.ts
index 7776db18..8f044c8b 100644
--- a/packages/cli/test/i18n.test.ts
+++ b/packages/cli/test/i18n.test.ts
@@ -121,6 +121,22 @@ describe("getMessages", () => {
const hint = m.usage.hint("penguin schedule add", "[options] <name>");
expect(hint).toContain("penguin schedule add [options] <name>");
expect(hint).toContain("penguin schedule add --help");
+ // The company-mode family: descriptions, the control-environment default, confirmations.
+ expect(m.org.lsDesc.length).toBeGreaterThan(0);
+ expect(m.org.ticketCreateDesc.length).toBeGreaterThan(0);
+ expect(m.org.orgId).toContain("PENGUIN_ORG_ID");
+ expect(m.org.orgIdMissing()).toContain("PENGUIN_ORG_ID");
+ expect(m.org.hireTargetConflict()).toContain("--new-agent");
+ expect(m.org.statusInvalid("bogus")).toContain("bogus");
+ expect(m.org.created("acme", "session-x")).toContain("session-x");
+ expect(m.org.created("acme", undefined)).toContain("acme");
+ expect(m.org.hired("dev1", "Developer", "ceo")).toContain("ceo");
+ expect(m.org.ticketMoved("2026-09-02-site", "in_progress")).toContain("in_progress");
+ expect(m.org.calendarWritten("dev1", "standup", m.schedule.enabled(), undefined)).toContain(
+ "dev1/standup",
+ );
+ expect(m.org.ticketHead("2026-09-02-site", "review", false, "waiting")).toContain("waiting");
+ expect(m.org.financeTotal("2026-09", "$1.0000")).toContain("2026-09");
}
// Argument errors really are translated, not the English text twice.
expect(getMessages("zh").usage.missingArgument("sessionId")).not.toBe(
@@ -131,6 +147,7 @@ describe("getMessages", () => {
);
// The dictionaries are genuinely two languages, not one copied twice.
expect(getMessages("zh").ls.desc).not.toBe(getMessages("en").ls.desc);
+ expect(getMessages("zh").org.desc).not.toBe(getMessages("en").org.desc);
expect(getMessages("zh").client.noServer()).not.toBe(getMessages("en").client.noServer());
});
diff --git a/packages/cli/test/org-commands.test.ts b/packages/cli/test/org-commands.test.ts
new file mode 100644
index 00000000..c88b48f2
--- /dev/null
+++ b/packages/cli/test/org-commands.test.ts
@@ -0,0 +1,1375 @@
+/**
+ * `penguin org` wiring, driven through `cli()` in-process against the fake server's
+ * organization routes: list / overview / chart rendering, creation, hiring (both forms
+ * and the exclusivity rule), the calendar writer, the ticket writes (their bodies, and
+ * the caller identity taken from the control environment), the channel family with its
+ * membership rules, finance, the --org-id default and --json output.
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { cli } from "../src/index.js";
+import { getMessages } from "../src/i18n.js";
+import { FakeServer } from "./fake-server.js";
+
+const t = getMessages("en");
+
+/** The control environment a desk or ticket session carries: every test starts without it and restores what was there. */
+const ENV_KEYS = ["PENGUIN_ORG_ID", "PENGUIN_AGENT_ID", "PENGUIN_SESSION_ID", "PENGUIN_PROJECT_ID"];
+const saved = new Map<string, string | undefined>();
+
+/** The desk session the CLI is assumed to run inside when PENGUIN_SESSION_ID is set below. */
+const DESK_SESSION = "session-2026-09-02-10-00-00-de5c0001";
+
+let server: FakeServer;
+let uninstall: () => void;
+let stdout: string[];
+let stderr: string[];
+let outSpy: { mockRestore(): void };
+let errSpy: { mockRestore(): void };
+
+beforeEach(() => {
+ for (const key of ENV_KEYS) {
+ saved.set(key, process.env[key]);
+ delete process.env[key];
+ }
+ server = new FakeServer();
+ uninstall = server.install();
+ server.addOrg({ orgId: "acme", name: "Acme", mission: "Ship the site" });
+ process.env.PENGUIN_ORG_ID = "acme";
+ stdout = [];
+ stderr = [];
+ outSpy = vi.spyOn(process.stdout, "write").mockImplementation((chunk) => {
+ stdout.push(String(chunk));
+ return true;
+ });
+ errSpy = vi.spyOn(process.stderr, "write").mockImplementation((chunk) => {
+ stderr.push(String(chunk));
+ return true;
+ });
+});
+afterEach(() => {
+ outSpy.mockRestore();
+ errSpy.mockRestore();
+ uninstall();
+ for (const [key, value] of saved) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+});
+
+const out = () => stdout.join("");
+const err = () => stderr.join("");
+/** The most recent recorded request of `method` whose path ends with `suffix`. */
+const lastRequest = (method: string, suffix: string) =>
+ server.requests.findLast((r) => r.method === method && r.path.endsWith(suffix));
+const org = () => server.orgs.get("acme")!;
+
+describe("penguin org ls / show / chart", () => {
+ it("ls lists organizations with counts and spend; --json prints the response", async () => {
+ server.addEmployee("acme", {
+ agentId: "dev1",
+ title: "Developer",
+ state: "running",
+ spend: { own: 1.5, cumulative: 1.5 },
+ });
+ server.addTicket("acme", {
+ ticketId: "2026-09-02-site",
+ title: "Build the site",
+ status: "in_progress",
+ blocked: "waiting for keys",
+ });
+ org().spend = { period: "2026-09", cost: 1.5, budget: 50, ratio: 0.03 };
+ expect(await cli(["org", "ls"])).toBe(0);
+ const text = out();
+ expect(text).toContain("acme");
+ expect(text).toContain("Acme");
+ expect(text).toContain("active");
+ expect(text).toContain("$1.5000 / $50.00 (3%)");
+
+ stdout.length = 0;
+ expect(await cli(["org", "ls", "--json"])).toBe(0);
+ const parsed = JSON.parse(out()) as { organizations: Array<Record<string, unknown>> };
+ expect(parsed.organizations[0]).toMatchObject({
+ orgId: "acme",
+ employeeCount: 2,
+ runningCount: 1,
+ openTickets: 1,
+ blockedTickets: 1,
+ });
+ });
+
+ it("ls prints the empty line when the project has no organization", async () => {
+ server.orgs.clear();
+ expect(await cli(["org", "ls"])).toBe(0);
+ expect(out()).toBe(`${t.org.empty("default_project")}\n`);
+ });
+
+ it("show prints the overview: identity, mission, people, board, spend, pending", async () => {
+ server.addEmployee("acme", { agentId: "dev1", title: "Developer", state: "running" });
+ server.addTicket("acme", { ticketId: "2026-09-02-site", title: "Site", status: "review" });
+ server.addTicket("acme", { ticketId: "2026-09-02-docs", title: "Docs", blocked: "waiting" });
+ expect(await cli(["org", "show"])).toBe(0);
+ const text = out();
+ expect(text).toContain("Acme (acme) — active");
+ expect(text).toContain("Mission: Ship the site");
+ expect(text).toContain(t.org.showLanguage("en"));
+ expect(text).toContain(t.org.showEmployees(2, 1, 0));
+ expect(text).toContain("proposed 1, in_progress 0, review 1, done 0, rejected 0 (1 blocked)");
+ expect(text).toContain("Spend (2026-09): $0.0000");
+ expect(text).toContain(t.org.showPending(0, 1, 0));
+
+ stdout.length = 0;
+ expect(await cli(["org", "show", "--json"])).toBe(0);
+ expect(JSON.parse(out())).toMatchObject({ orgId: "acme", board: { review: 1, proposed: 1 } });
+ });
+
+ it("chart renders the reporting tree indented by depth, with state, spend and budget", async () => {
+ server.addEmployee("acme", {
+ agentId: "hr",
+ title: "HR",
+ budget: 20,
+ spend: { own: 2, cumulative: 8, ratio: 0.4 },
+ });
+ server.addEmployee("acme", {
+ agentId: "dev1",
+ title: "Developer",
+ reportsTo: "hr",
+ state: "running",
+ spend: { own: 6, cumulative: 6 },
+ });
+ server.addEmployee("acme", {
+ agentId: "ghost",
+ title: "Contractor",
+ reportsTo: "nobody",
+ invalid: "missing Agent",
+ });
+ expect(await cli(["org", "chart"])).toBe(0);
+ const lines = out().split("\n");
+ const row = (id: string) => lines.find((l) => l.trimStart().startsWith(`${id} `))!;
+ expect(row("ceo").startsWith("ceo ")).toBe(true);
+ expect(row("hr").startsWith(" hr ")).toBe(true);
+ expect(row("dev1").startsWith(" dev1 ")).toBe(true);
+ expect(row("hr")).toContain("$2.0000");
+ expect(row("hr")).toContain("$8.0000");
+ expect(row("hr")).toContain("$20.00 (40%)");
+ expect(row("dev1")).toContain("running");
+ // An employee whose manager is not in the tree is listed at the root with its reason, not dropped.
+ expect(row("ghost").startsWith("ghost ")).toBe(true);
+ expect(row("ghost")).toContain("invalid: missing Agent");
+
+ stdout.length = 0;
+ expect(await cli(["org", "chart", "--json"])).toBe(0);
+ expect(JSON.parse(out())).toMatchObject({ ceoAgentId: "ceo" });
+ });
+});
+
+describe("penguin org create", () => {
+ it("posts the definition and prints the org id with the CEO's desk session id", async () => {
+ expect(
+ await cli([
+ "org",
+ "create",
+ "--org-id",
+ "beta",
+ "--mission",
+ "Make widgets",
+ "--name",
+ "Beta Inc",
+ ]),
+ ).toBe(0);
+ // --ceo-budget defaults to 100: the CEO's chart entry is the whole company's budget,
+ // so a new organization is capped rather than unbounded.
+ expect(lastRequest("POST", "/organizations")?.body).toEqual({
+ orgId: "beta",
+ mission: "Make widgets",
+ name: "Beta Inc",
+ ceoBudget: 100,
+ });
+ const beta = server.orgs.get("beta")!;
+ expect(beta.employees.find((e) => e.agentId === "ceo")?.budget).toBe(100);
+ expect(beta.ceoDeskSessionId).toBeDefined();
+ expect(out()).toBe(`${t.org.created("beta", beta.ceoDeskSessionId)}\n`);
+
+ stdout.length = 0;
+ expect(await cli(["org", "create", "--org-id", "gamma", "--mission", "m", "--json"])).toBe(0);
+ expect(JSON.parse(out())).toMatchObject({ orgId: "gamma", mission: "m", employeeCount: 1 });
+ });
+
+ it("--ceo-budget sets the CEO's budget; a negative amount is refused before any request", async () => {
+ expect(
+ await cli(["org", "create", "--org-id", "beta", "--mission", "m", "--ceo-budget", "250.5"]),
+ ).toBe(0);
+ expect(lastRequest("POST", "/organizations")?.body).toMatchObject({ ceoBudget: 250.5 });
+ expect(server.orgs.get("beta")!.employees.find((e) => e.agentId === "ceo")?.budget).toBe(250.5);
+
+ stdout.length = 0;
+ for (const bad of ["-1", "many"]) {
+ expect(
+ await cli(["org", "create", "--org-id", "delta", "--mission", "m", "--ceo-budget", bad]),
+ ).toBe(1);
+ expect(server.orgs.has("delta")).toBe(false);
+ }
+ expect(err()).toContain(t.org.budgetInvalid("--ceo-budget", "many"));
+ });
+
+ it("--language overrides the language the mission would give; a value that is neither is refused", async () => {
+ expect(
+ await cli(["org", "create", "--org-id", "beta", "--mission", "m", "--language", "zh"]),
+ ).toBe(0);
+ expect(lastRequest("POST", "/organizations")?.body).toMatchObject({ language: "zh" });
+ // Omitted, the field is not sent at all: the server detects it from the mission.
+ expect(await cli(["org", "create", "--org-id", "gamma", "--mission", "m"])).toBe(0);
+ expect(lastRequest("POST", "/organizations")?.body).not.toHaveProperty("language");
+
+ expect(
+ await cli(["org", "create", "--org-id", "delta", "--mission", "m", "--language", "fr"]),
+ ).toBe(1);
+ expect(err()).toContain(t.org.languageInvalid("fr"));
+ expect(server.orgs.has("delta")).toBe(false);
+ });
+
+ it("create's --org-id names the organization to create; PENGUIN_ORG_ID never fills it in", async () => {
+ expect(await cli(["org", "create", "--mission", "m"])).toBe(1);
+ expect(err()).toContain("--org-id");
+ expect(server.requests.some((r) => r.method === "POST")).toBe(false);
+ });
+});
+
+describe("penguin org hire / employee set / leave", () => {
+ it("hire --agent-id employs an existing Agent; the body carries title, manager, workspace, budget and duties", async () => {
+ server.agents.push({
+ agentId: "dev1",
+ name: "Dev One",
+ description: "",
+ sessionCount: 0,
+ activeSessionCount: 0,
+ sessionActivity: [],
+ });
+ expect(
+ await cli([
+ "org",
+ "hire",
+ "--agent-id",
+ "dev1",
+ "--title",
+ "Developer",
+ "--reports-to",
+ "ceo",
+ "--workspace",
+ "site",
+ "--budget",
+ "20",
+ "--duties",
+ "Builds things",
+ ]),
+ ).toBe(0);
+ expect(lastRequest("POST", "/employees")?.body).toEqual({
+ agentId: "dev1",
+ title: "Developer",
+ reportsTo: "ceo",
+ workspace: "site",
+ budget: 20,
+ duties: "Builds things",
+ });
+ expect(out()).toBe(`${t.org.hired("dev1", "Developer", "ceo")}\n`);
+ });
+
+ it("hire --new-agent creates the Agent: name, description and --skills become newAgent.plugins", async () => {
+ expect(
+ await cli([
+ "org",
+ "hire",
+ "--new-agent",
+ "writer",
+ "--name",
+ "Writer",
+ "--description",
+ "Writes docs",
+ "--skills",
+ "agent-company, humanizer",
+ "--title",
+ "Writer",
+ "--reports-to",
+ "ceo",
+ ]),
+ ).toBe(0);
+ expect(lastRequest("POST", "/employees")?.body).toEqual({
+ newAgent: {
+ agentId: "writer",
+ name: "Writer",
+ description: "Writes docs",
+ plugins: ["agent-company", "humanizer"],
+ },
+ title: "Writer",
+ reportsTo: "ceo",
+ });
+ expect(server.agents.some((a) => a.agentId === "writer")).toBe(true);
+ expect(org().employees.some((e) => e.agentId === "writer")).toBe(true);
+ });
+
+ it("hire takes exactly one of --agent-id and --new-agent; the new-Agent fields and a bad budget are refused locally", async () => {
+ const base = ["org", "hire", "--title", "T", "--reports-to", "ceo"];
+ expect(await cli([...base, "--agent-id", "a", "--new-agent", "b"])).toBe(1);
+ expect(err()).toContain("--new-agent");
+ expect(await cli(base)).toBe(1);
+ expect(await cli([...base, "--agent-id", "a", "--skills", "x"])).toBe(1);
+ expect(await cli([...base, "--agent-id", "a", "--budget", "-1"])).toBe(1);
+ expect(server.requests.some((r) => r.method === "POST")).toBe(false);
+ });
+
+ it("employee set PATCHes the given fields (the model as a pair); nothing to set is refused", async () => {
+ server.addEmployee("acme", { agentId: "dev1", title: "Developer" });
+ expect(
+ await cli([
+ "org",
+ "employee",
+ "set",
+ "dev1",
+ "--title",
+ "Senior Developer",
+ "--budget",
+ "30",
+ "--model-id",
+ "m1",
+ "--provider",
+ "p1",
+ ]),
+ ).toBe(0);
+ expect(lastRequest("PATCH", "/employees/dev1")?.body).toEqual({
+ title: "Senior Developer",
+ budget: 30,
+ model: { provider: "p1", modelId: "m1" },
+ });
+ expect(out()).toBe(`${t.org.employeeUpdated("dev1")}\n`);
+ expect(await cli(["org", "employee", "set", "dev1", "--model-id", "m1"])).toBe(1);
+ expect(await cli(["org", "employee", "set", "dev1"])).toBe(1);
+ expect(err()).toContain(t.org.nothingToSet());
+ });
+
+ it("leave DELETEs the employee; the server's refusal for the CEO surfaces verbatim", async () => {
+ server.addEmployee("acme", { agentId: "dev1" });
+ expect(await cli(["org", "leave", "dev1"])).toBe(0);
+ expect(lastRequest("DELETE", "/employees/dev1")).toBeDefined();
+ expect(org().employees.some((e) => e.agentId === "dev1")).toBe(false);
+ expect(out()).toBe(`${t.org.left("dev1")}\n`);
+ expect(await cli(["org", "leave", "ceo"])).toBe(1);
+ expect(err()).toContain("409");
+ });
+});
+
+describe("penguin org desk", () => {
+ it("show defaults the employee to PENGUIN_AGENT_ID and opens the desk when there is none; renew POSTs a fresh one", async () => {
+ server.addEmployee("acme", { agentId: "dev1" });
+ process.env.PENGUIN_AGENT_ID = "dev1";
+ expect(await cli(["org", "desk", "show"])).toBe(0);
+ expect(lastRequest("GET", "/employees/dev1/desk")).toBeDefined();
+ const first = String(org().desks.get("dev1")!.sessionId);
+ expect(out()).toContain(first);
+
+ stdout.length = 0;
+ expect(await cli(["org", "desk", "renew", "dev1", "--json"])).toBe(0);
+ expect(lastRequest("POST", "/employees/dev1/desk")).toBeDefined();
+ const renewed = JSON.parse(out()) as { sessionId: string; created: boolean };
+ expect(renewed.created).toBe(true);
+ expect(renewed.sessionId).not.toBe(first);
+ });
+});
+
+describe("penguin org calendar", () => {
+ beforeEach(() => {
+ server.addEmployee("acme", { agentId: "dev1" });
+ process.env.PENGUIN_AGENT_ID = "dev1";
+ });
+
+ it("add posts the event under the calling employee, enabled, with --start-at now resolved to the current instant", async () => {
+ const before = Date.now();
+ expect(
+ await cli([
+ "org",
+ "calendar",
+ "add",
+ "standup",
+ "--prompt",
+ "check the board",
+ "--start-at",
+ "now",
+ "--period",
+ "1d",
+ "--title",
+ "Standup",
+ ]),
+ ).toBe(0);
+ const body = lastRequest("POST", "/calendar")?.body as { startAt: string };
+ expect(body).toMatchObject({
+ agentId: "dev1",
+ name: "standup",
+ enabled: true,
+ prompt: "check the board",
+ period: "1d",
+ title: "Standup",
+ });
+ const ms = Date.parse(body.startAt);
+ expect(ms).toBeGreaterThanOrEqual(before - 1000);
+ expect(ms).toBeLessThanOrEqual(Date.now() + 1000);
+ expect(out()).toContain("dev1/standup");
+ });
+
+ it("prints the rota advice the write answered with, under the written line", async () => {
+ org().calendarWarnings = [
+ "`acme_hr/hr-audit` also fires at 10:00; give every employee its own minute.",
+ ];
+ expect(
+ await cli([
+ "org",
+ "calendar",
+ "add",
+ "standup",
+ "--prompt",
+ "p",
+ "--start-at",
+ "2026-09-08T10:00:00.000Z",
+ "--period",
+ "1d",
+ ]),
+ ).toBe(0);
+ expect(out()).toBe(
+ [
+ t.org.calendarWritten("dev1", "standup", t.schedule.enabled(), "2026-09-08T10:00:00.000Z"),
+ t.org.calendarWarning(
+ "`acme_hr/hr-audit` also fires at 10:00; give every employee its own minute.",
+ ),
+ "",
+ ].join("\n"),
+ );
+
+ // --json hands the warnings on as the server returned them.
+ stdout.length = 0;
+ expect(
+ await cli([
+ "org",
+ "calendar",
+ "update",
+ "standup",
+ "--start-at",
+ "2026-09-08T11:00:00.000Z",
+ "--json",
+ ]),
+ ).toBe(0);
+ expect((JSON.parse(out()) as { warnings: string[] }).warnings).toEqual(org().calendarWarnings);
+ });
+
+ it("--disabled opts out of the enabled default; --agent-id overrides the environment", async () => {
+ server.addEmployee("acme", { agentId: "hr" });
+ expect(
+ await cli([
+ "org",
+ "calendar",
+ "add",
+ "weekly",
+ "--agent-id",
+ "hr",
+ "--prompt",
+ "p",
+ "--start-at",
+ "2026-09-08T09:00:00.000Z",
+ "--disabled",
+ ]),
+ ).toBe(0);
+ expect(lastRequest("POST", "/calendar")?.body).toMatchObject({ agentId: "hr", enabled: false });
+ });
+
+ it("update is read-modify-write, ls lists all or one employee's events, rm deletes", async () => {
+ await cli([
+ "org",
+ "calendar",
+ "add",
+ "standup",
+ "--prompt",
+ "original",
+ "--start-at",
+ "2026-09-08T09:00:00.000Z",
+ "--period",
+ "1d",
+ ]);
+ stdout.length = 0;
+ expect(
+ await cli(["org", "calendar", "update", "standup", "--period", "12h", "--disable"]),
+ ).toBe(0);
+ expect(lastRequest("PUT", "/calendar/dev1/standup")?.body).toEqual({
+ enabled: false,
+ prompt: "original",
+ startAt: "2026-09-08T09:00:00.000Z",
+ period: "12h",
+ });
+ expect(await cli(["org", "calendar", "update", "standup", "--enable", "--disable"])).toBe(1);
+
+ stdout.length = 0;
+ expect(await cli(["org", "calendar", "ls"])).toBe(0);
+ expect(out()).toContain("standup");
+ expect(out()).toContain(t.schedule.disabled());
+ stdout.length = 0;
+ expect(await cli(["org", "calendar", "ls", "--agent-id", "ceo"])).toBe(0);
+ expect(out()).toBe(`${t.org.calendarEmpty()}\n`);
+
+ expect(await cli(["org", "calendar", "rm", "standup"])).toBe(0);
+ expect(lastRequest("DELETE", "/calendar/dev1/standup")).toBeDefined();
+ expect(await cli(["org", "calendar", "rm", "standup"])).toBe(1);
+ expect(err()).toContain("calendar_event_not_found");
+ });
+});
+
+describe("penguin org ticket (writes carry the calling session)", () => {
+ beforeEach(() => {
+ server.addEmployee("acme", { agentId: "dev1", title: "Developer" });
+ // The CLI runs inside dev1's desk session: the control environment names it.
+ server.addSession({ sessionId: DESK_SESSION, agentId: "dev1" });
+ process.env.PENGUIN_SESSION_ID = DESK_SESSION;
+ process.env.PENGUIN_AGENT_ID = "dev1";
+ });
+
+ it("create posts goal, criteria, owner, parent, notify list, priority and due, attributed to the session", async () => {
+ server.addTicket("acme", { ticketId: "2026-09-01-plan", title: "Plan" });
+ expect(
+ await cli([
+ "org",
+ "ticket",
+ "create",
+ "--title",
+ "Build the site",
+ "--goal",
+ "A landing page",
+ "--criteria",
+ "It renders",
+ "--owner",
+ "agent:dev1",
+ "--parent",
+ "2026-09-01-plan",
+ "--notify",
+ "agent:ceo,user:admin",
+ "--priority",
+ "P0",
+ "--due",
+ "2026-09-10",
+ ]),
+ ).toBe(0);
+ expect(lastRequest("POST", "/tickets")?.body).toEqual({
+ title: "Build the site",
+ goal: "A landing page",
+ acceptanceCriteria: "It renders",
+ owner: "agent:dev1",
+ parent: "2026-09-01-plan",
+ notify: ["agent:ceo", "user:admin"],
+ priority: "P0",
+ due: "2026-09-10",
+ sessionId: DESK_SESSION,
+ agentId: "dev1",
+ });
+ expect(out()).toBe(`${t.org.ticketCreated("2026-09-02-build-the-site", "proposed")}\n`);
+ // The file records the session's employee, not the token's user; the owner it was filed
+ // for is the one it names, and filing for someone else is an `assigned` history entry.
+ expect(org().tickets.get("2026-09-02-build-the-site")).toMatchObject({
+ owner: "agent:dev1",
+ });
+ expect(
+ (org().tickets.get("2026-09-02-build-the-site")!.history as Array<{ by: string }>)[0],
+ ).toMatchObject({ by: "agent:dev1", action: "created" });
+ });
+
+ it("create names the ticket id's words with --slug when the title carries none", async () => {
+ expect(
+ await cli([
+ "org",
+ "ticket",
+ "create",
+ "--title",
+ "上线站点",
+ "--goal",
+ "把站点发出去",
+ "--slug",
+ "launch-the-site",
+ ]),
+ ).toBe(0);
+ expect(lastRequest("POST", "/tickets")?.body).toMatchObject({ slug: "launch-the-site" });
+ expect(org().tickets.has("2026-09-02-launch-the-site")).toBe(true);
+ });
+
+ it("create takes the whole body from --body-file; --goal with it, --criteria without it and a bad priority are refused", async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-org-test-"));
+ const file = path.join(dir, "ticket.md");
+ fs.writeFileSync(file, "## Goal\nFrom a file\n");
+ try {
+ expect(await cli(["org", "ticket", "create", "--title", "Docs", "--body-file", file])).toBe(
+ 0,
+ );
+ expect(lastRequest("POST", "/tickets")?.body).toMatchObject({
+ title: "Docs",
+ body: "## Goal\nFrom a file\n",
+ });
+ const create = ["org", "ticket", "create", "--title", "Docs"];
+ expect(await cli([...create, "--goal", "g", "--body-file", file])).toBe(1);
+ expect(await cli([...create, "--criteria", "c", "--body-file", file])).toBe(1);
+ expect(await cli([...create, "--goal", "g", "--priority", "P9"])).toBe(1);
+ expect(await cli([...create, "--body-file", path.join(dir, "missing.md")])).toBe(1);
+ expect(server.requests.filter((r) => r.method === "POST")).toHaveLength(1);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("move / assign / block / unblock / progress send their bodies with the caller's identity", async () => {
+ server.addTicket("acme", { ticketId: "2026-09-02-site", title: "Site", owner: "agent:dev1" });
+ expect(await cli(["org", "ticket", "move", "2026-09-02-site", "--to", "in_progress"])).toBe(0);
+ expect(lastRequest("POST", "/tickets/2026-09-02-site/move")?.body).toEqual({
+ status: "in_progress",
+ sessionId: DESK_SESSION,
+ agentId: "dev1",
+ });
+ expect(out()).toBe(`${t.org.ticketMoved("2026-09-02-site", "in_progress")}\n`);
+ expect(await cli(["org", "ticket", "move", "2026-09-02-site", "--to", "bogus"])).toBe(1);
+ expect(err()).toContain("bogus");
+ // Moving into rejected needs a reason: the server's rule, surfacing verbatim.
+ expect(await cli(["org", "ticket", "move", "2026-09-02-site", "--to", "rejected"])).toBe(1);
+ expect(err()).toContain("reason");
+
+ stdout.length = 0;
+ expect(await cli(["org", "ticket", "assign", "2026-09-02-site", "--owner", "agent:ceo"])).toBe(
+ 0,
+ );
+ expect(lastRequest("PUT", "/tickets/2026-09-02-site")?.body).toEqual({
+ owner: "agent:ceo",
+ sessionId: DESK_SESSION,
+ agentId: "dev1",
+ });
+ expect(out()).toBe(`${t.org.ticketAssigned("2026-09-02-site", "agent:ceo")}\n`);
+
+ stdout.length = 0;
+ expect(
+ await cli([
+ "org",
+ "ticket",
+ "block",
+ "2026-09-02-site",
+ "--reason",
+ "waiting for keys",
+ "--by",
+ "user:admin",
+ ]),
+ ).toBe(0);
+ expect(lastRequest("POST", "/tickets/2026-09-02-site/block")?.body).toEqual({
+ reason: "waiting for keys",
+ by: "user:admin",
+ sessionId: DESK_SESSION,
+ agentId: "dev1",
+ });
+ expect(out()).toBe(`${t.org.ticketBlocked("2026-09-02-site")}\n`);
+ expect(org().tickets.get("2026-09-02-site")).toMatchObject({
+ blocked: "waiting for keys",
+ blockedBy: "user:admin",
+ });
+
+ stdout.length = 0;
+ expect(await cli(["org", "ticket", "unblock", "2026-09-02-site"])).toBe(0);
+ expect(lastRequest("POST", "/tickets/2026-09-02-site/unblock")?.body).toEqual({
+ sessionId: DESK_SESSION,
+ agentId: "dev1",
+ });
+ expect(org().tickets.get("2026-09-02-site")!.blocked).toBeUndefined();
+ expect(out()).toBe(`${t.org.ticketUnblocked("2026-09-02-site")}\n`);
+
+ stdout.length = 0;
+ expect(await cli(["org", "ticket", "progress", "2026-09-02-site", "-m", "half done"])).toBe(0);
+ expect(lastRequest("POST", "/tickets/2026-09-02-site/progress")?.body).toEqual({
+ text: "half done",
+ sessionId: DESK_SESSION,
+ agentId: "dev1",
+ });
+ expect(out()).toBe(`${t.org.progressRecorded("2026-09-02-site")}\n`);
+ // The section is prose; who wrote it is the history entry beside it.
+ expect(org().tickets.get("2026-09-02-site")!.progress).toEqual(["half done"]);
+ expect(
+ (org().tickets.get("2026-09-02-site")!.history as Array<{ by: string }>).at(-1),
+ ).toMatchObject({ by: "agent:dev1", action: "progress", note: "half done" });
+ });
+
+ it("outside a session and outside an Agent the writes carry no identity", async () => {
+ delete process.env.PENGUIN_SESSION_ID;
+ delete process.env.PENGUIN_AGENT_ID;
+ server.addTicket("acme", { ticketId: "2026-09-02-site", title: "Site" });
+ expect(await cli(["org", "ticket", "progress", "2026-09-02-site", "-m", "note"])).toBe(0);
+ expect(lastRequest("POST", "/tickets/2026-09-02-site/progress")?.body).toEqual({
+ text: "note",
+ });
+ expect(await cli(["org", "ticket", "unblock", "2026-09-02-site"])).toBe(0);
+ expect(lastRequest("POST", "/tickets/2026-09-02-site/unblock")?.body).toEqual({});
+ });
+
+ it("start runs the ticket session as PENGUIN_AGENT_ID, carries the calling session, and prints the bare session id (--json: {sessionId})", async () => {
+ server.addTicket("acme", { ticketId: "2026-09-02-site", title: "Site", owner: "agent:ceo" });
+ expect(
+ await cli([
+ "org",
+ "ticket",
+ "start",
+ "2026-09-02-site",
+ "-m",
+ "start with the header",
+ "--workspace",
+ "site",
+ ]),
+ ).toBe(0);
+ // The calling session rides along: it is what tells the server which employee is asking,
+ // and only a ticket's owner may start its sessions.
+ expect(lastRequest("POST", "/tickets/2026-09-02-site/start")?.body).toEqual({
+ agentId: "dev1",
+ message: "start with the header",
+ workspace: "site",
+ sessionId: DESK_SESSION,
+ });
+ const sessions = org().tickets.get("2026-09-02-site")!.sessions as string[];
+ expect(sessions).toHaveLength(1);
+ expect(out()).toBe(`${sessions[0]}\n`);
+ expect(server.sessions.get(sessions[0]!)?.agentId).toBe("dev1");
+
+ // --agent-id wins over the environment: the owner enlisting a colleague on its own ticket.
+ stdout.length = 0;
+ expect(await cli(["org", "ticket", "start", "2026-09-02-site", "--agent-id", "ceo"])).toBe(0);
+ expect(lastRequest("POST", "/tickets/2026-09-02-site/start")?.body).toEqual({
+ agentId: "ceo",
+ sessionId: DESK_SESSION,
+ });
+
+ // Outside a session the body names neither employee nor session: the server picks the owner.
+ delete process.env.PENGUIN_AGENT_ID;
+ delete process.env.PENGUIN_SESSION_ID;
+ stdout.length = 0;
+ expect(await cli(["org", "ticket", "start", "2026-09-02-site", "--json"])).toBe(0);
+ expect(lastRequest("POST", "/tickets/2026-09-02-site/start")?.body).toEqual({});
+ expect(sessions).toHaveLength(3);
+ expect(JSON.parse(out())).toEqual({ sessionId: sessions[2] });
+ expect(server.sessions.get(sessions[2]!)?.agentId).toBe("ceo");
+ });
+
+ it("attach defaults to the calling session, resolves a fragment, and needs one of the two", async () => {
+ server.addTicket("acme", { ticketId: "2026-09-02-site", title: "Site" });
+ expect(await cli(["org", "ticket", "attach", "2026-09-02-site"])).toBe(0);
+ // `sessionId` is the Session to attach; the Agent id is what says who attached it.
+ expect(lastRequest("POST", "/tickets/2026-09-02-site/attach")?.body).toEqual({
+ sessionId: DESK_SESSION,
+ agentId: "dev1",
+ });
+ expect(out()).toBe(`${t.org.ticketAttached("2026-09-02-site", DESK_SESSION)}\n`);
+
+ server.addSession({ sessionId: "session-2026-09-02-10-00-00-abcd0002", agentId: "dev1" });
+ expect(await cli(["org", "ticket", "attach", "2026-09-02-site", "--session", "abcd0002"])).toBe(
+ 0,
+ );
+ expect(lastRequest("POST", "/tickets/2026-09-02-site/attach")?.body).toEqual({
+ sessionId: "session-2026-09-02-10-00-00-abcd0002",
+ agentId: "dev1",
+ });
+ expect(org().tickets.get("2026-09-02-site")!.sessions).toEqual([
+ DESK_SESSION,
+ "session-2026-09-02-10-00-00-abcd0002",
+ ]);
+
+ delete process.env.PENGUIN_SESSION_ID;
+ expect(await cli(["org", "ticket", "attach", "2026-09-02-site"])).toBe(1);
+ expect(err()).toContain("--session");
+ });
+
+ it("ls filters locally by column, owner and blocked state; show prints fields, prose and history", async () => {
+ server.addTicket("acme", {
+ ticketId: "2026-09-02-site",
+ title: "Site",
+ status: "in_progress",
+ owner: "agent:dev1",
+ priority: "P0",
+ sessions: [DESK_SESSION],
+ history: [{ at: "2026-09-02T10:00:00Z", by: "agent:dev1", action: "created" }],
+ progress: ["scaffolded the site"],
+ running: true,
+ cost: 0.12,
+ rolledUpCost: 0.3,
+ });
+ server.addTicket("acme", {
+ ticketId: "2026-09-02-docs",
+ title: "Docs",
+ owner: "agent:ceo",
+ blocked: "waiting",
+ blockedBy: "user:admin",
+ });
+ server.addTicket("acme", { ticketId: "2026-09-01-old", title: "Old", status: "done" });
+ expect(await cli(["org", "ticket", "ls"])).toBe(0);
+ let text = out();
+ expect(text).toContain("2026-09-02-site");
+ expect(text).toContain("2026-09-02-docs");
+ expect(text).toContain("2026-09-01-old");
+ expect(text).toContain("blocked");
+
+ stdout.length = 0;
+ expect(await cli(["org", "ticket", "ls", "--status", "in_progress"])).toBe(0);
+ text = out();
+ expect(text).toContain("2026-09-02-site");
+ expect(text).not.toContain("2026-09-02-docs");
+
+ stdout.length = 0;
+ expect(await cli(["org", "ticket", "ls", "--blocked", "--json"])).toBe(0);
+ const parsed = JSON.parse(out()) as { tickets: Array<{ ticketId: string }> };
+ expect(parsed.tickets.map((x) => x.ticketId)).toEqual(["2026-09-02-docs"]);
+
+ stdout.length = 0;
+ expect(await cli(["org", "ticket", "ls", "--owner", "agent:ceo", "--status", "done"])).toBe(0);
+ expect(out()).toBe(`${t.org.ticketsEmpty()}\n`);
+ expect(await cli(["org", "ticket", "ls", "--status", "bogus"])).toBe(1);
+
+ stdout.length = 0;
+ expect(await cli(["org", "ticket", "show", "2026-09-02-site"])).toBe(0);
+ text = out();
+ expect(text).toContain(t.org.ticketHead("2026-09-02-site", "in_progress", true, undefined));
+ expect(text).toContain(t.org.ticketFigures("$0.1200", "$0.3000", 1, 0));
+ expect(text).toContain(`${t.org.ticketFields().title}: Site`);
+ expect(text).toContain(`${t.org.ticketFields().owner}: agent:dev1`);
+ expect(text).toContain("## Progress\n- scaffolded the site");
+ expect(text).toContain(`${t.org.ticketHistory()}\n2026-09-02T10:00:00Z agent:dev1 created`);
+
+ stdout.length = 0;
+ expect(await cli(["org", "ticket", "show", "2026-09-02-site", "--json"])).toBe(0);
+ expect(JSON.parse(out())).toMatchObject({
+ ticketId: "2026-09-02-site",
+ running: true,
+ body: expect.stringContaining("---\ntitle: Site") as string,
+ });
+ expect(await cli(["org", "ticket", "show", "2026-09-02-nope"])).toBe(1);
+ expect(err()).toContain("ticket_not_found");
+ });
+});
+
+describe("penguin org handbook", () => {
+ it("list prints the files with the index first; show prints the index or a document", async () => {
+ org().handbook.set("decisions/2026-09-02-hire-plan.md", "# Hire plan\n");
+ expect(await cli(["org", "handbook", "list"])).toBe(0);
+ const lines = out().trimEnd().split("\n");
+ expect(lines[0]).toMatch(/^README\.md\t/);
+ expect(lines[1]).toMatch(/^decisions\/2026-09-02-hire-plan\.md\t/);
+
+ stdout.length = 0;
+ expect(await cli(["org", "handbook", "show"])).toBe(0);
+ expect(out()).toBe("# Acme — organization handbook\n");
+
+ stdout.length = 0;
+ expect(await cli(["org", "handbook", "show", "decisions/2026-09-02-hire-plan.md"])).toBe(0);
+ expect(out()).toBe("# Hire plan\n");
+ expect(lastRequest("GET", "/handbook/files/decisions/2026-09-02-hire-plan.md")).toBeTruthy();
+
+ stdout.length = 0;
+ expect(await cli(["org", "handbook", "show", "missing.md"])).toBe(1);
+ expect(err()).toContain("missing.md is not in the handbook.");
+ });
+
+ it("write takes exactly one of -m or --file; rm deletes a document and refuses the index", async () => {
+ expect(await cli(["org", "handbook", "write", "conventions.md"])).toBe(1);
+ expect(err()).toContain(t.org.handbookOneSource);
+
+ expect(await cli(["org", "handbook", "write", "conventions.md", "-m", "# Conventions"])).toBe(
+ 0,
+ );
+ expect(org().handbook.get("conventions.md")).toBe("# Conventions");
+ expect(out()).toBe(`${t.org.handbookWritten("conventions.md")}\n`);
+ expect(lastRequest("PUT", "/handbook/files/conventions.md")?.body).toEqual({
+ content: "# Conventions",
+ });
+
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-handbook-"));
+ const file = path.join(dir, "guide.md");
+ fs.writeFileSync(file, "# Guide\n");
+ stdout.length = 0;
+ expect(await cli(["org", "handbook", "write", "roles/dev.md", "--file", file])).toBe(0);
+ expect(org().handbook.get("roles/dev.md")).toBe("# Guide\n");
+ fs.rmSync(dir, { recursive: true, force: true });
+
+ stdout.length = 0;
+ expect(await cli(["org", "handbook", "rm", "conventions.md"])).toBe(0);
+ expect(org().handbook.has("conventions.md")).toBe(false);
+ expect(out()).toBe(`${t.org.handbookRemoved("conventions.md")}\n`);
+
+ expect(await cli(["org", "handbook", "rm", "README.md"])).toBe(1);
+ expect(err()).toContain("cannot be deleted");
+ });
+
+ // A `.` / `..` segment survives encodeURIComponent and the URL parser collapses it, so an
+ // unchecked path leaves the handbook route entirely: `handbook/files/../../../victim` is
+ // the organization `victim`, and `employees/..` is the organization itself.
+ it("refuses a dot segment in a handbook path or an employee id before any request", async () => {
+ server.addOrg({ orgId: "victim", name: "Victim", mission: "Stay alive" });
+ server.requests.length = 0;
+
+ expect(await cli(["org", "handbook", "rm", "../../../victim"])).toBe(1);
+ expect(err()).toContain(t.org.pathSegmentInvalid("../../../victim"));
+ expect(server.orgs.has("victim")).toBe(true);
+
+ expect(await cli(["org", "handbook", "show", ".."])).toBe(1);
+ expect(await cli(["org", "handbook", "write", "../x.md", "-m", "x"])).toBe(1);
+ expect(await cli(["org", "leave", ".."])).toBe(1);
+ expect(await cli(["org", "employee", "set", "..", "--title", "CEO"])).toBe(1);
+ // `channels/site/members/../../..` is the organization too, so the channel arguments
+ // that reach a path are guarded the same way.
+ expect(await cli(["org", "channel", "show", ".."])).toBe(1);
+ expect(await cli(["org", "channel", "remove", "site", "../../.."])).toBe(1);
+ expect(await cli(["org", "channel", "tail", "--channel", ".."])).toBe(1);
+ expect(server.orgs.has("acme")).toBe(true);
+ expect(server.requests).toEqual([]);
+ });
+});
+
+describe("penguin org channel", () => {
+ /** The all-hands channel, created with every organization and the default of `--channel`. */
+ const DEFAULT = "default_channel";
+ /** The desk session's employee, set up by the tests that run inside a session. */
+ const employeeInSession = (agentId: string) => {
+ server.addEmployee("acme", { agentId });
+ server.addSession({ sessionId: DESK_SESSION, agentId });
+ process.env.PENGUIN_SESSION_ID = DESK_SESSION;
+ };
+
+ it("ls lists the channels — the all-hands label, member counts, unread and @me; --json passes the response", async () => {
+ server.addEmployee("acme", { agentId: "dev1" });
+ const site = server.addChannel("acme", "site", {
+ name: "Site launch",
+ members: ["user:admin", "agent:dev1"],
+ });
+ site.unread = 3;
+ site.mentionsMe = 1;
+ server.addChannel("acme", "marketing", { name: "Marketing", archived: true });
+ expect(await cli(["org", "channel", "ls"])).toBe(0);
+ const lines = out().trimEnd().split("\n");
+ // The all-hands channel comes first and under its label, never its stored name.
+ expect(lines[1]).toMatch(/^default_channel\s+All hands\s+3\s/);
+ expect(lines[1]).not.toContain("All hands (");
+ const row = (id: string) => lines.find((l) => l.startsWith(`${id} `))!;
+ expect(row("site")).toContain("Site launch");
+ expect(row("site")).toMatch(/\s3\s+1$/);
+ expect(row("marketing")).toContain("archived");
+
+ stdout.length = 0;
+ expect(await cli(["org", "channel", "ls", "--json"])).toBe(0);
+ const parsed = JSON.parse(out()) as { channels: Array<{ channelId: string }> };
+ // default_channel first, then by name: Marketing before Site launch.
+ expect(parsed.channels.map((c) => c.channelId)).toEqual([DEFAULT, "marketing", "site"]);
+ });
+
+ it("an employee sees only its own channels, and the read says which employee is asking", async () => {
+ employeeInSession("dev1");
+ server.addChannel("acme", "site", { members: ["agent:dev1"] });
+ server.addChannel("acme", "marketing", { members: ["user:admin"] });
+ expect(await cli(["org", "channel", "ls", "--json"])).toBe(0);
+ const parsed = JSON.parse(out()) as { channels: Array<{ channelId: string }> };
+ expect(parsed.channels.map((c) => c.channelId)).toEqual([DEFAULT, "site"]);
+ // The read has no body, so the identity rides the query; without it the server would
+ // answer the employee as the signed-in person and list every channel.
+ expect(lastRequest("GET", "/channels")?.search).toBe(`?sessionId=${DESK_SESSION}`);
+
+ delete process.env.PENGUIN_SESSION_ID;
+ stdout.length = 0;
+ expect(await cli(["org", "channel", "ls", "--json"])).toBe(0);
+ const asPerson = JSON.parse(out()) as { channels: Array<{ channelId: string }> };
+ expect(asPerson.channels.map((c) => c.channelId)).toEqual([DEFAULT, "marketing", "site"]);
+ expect(lastRequest("GET", "/channels")?.search).toBe("");
+ });
+
+ it("create opens a channel holding only its creator; show prints it with its members", async () => {
+ expect(
+ await cli([
+ "org",
+ "channel",
+ "create",
+ "site",
+ "--name",
+ "Site launch",
+ "--purpose",
+ "Ship the site",
+ ]),
+ ).toBe(0);
+ expect(lastRequest("POST", "/channels")?.body).toEqual({
+ channelId: "site",
+ name: "Site launch",
+ purpose: "Ship the site",
+ });
+ expect(out()).toBe(`${t.org.channelCreated("site")}\n`);
+ const site = org().channels.get("site")!;
+ expect(site.members).toEqual(["user:admin"]);
+ // Creation leaves its own system line in the new channel.
+ expect(site.messages.map((m) => m.text)).toEqual(["user:admin created the channel."]);
+
+ stdout.length = 0;
+ expect(await cli(["org", "channel", "show", "site"])).toBe(0);
+ const text = out();
+ expect(text).toContain(t.org.channelHead("Site launch", "site", 1, false));
+ expect(text).toContain(t.org.channelPurposeLine("Ship the site"));
+ expect(text).toContain(t.org.channelCreatedBy("user:admin", site.createdAt));
+ expect(text).toContain("user:admin");
+
+ // The all-hands channel is shown under its label and holds everybody.
+ stdout.length = 0;
+ expect(await cli(["org", "channel", "show", DEFAULT])).toBe(0);
+ expect(out()).toContain(t.org.channelHead(t.org.allHands(), DEFAULT, 2, false));
+ expect(out()).toContain("agent:ceo");
+
+ // A taken id is the server's 409, verbatim.
+ expect(await cli(["org", "channel", "create", "site"])).toBe(1);
+ expect(err()).toContain("channel_exists");
+ });
+
+ it("create inside a session makes an agent-owned channel", async () => {
+ employeeInSession("dev1");
+ expect(await cli(["org", "channel", "create", "site", "--json"])).toBe(0);
+ expect(lastRequest("POST", "/channels")?.body).toEqual({
+ channelId: "site",
+ sessionId: DESK_SESSION,
+ });
+ expect(JSON.parse(out())).toMatchObject({ channelId: "site", createdBy: "agent:dev1" });
+ expect(org().channels.get("site")!.members).toEqual(["agent:dev1"]);
+ });
+
+ it("invite posts one principal at a time and prints each; a stranger is refused", async () => {
+ server.addEmployee("acme", { agentId: "dev1" });
+ server.addEmployee("acme", { agentId: "hr" });
+ server.addChannel("acme", "site", { members: ["user:admin"] });
+ expect(await cli(["org", "channel", "invite", "site", "agent:dev1", "agent:hr"])).toBe(0);
+ expect(
+ server.requests.filter(
+ (r) => r.method === "POST" && r.path.endsWith("/channels/site/members"),
+ ),
+ ).toHaveLength(2);
+ expect(out()).toBe(
+ `${t.org.channelInvited("site", "agent:dev1")}\n${t.org.channelInvited("site", "agent:hr")}\n`,
+ );
+ expect(org().channels.get("site")!.members).toEqual(["user:admin", "agent:dev1", "agent:hr"]);
+
+ // Only an employee or a Project member can be in a channel.
+ expect(await cli(["org", "channel", "invite", "site", "agent:nobody"])).toBe(1);
+ expect(err()).toContain("invalid_principal");
+ // The all-hands channel already holds everyone.
+ expect(await cli(["org", "channel", "invite", DEFAULT, "agent:dev1"])).toBe(1);
+ expect(err()).toContain("all_hands_immutable");
+ });
+
+ it("join adds the person itself; the principal is always the caller's own", async () => {
+ server.addChannel("acme", "site", { members: ["agent:ceo"], createdBy: "agent:ceo" });
+ expect(await cli(["org", "channel", "join", "site"])).toBe(0);
+ // Outside a session the caller is the signed-in person, whom only the server knows.
+ expect(lastRequest("GET", "/api/me")).toBeDefined();
+ expect(lastRequest("POST", "/channels/site/members")?.body).toEqual({
+ principal: "user:admin",
+ });
+ expect(org().channels.get("site")!.members).toEqual(["agent:ceo", "user:admin"]);
+ expect(out()).toBe(`${t.org.channelJoined("site")}\n`);
+ });
+
+ it("an employee's join asks for itself and is refused, whether or not it is already in", async () => {
+ employeeInSession("dev1");
+ server.addChannel("acme", "marketing", { members: ["agent:ceo"] });
+ expect(await cli(["org", "channel", "join", "marketing"])).toBe(1);
+ // The body names the employee, never the token's user: joining can never invite someone else.
+ expect(lastRequest("POST", "/channels/marketing/members")?.body).toEqual({
+ principal: "agent:dev1",
+ sessionId: DESK_SESSION,
+ });
+ expect(err()).toContain("An employee joins a channel only when a member invites it.");
+ expect(org().channels.get("marketing")!.members).toEqual(["agent:ceo"]);
+
+ // Already a member changes nothing: an employee is still refused, and the person the
+ // token belongs to is not dragged into the channel behind its back.
+ server.addChannel("acme", "site", { members: ["agent:dev1"] });
+ expect(await cli(["org", "channel", "join", "site"])).toBe(1);
+ expect(err()).toContain("An employee joins a channel only when a member invites it.");
+ expect(org().channels.get("site")!.members).toEqual(["agent:dev1"]);
+ });
+
+ it("leave removes the caller's own principal: the employee's in a session, the person's outside one", async () => {
+ employeeInSession("dev1");
+ server.addChannel("acme", "site", { members: ["user:admin", "agent:dev1"] });
+ expect(await cli(["org", "channel", "leave", "site"])).toBe(0);
+ const asEmployee = lastRequest("DELETE", `/members/${encodeURIComponent("agent:dev1")}`);
+ expect(asEmployee?.search).toBe(`?sessionId=${DESK_SESSION}`);
+ expect(org().channels.get("site")!.members).toEqual(["user:admin"]);
+ expect(out()).toBe(`${t.org.channelLeft("site")}\n`);
+
+ delete process.env.PENGUIN_SESSION_ID;
+ stdout.length = 0;
+ expect(await cli(["org", "channel", "leave", "site"])).toBe(0);
+ expect(lastRequest("DELETE", `/members/${encodeURIComponent("user:admin")}`)?.search).toBe("");
+ expect(org().channels.get("site")!.members).toEqual([]);
+
+ // Nobody leaves the all-hands channel.
+ expect(await cli(["org", "channel", "leave", DEFAULT])).toBe(1);
+ expect(err()).toContain("all_hands_immutable");
+ });
+
+ it("remove takes another member out; an employee may only remove itself", async () => {
+ server.addEmployee("acme", { agentId: "dev1" });
+ server.addSession({ sessionId: DESK_SESSION, agentId: "dev1" });
+ server.addChannel("acme", "site", { members: ["user:admin", "agent:dev1"] });
+ expect(await cli(["org", "channel", "remove", "site", "agent:dev1"])).toBe(0);
+ expect(out()).toBe(`${t.org.channelMemberRemoved("site", "agent:dev1")}\n`);
+ expect(org().channels.get("site")!.members).toEqual(["user:admin"]);
+
+ server.addChannel("acme", "marketing", { members: ["user:admin", "agent:dev1"] });
+ process.env.PENGUIN_SESSION_ID = DESK_SESSION;
+ expect(await cli(["org", "channel", "remove", "marketing", "user:admin"])).toBe(1);
+ expect(err()).toContain("An employee removes only itself from a channel.");
+ expect(org().channels.get("marketing")!.members).toEqual(["user:admin", "agent:dev1"]);
+ });
+
+ it("archive makes a channel read-only, unarchive lifts it; the all-hands channel and employees are refused", async () => {
+ server.addChannel("acme", "site", { members: ["user:admin"] });
+ expect(await cli(["org", "channel", "archive", "site"])).toBe(0);
+ expect(lastRequest("PATCH", "/channels/site")?.body).toEqual({ archived: true });
+ expect(org().channels.get("site")!.archived).toBe(true);
+ expect(out()).toBe(`${t.org.channelArchived("site")}\n`);
+
+ // An archived channel takes no messages until it is unarchived.
+ expect(await cli(["org", "channel", "send", "--channel", "site", "-m", "hello"])).toBe(1);
+ expect(err()).toContain("channel_archived");
+
+ stdout.length = 0;
+ expect(await cli(["org", "channel", "unarchive", "site"])).toBe(0);
+ expect(lastRequest("PATCH", "/channels/site")?.body).toEqual({ archived: false });
+ expect(org().channels.get("site")!.archived).toBe(false);
+ expect(out()).toBe(`${t.org.channelUnarchived("site")}\n`);
+
+ expect(await cli(["org", "channel", "archive", DEFAULT])).toBe(1);
+ expect(err()).toContain("all_hands_immutable");
+
+ employeeInSession("dev1");
+ expect(await cli(["org", "channel", "archive", "site"])).toBe(1);
+ expect(err()).toContain("Only people archive a channel.");
+ });
+
+ it("tail prints the day's last messages as `time sender text`; -n limits, --date picks the day, --json carries it", async () => {
+ for (let i = 1; i <= 3; i++) {
+ server.addMessage("acme", {
+ sender: "agent:ceo",
+ text: `message ${i}`,
+ time: `2026-09-02T10:0${i}:00.000Z`,
+ });
+ }
+ server.addMessage("acme", {
+ sender: "user:admin",
+ text: "yesterday",
+ time: "2026-09-01T09:00:00.000Z",
+ });
+ expect(await cli(["org", "channel", "tail"])).toBe(0);
+ expect(out()).toBe(
+ [
+ "2026-09-02T10:01:00.000Z agent:ceo message 1",
+ "2026-09-02T10:02:00.000Z agent:ceo message 2",
+ "2026-09-02T10:03:00.000Z agent:ceo message 3",
+ "",
+ ].join("\n"),
+ );
+
+ stdout.length = 0;
+ expect(await cli(["org", "channel", "tail", "-n", "1"])).toBe(0);
+ expect(out()).toBe("2026-09-02T10:03:00.000Z agent:ceo message 3\n");
+
+ stdout.length = 0;
+ expect(await cli(["org", "channel", "tail", "--date", "2026-09-01", "--json"])).toBe(0);
+ const parsed = JSON.parse(out()) as {
+ channelId: string;
+ date: string;
+ messages: Array<{ text: string }>;
+ };
+ expect(parsed.channelId).toBe(DEFAULT);
+ expect(parsed.date).toBe("2026-09-01");
+ expect(parsed.messages.map((m) => m.text)).toEqual(["yesterday"]);
+
+ expect(await cli(["org", "channel", "tail", "-n", "0"])).toBe(1);
+ stdout.length = 0;
+ expect(await cli(["org", "channel", "tail", "--date", "2026-08-01"])).toBe(0);
+ expect(out()).toBe(`${t.org.channelEmpty(DEFAULT, "2026-08-01")}\n`);
+ });
+
+ it("tail reads the channel --channel names and names it above the messages; the default one says nothing", async () => {
+ server.addChannel("acme", "site", { members: ["user:admin"] });
+ server.addMessage("acme", { sender: "user:admin", text: "kickoff" }, "site");
+ server.addMessage("acme", { sender: "user:admin", text: "all hands" });
+ expect(await cli(["org", "channel", "tail", "--channel", "site"])).toBe(0);
+ expect(out()).toContain(t.org.channelHeader("site"));
+ expect(out()).toContain("2026-09-02T10:00:00.000Z user:admin kickoff");
+ expect(out()).not.toContain("all hands");
+
+ stdout.length = 0;
+ expect(await cli(["org", "channel", "tail"])).toBe(0);
+ expect(out()).toBe("2026-09-02T10:00:00.000Z user:admin all hands\n");
+
+ // The empty line names the channel it read.
+ stdout.length = 0;
+ server.addChannel("acme", "quiet", { members: ["user:admin"] });
+ expect(await cli(["org", "channel", "tail", "--channel", "quiet"])).toBe(0);
+ expect(out()).toBe(`${t.org.channelEmpty("quiet", "2026-09-02")}\n`);
+ });
+
+ it("renders a system line from its structured notice, and falls back to the text", async () => {
+ server.addMessage("acme", {
+ sender: "system",
+ text: "agent:acme_hr joined as HR, reporting to agent:acme_ceo.",
+ notice: {
+ kind: "employee_joined",
+ params: { agent: "agent:acme_hr", title: "HR", reportsTo: "agent:acme_ceo" },
+ },
+ time: "2026-09-02T10:01:00.000Z",
+ });
+ // A kind this build does not know, and a line from before the field existed.
+ server.addMessage("acme", {
+ sender: "system",
+ text: "The office moved to Berlin.",
+ notice: { kind: "office_moved", params: { to: "Berlin" } },
+ time: "2026-09-02T10:02:00.000Z",
+ });
+ server.addMessage("acme", {
+ sender: "system",
+ text: "Something old.",
+ time: "2026-09-02T10:03:00.000Z",
+ });
+ expect(await cli(["org", "channel", "tail"])).toBe(0);
+ expect(out()).toBe(
+ [
+ `2026-09-02T10:01:00.000Z system ${t.org.notices.employee_joined({
+ agent: "agent:acme_hr",
+ title: "HR",
+ reportsTo: "agent:acme_ceo",
+ })}`,
+ "2026-09-02T10:02:00.000Z system The office moved to Berlin.",
+ "2026-09-02T10:03:00.000Z system Something old.",
+ "",
+ ].join("\n"),
+ );
+ });
+
+ it("send posts the text with refs and the calling session; --channel picks the channel", async () => {
+ employeeInSession("dev1");
+ expect(
+ await cli([
+ "org",
+ "channel",
+ "send",
+ "-m",
+ "@agent:ceo the site is up",
+ "--ref-ticket",
+ "2026-09-02-site",
+ ]),
+ ).toBe(0);
+ expect(lastRequest("POST", `/channels/${DEFAULT}/messages`)?.body).toEqual({
+ text: "@agent:ceo the site is up",
+ refs: { ticket: "2026-09-02-site" },
+ sessionId: DESK_SESSION,
+ });
+ const msg = org().channels.get(DEFAULT)!.messages[0]!;
+ expect(msg).toMatchObject({ sender: "agent:dev1", mentions: ["agent:ceo"] });
+ expect(out()).toBe(`${t.org.messageSent(String(msg.id))}\n`);
+
+ server.addChannel("acme", "site", { members: ["agent:dev1", "agent:ceo"] });
+ stdout.length = 0;
+ expect(
+ await cli(["org", "channel", "send", "--channel", "site", "-m", "@agent:ceo look"]),
+ ).toBe(0);
+ expect(lastRequest("POST", "/channels/site/messages")?.body).toEqual({
+ text: "@agent:ceo look",
+ sessionId: DESK_SESSION,
+ });
+ expect(org().channels.get("site")!.messages).toHaveLength(1);
+ expect(org().channels.get(DEFAULT)!.messages).toHaveLength(1);
+
+ delete process.env.PENGUIN_SESSION_ID;
+ expect(await cli(["org", "channel", "send", "-m", "plain"])).toBe(0);
+ expect(lastRequest("POST", `/channels/${DEFAULT}/messages`)?.body).toEqual({ text: "plain" });
+ });
+
+ it("the server's refusals surface verbatim: a mention outside the membership, a channel the caller is not in, an id no channel carries", async () => {
+ server.addEmployee("acme", { agentId: "dev1" });
+ server.addSession({ sessionId: DESK_SESSION, agentId: "dev1" });
+ server.addChannel("acme", "site", { members: ["user:admin"] });
+
+ // A message naming a non-member is refused before anything is written.
+ expect(
+ await cli(["org", "channel", "send", "--channel", "site", "-m", "@agent:dev1 look"]),
+ ).toBe(1);
+ expect(err()).toContain("mention_not_member");
+ expect(org().channels.get("site")!.messages).toEqual([]);
+
+ // An employee reads and posts only in the channels it belongs to.
+ process.env.PENGUIN_SESSION_ID = DESK_SESSION;
+ expect(await cli(["org", "channel", "tail", "--channel", "site"])).toBe(1);
+ expect(err()).toContain("not_a_member");
+ expect(await cli(["org", "channel", "show", "site"])).toBe(1);
+ expect(err()).toContain("not_a_member");
+ expect(await cli(["org", "channel", "send", "--channel", "site", "-m", "hi"])).toBe(1);
+ expect(err()).toContain("not_a_member");
+ delete process.env.PENGUIN_SESSION_ID;
+
+ // An unknown channel is a 404, and so is an id no channel could carry.
+ expect(await cli(["org", "channel", "show", "nope"])).toBe(1);
+ expect(err()).toContain("channel_not_found");
+ expect(await cli(["org", "channel", "tail", "--channel", "Bad-Id"])).toBe(1);
+ expect(err()).toContain("channel_not_found");
+
+ // A malformed id in a body is the create route's bad_request; the CLI adds no rule of its own.
+ expect(await cli(["org", "channel", "create", "Bad-Id"])).toBe(1);
+ expect(err()).toContain("Invalid channel id");
+ });
+});
+
+describe("penguin org finance", () => {
+ it("renders employees along the tree, tickets and the total; unpriced usage is noted on stderr", async () => {
+ org().employees[0]!.spend = { own: 1, cumulative: 6 };
+ server.addEmployee("acme", {
+ agentId: "dev1",
+ title: "Developer",
+ budget: 20,
+ spend: { own: 5, cumulative: 5, ratio: 0.25 },
+ });
+ server.addTicket("acme", {
+ ticketId: "2026-09-02-site",
+ title: "Site",
+ status: "in_progress",
+ cost: 4,
+ rolledUpCost: 4,
+ });
+ org().unpriced = true;
+ expect(await cli(["org", "finance"])).toBe(0);
+ const text = out();
+ expect(text).toContain(" dev1");
+ expect(text).toContain("$5.0000");
+ expect(text).toContain("$20.00 (25%)");
+ expect(text).toContain("2026-09-02-site");
+ expect(text).toContain(t.org.financeTotal("2026-09", "$6.0000"));
+ expect(err()).toContain(t.org.unpriced());
+
+ stdout.length = 0;
+ stderr.length = 0;
+ expect(await cli(["org", "finance", "--period", "2026-08", "--json"])).toBe(0);
+ expect(JSON.parse(out())).toMatchObject({ period: "2026-08", currency: "USD", unpriced: true });
+ expect(err()).toBe("");
+
+ expect(await cli(["org", "finance", "--period", "bogus"])).toBe(1);
+ expect(err()).toContain("period must be yyyy-mm");
+ });
+});
+
+describe("--org-id resolution", () => {
+ it("defaults to PENGUIN_ORG_ID; with neither, the command fails before any request", async () => {
+ delete process.env.PENGUIN_ORG_ID;
+ expect(await cli(["org", "show"])).toBe(1);
+ expect(err()).toContain("PENGUIN_ORG_ID");
+ expect(server.requests).toHaveLength(0);
+
+ expect(await cli(["org", "show", "--org-id", "acme"])).toBe(0);
+ expect(lastRequest("GET", "/organizations/acme")).toBeDefined();
+
+ // An unknown organization is the server's 404, verbatim.
+ expect(await cli(["org", "show", "--org-id", "nope"])).toBe(1);
+ expect(err()).toContain("org_not_found");
+ });
+});
diff --git a/packages/core/package.json b/packages/core/package.json
index 880ee5e8..a83d5ec9 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -57,6 +57,7 @@
},
"dependencies": {
"@modelcontextprotocol/client": "^2.0.0",
+ "@penguinharness/agent-company": "workspace:*",
"@penguinharness/agent-development": "workspace:*",
"@penguinharness/agent-tuning": "workspace:*",
"@penguinharness/continual-learning": "workspace:*",
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 16a03d5a..4c16393f 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -73,7 +73,10 @@ export { modelVisiblePath } from "./internal/model-visible-path.js";
// same way.
export { atomicWriteFile } from "./internal/atomic-write.js";
export type { AtomicWriteOptions } from "./internal/atomic-write.js";
-export { Agent, createAgent } from "./agent.js";
+// `metaMaxTokens` is the output cap every out-of-band meta request shares — a small budget,
+// tightened by the entry's pinned per-model cap. Exported so a host running its own one-off
+// requests on a Project's model sizes them the way the SDK sizes its own.
+export { Agent, createAgent, metaMaxTokens } from "./agent.js";
export type {
ControlEnvContext,
CreateAgentOptions,
diff --git a/packages/core/src/omnimessage/markers/origin-blocks.ts b/packages/core/src/omnimessage/markers/origin-blocks.ts
index 6f561267..6d3a7612 100644
--- a/packages/core/src/omnimessage/markers/origin-blocks.ts
+++ b/packages/core/src/omnimessage/markers/origin-blocks.ts
@@ -214,6 +214,123 @@ export function parseScheduledMessage(
return { origin, rest: text.slice(m[0].length).replace(/^\n+/, "") };
}
+// ---------------------------------------------------------------------------
+// [org_trigger] — a work run or ticket session opened by the company-mode scheduler
+// ---------------------------------------------------------------------------
+
+/** What kind of organization trigger a message carries. */
+export type OrgTriggerKind = "init" | "event" | "mention" | "ticket_notice" | "ticket_work";
+
+/**
+ * Origin info for an organization trigger: the organization, the employee it addresses
+ * (with its title and reporting line for the model's orientation), the trigger kind and the
+ * kind-specific facts. Every field but `org`, `employee` and `kind` is optional so one shape
+ * serves all five kinds; the body after the block is the trigger's content (a calendar
+ * prompt, the quoted chat, a ticket excerpt or the whole ticket).
+ */
+export interface OrgTriggerOrigin {
+ org: string;
+ /** `<agent_id>` or `<agent_id> (<title>, reports to <agent_id>)`. */
+ employee: string;
+ kind: OrgTriggerKind;
+ /** kind=event: the calendar event name. */
+ event?: string;
+ /** kind=event: the fire time (ISO 8601). */
+ firedAt?: string;
+ /** kind=mention: `<message id> from <principal>`. */
+ message?: string;
+ /** kind=mention: the channel the message was posted in, and the one to answer in. */
+ channel?: string;
+ /** kind=ticket_notice / ticket_work: the ticket id. */
+ ticket?: string;
+ /** kind=ticket_notice: assigned | blocked | blocker_closed | done | rejected. */
+ change?: string;
+ /** Cumulative spend against the employee's budget for the period, as the scheduler formatted it. */
+ budget?: string;
+}
+
+const ORG_TRIGGER_KEYS = [
+ "org",
+ "employee",
+ "kind",
+ "event",
+ "fired_at",
+ "message",
+ "channel",
+ "ticket",
+ "change",
+ "budget",
+] as const;
+
+/**
+ * Trigger input = an `[org_trigger]` origin block + the trigger body: tells the model the
+ * organization scheduler sent this and which handbook to read first; the frontend collapses
+ * the block into a one-line trigger hint (Trace shows it verbatim). `<app_data_dir>` is a
+ * PRN-020 placeholder the model resolves from its Environment section, never an absolute path.
+ */
+export function buildOrgTriggerMessage(origin: OrgTriggerOrigin, body: string): string {
+ const lines = [
+ `This message was sent automatically by the organization scheduler. Read the organization handbook at <app_data_dir>/organizations/${origin.org}/handbook/README.md before acting, then follow its procedures; the trigger's details are listed below and its content follows.`,
+ `org: ${origin.org}`,
+ `employee: ${origin.employee}`,
+ `kind: ${origin.kind}`,
+ ];
+ if (origin.event !== undefined) lines.push(`event: ${origin.event}`);
+ if (origin.firedAt !== undefined) lines.push(`fired_at: ${origin.firedAt}`);
+ if (origin.message !== undefined) lines.push(`message: ${origin.message}`);
+ if (origin.channel !== undefined) lines.push(`channel: ${origin.channel}`);
+ if (origin.ticket !== undefined) lines.push(`ticket: ${origin.ticket}`);
+ if (origin.change !== undefined) lines.push(`change: ${origin.change}`);
+ if (origin.budget !== undefined) lines.push(`budget: ${origin.budget}`);
+ const block = markerBlock(MARKER_TAGS.orgTrigger, lines.join("\n"));
+ return body === "" ? block : `${block}\n\n${body}`;
+}
+
+const ORG_TRIGGER_PATTERNS = dualFormPatterns(MARKER_TAGS.orgTrigger, "\\n([\\s\\S]*?)\\n");
+
+/**
+ * Inverse of `buildOrgTriggerMessage`: origin info plus the body when the message **starts
+ * with** an `[org_trigger]` block, otherwise null. An unknown `kind` makes the block unparsable
+ * (returned as null) rather than silently reinterpreted.
+ */
+export function parseOrgTriggerMessage(
+ text: string,
+): { origin: OrgTriggerOrigin; rest: string } | null {
+ const m = matchDualForm(ORG_TRIGGER_PATTERNS, text);
+ if (!m || m.index !== 0) return null;
+ const fields = new Map<string, string>(fieldLines(m[1]!, ORG_TRIGGER_KEYS));
+ const org = fields.get("org");
+ const employee = fields.get("employee");
+ const kind = fields.get("kind");
+ if (!org || !employee || !isOrgTriggerKind(kind)) return null;
+ const origin: OrgTriggerOrigin = { org, employee, kind };
+ const event = fields.get("event");
+ if (event !== undefined) origin.event = event;
+ const firedAt = fields.get("fired_at");
+ if (firedAt !== undefined) origin.firedAt = firedAt;
+ const message = fields.get("message");
+ if (message !== undefined) origin.message = message;
+ const channel = fields.get("channel");
+ if (channel !== undefined) origin.channel = channel;
+ const ticket = fields.get("ticket");
+ if (ticket !== undefined) origin.ticket = ticket;
+ const change = fields.get("change");
+ if (change !== undefined) origin.change = change;
+ const budget = fields.get("budget");
+ if (budget !== undefined) origin.budget = budget;
+ return { origin, rest: text.slice(m[0].length).replace(/^\n+/, "") };
+}
+
+function isOrgTriggerKind(value: string | undefined): value is OrgTriggerKind {
+ return (
+ value === "init" ||
+ value === "event" ||
+ value === "mention" ||
+ value === "ticket_notice" ||
+ value === "ticket_work"
+ );
+}
+
// ---------------------------------------------------------------------------
// [model_switch_from] — the /model command's handoff-style conversation switch
// ---------------------------------------------------------------------------
diff --git a/packages/core/src/omnimessage/markers/tags.ts b/packages/core/src/omnimessage/markers/tags.ts
index 2f3876be..3a46a26a 100644
--- a/packages/core/src/omnimessage/markers/tags.ts
+++ b/packages/core/src/omnimessage/markers/tags.ts
@@ -23,6 +23,8 @@ export const MARKER_TAGS = {
handoffFrom: "handoff_from",
/** Scheduled-task trigger origin block (server scheduler). */
scheduledTask: "scheduled_task",
+ /** Organization trigger origin block — a work run or ticket session opened by the company-mode scheduler (server). */
+ orgTrigger: "org_trigger",
/** Background-task completion report injected as a harness user message (exec_command / run_subagent with run_in_background). */
backgroundTaskDone: "background_task_done",
/** `/model` switch origin block, first message of the continued conversation (Web). */
@@ -50,6 +52,7 @@ export const TITLE_NOISE_TAGS: readonly string[] = [
MARKER_TAGS.useSkills,
MARKER_TAGS.handoffFrom,
MARKER_TAGS.scheduledTask,
+ MARKER_TAGS.orgTrigger,
MARKER_TAGS.modelSwitchFrom,
MARKER_TAGS.backgroundTaskDone,
];
diff --git a/packages/core/src/plugins/index.ts b/packages/core/src/plugins/index.ts
index 178eef8b..441fe349 100644
--- a/packages/core/src/plugins/index.ts
+++ b/packages/core/src/plugins/index.ts
@@ -501,6 +501,7 @@ export const PLUGIN_CATEGORIES: PluginCategory[] = [
{ id: "office-productivity", title: "Office Productivity", titleZh: "办公效率" },
{ id: "software-development", title: "Software Development", titleZh: "软件开发" },
{ id: "ai-app-development", title: "AI App Development", titleZh: "AI 应用开发" },
+ { id: "agent-company", title: "Agent Company", titleZh: "Agent 公司" },
];
/**
diff --git a/packages/core/test/markers.test.ts b/packages/core/test/markers.test.ts
index 46856244..e78f5586 100644
--- a/packages/core/test/markers.test.ts
+++ b/packages/core/test/markers.test.ts
@@ -15,6 +15,7 @@ import {
buildContextSummaryText,
buildHandoffMessage,
buildModelSwitchMessage,
+ buildOrgTriggerMessage,
buildScheduledMessage,
buildSkillsMessage,
buildTurnAbortedBlock,
@@ -25,6 +26,7 @@ import {
matchDualForm,
parseHandoffMessage,
parseModelSwitchMessage,
+ parseOrgTriggerMessage,
parseScheduledMessage,
parseSkillsMessage,
parseUserSteeringText,
@@ -68,6 +70,7 @@ describe("marker block primitives", () => {
MARKER_TAGS.useSkills,
MARKER_TAGS.handoffFrom,
MARKER_TAGS.scheduledTask,
+ MARKER_TAGS.orgTrigger,
MARKER_TAGS.modelSwitchFrom,
MARKER_TAGS.backgroundTaskDone,
]);
@@ -190,6 +193,48 @@ describe("[user_steering] messages", () => {
});
});
+describe("[org_trigger] (company-mode work runs and ticket sessions)", () => {
+ it("round-trips every field and keeps the body", () => {
+ const origin = {
+ org: "acme",
+ employee: "acme_hr (HR, reports to acme_ceo)",
+ kind: "event" as const,
+ event: "daily-standup",
+ firedAt: "2026-09-01T09:00:00+08:00",
+ budget: "12.40 / 30.00 USD (41%)",
+ };
+ const text = buildOrgTriggerMessage(origin, "Sweep the board.");
+ expect(text.startsWith("[org_trigger]\n")).toBe(true);
+ expect(text).toContain("<app_data_dir>/organizations/acme/handbook/README.md");
+ expect(parseOrgTriggerMessage(text)).toEqual({ origin, rest: "Sweep the board." });
+ });
+
+ it("carries the channel a mention was posted in, and the one to answer in", () => {
+ const origin = {
+ org: "acme",
+ employee: "acme_dev (Developer, reports to acme_ceo)",
+ kind: "mention" as const,
+ message: "msg-2026-09-03-01-00-00-00000000 from user:alice",
+ channel: "site",
+ };
+ const text = buildOrgTriggerMessage(origin, "> the message");
+ expect(text).toContain("\nchannel: site\n");
+ expect(parseOrgTriggerMessage(text)).toEqual({ origin, rest: "> the message" });
+ // Absent on the kinds that have no channel, and absent from what they parse back to.
+ const init = buildOrgTriggerMessage({ org: "acme", employee: "acme_ceo", kind: "init" }, "");
+ expect(init).not.toContain("channel:");
+ expect(parseOrgTriggerMessage(init)?.origin.channel).toBeUndefined();
+ });
+
+ it("returns null for an unknown kind, a missing employee, or plain text", () => {
+ const text = buildOrgTriggerMessage({ org: "acme", employee: "acme_ceo", kind: "init" }, "");
+ expect(text.endsWith("[/org_trigger]")).toBe(true);
+ expect(parseOrgTriggerMessage(text.replace("kind: init", "kind: party"))).toBeNull();
+ expect(parseOrgTriggerMessage(text.replace("employee: acme_ceo\n", ""))).toBeNull();
+ expect(parseOrgTriggerMessage("hello")).toBeNull();
+ });
+});
+
describe("origin blocks ([use_skills] / [handoff_from] / [scheduled_task] / [model_switch_from])", () => {
it("[use_skills]: builds a leading block + body and parses it back; an empty list adds nothing", () => {
expect(buildSkillsMessage(["penguin-sdk"], "write me a demo")).toBe(
diff --git a/packages/core/test/plugins.test.ts b/packages/core/test/plugins.test.ts
index f2e8e61d..bbc4d8ea 100644
--- a/packages/core/test/plugins.test.ts
+++ b/packages/core/test/plugins.test.ts
@@ -41,7 +41,7 @@ describe("loadLibraryPlugins", () => {
it("loads every plugin directory sorted by name, each with a date-sequence version and a category", () => {
const plugins = loadLibraryPlugins();
expect(plugins.map((p) => p.name)).toEqual([...plugins.map((p) => p.name)].sort());
- expect(plugins.length).toBe(12);
+ expect(plugins.length).toBe(13);
for (const plugin of plugins) {
expect(plugin.version, plugin.name).toMatch(PLUGIN_VERSION_PATTERN);
expect(
@@ -135,7 +135,7 @@ describe("loadPreinstalledPlugins", () => {
const preinstalled = loadPreinstalledPlugins().map((p) => p.name);
expect(preinstalled).toContain("goal");
expect(preinstalled).toContain("software-development");
- for (const manual of ["continual-learning", "humanizer", "use-claude-code"]) {
+ for (const manual of ["agent-company", "continual-learning", "humanizer", "use-claude-code"]) {
expect(all).toContain(manual);
expect(preinstalled).not.toContain(manual);
}
@@ -177,7 +177,7 @@ describe("groupPlugins / loadPluginGroups", () => {
expect(groups[2]).toMatchObject({ title: "Other", titleZh: "其他" });
});
- it("the library itself fills the three categories and leaves no Other group; hook packages sit with their audience", () => {
+ it("the library itself fills every category and leaves no Other group; hook packages sit with their audience", () => {
const groups = loadPluginGroups();
expect(groups.map((g) => g.id)).toEqual(PLUGIN_CATEGORIES.map((c) => c.id));
const names = (id: string) => groups.find((g) => g.id === id)?.plugins.map((p) => p.name);
@@ -195,6 +195,7 @@ describe("groupPlugins / loadPluginGroups", () => {
"model-development",
"skill-porting",
]);
+ expect(names("agent-company")).toEqual(["agent-company"]);
});
});
diff --git a/packages/desktop/package.json b/packages/desktop/package.json
index 432b4b06..de7d68cb 100644
--- a/packages/desktop/package.json
+++ b/packages/desktop/package.json
@@ -16,6 +16,7 @@
"pack:win": "node scripts/preflight.mjs && electron-builder --win"
},
"dependencies": {
+ "@penguinharness/agent-company": "workspace:*",
"@penguinharness/agent-development": "workspace:*",
"@penguinharness/agent-tuning": "workspace:*",
"@penguinharness/continual-learning": "workspace:*",
diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.md
index 781282ba..7b16379f 100644
--- a/packages/docs/content/cli.en.md
+++ b/packages/docs/content/cli.en.md
@@ -5,7 +5,7 @@ description: Complete reference for the penguin command, its subcommands, and op
The CLI ships as the npm package `@prismshadow/penguin-cli`; the command is `penguin`. Running bare `penguin` prints help; `-v, --version` prints the running build's one-line identity, and `penguin version --json` prints the whole of it. A `.env` file in the working directory is loaded automatically on startup.
-The CLI is a thin client of the server: every session-facing command (`run`, `chat`, `ls`, `input`, `logs`, `agent`, `project`, `cost`, `schedule`) sends HTTP requests to a PenguinHarness server and renders the replies — tasks execute on the server, sessions live in its index, and the Web App sees everything the CLI creates (and vice versa). Only `config` still edits the Project's files directly, and `server` / `web` start the service itself.
+The CLI is a thin client of the server: every session-facing command (`run`, `chat`, `ls`, `input`, `logs`, `agent`, `project`, `cost`, `schedule`, `org`) sends HTTP requests to a PenguinHarness server and renders the replies — tasks execute on the server, sessions live in its index, and the Web App sees everything the CLI creates (and vice versa). Only `config` still edits the Project's files directly, and `server` / `web` start the service itself.
## Server connection
@@ -216,6 +216,72 @@ penguin schedule rm daily-report
| `--enable` / `--disable` (`update`) | Flip the enabled flag; `update` is read-modify-write against the stored item, so unspecified fields keep their values, and switching target kinds clears the other kind's fields |
| `--project-id` / `--agent-id` / `--json` / `--server` | As everywhere; `rm` deletes without prompting (the server's owner authorization still applies) |
+## penguin org
+
+Company mode's command family — a thin client over the organization API. An organization's files under the Project directory (the employee tree, the desks ledger, calendar, tickets, channels) stay the single source of truth; every subcommand reads a projection of them or writes through the route that edits them, with the same validated-writer contract `schedule` has: API errors surface verbatim, so an agent gets synchronous validation instead of the reconcile lag a hand edit hits. Generated ids carry a prefix by convention — `co_` for an organization, `ch_` for a channel — which the server proposes but never enforces, so an id passed here is created exactly as typed.
+
+```bash
+penguin org ls [--project-id <id>] [--json]
+penguin org create --org-id <id> --mission <s> [--name <s>] [--language <zh|en>] [--workspace <path>] [--ceo-budget <usd>] [--model-id <id> --provider <p>] [--project-id <id>] # by convention `co_<slug>`
+penguin org show [--org-id <id>] [--json] # overview: working language, employees and states, board counts, spend against budget, pending items
+penguin org chart [--org-id <id>] [--json] # the employee tree
+penguin org hire (--agent-id <id> | --new-agent <id> [--name <s>] [--description <s>] [--skills <a,b>]) --title <s> --reports-to <agent_id> [--workspace <path>] [--budget <usd>] [--duties <s>]
+penguin org employee set <agent_id> [--title <s>] [--reports-to <agent_id>] [--workspace <path>] [--budget <usd>] [--duties <s>] [--model-id <id> --provider <p>]
+penguin org leave <agent_id> # out of the organization (not the CEO); the Agent itself stays
+penguin org desk show [<agent_id>] [--json] # the desk session id and Workspace (opens the desk if there is none)
+penguin org desk renew [<agent_id>] # a fresh desk session (resets the context)
+penguin org calendar ls [--agent-id <id>] [--json]
+penguin org calendar add <name> [--agent-id <id>] --prompt <s> --start-at <ISO|now> [--period <dur>] [--end-at <ISO>] [--title <s>] [--disabled]
+penguin org calendar update <name> [--agent-id <id>] [same fields] [--enable|--disable]
+penguin org calendar rm <name> [--agent-id <id>]
+penguin org ticket ls [--status <col>] [--owner <principal>] [--blocked] [--json]
+penguin org ticket show <ticket_id> [--json]
+penguin org ticket create --title <s> (--goal <s> [--criteria <s>] | --body-file <path>) [--owner <principal>] [--slug <words>] [--parent <ticket_id>] [--notify <p,p>] [--priority P0|P1|P2] [--due <date>]
+penguin org ticket move <ticket_id> --to <col> [--reason <s>] # moving into rejected needs a reason
+penguin org ticket assign <ticket_id> --owner <principal>
+penguin org ticket block <ticket_id> --reason <s> [--by <principal|ticket_id>] # the ticket stays in its column
+penguin org ticket unblock <ticket_id>
+penguin org ticket progress <ticket_id> -m <text> # a progress entry, attributed to the calling session
+penguin org ticket start <ticket_id> [-m <note>] [--workspace <path>] [--agent-id <id>] [--json] # a ticket session working on the ticket in the background; prints its id
+penguin org ticket attach <ticket_id> [--session <session_id>] # an existing session as a contributor (default: the calling session)
+penguin org channel ls [--json] # every channel for a person, its own for an employee
+penguin org channel create <channel_id> [--name <s>] [--purpose <s>] # a new channel holds only its creator; `ch_<slug>` by convention
+penguin org channel show <channel_id> [--json] # purpose, member count and the member list
+penguin org channel invite <channel_id> <principal>... # any member invites; one POST per principal
+penguin org channel join <channel_id> # people only; an employee waits to be invited
+penguin org channel leave <channel_id> # self-removal
+penguin org channel remove <channel_id> <principal> # people only
+penguin org channel archive <channel_id> | unarchive <channel_id> # people only; read-only while archived
+penguin org channel tail [--channel <id>] [--date <d>] [-n <count>] [--json]
+penguin org channel send -m <text> [--channel <id>] [--ref-ticket <id>] [--ref-session <id>]
+penguin org handbook list [--json]
+penguin org handbook show [path] [--json]
+penguin org handbook write <path> (-m <text> | --file <file>)
+penguin org handbook rm <path>
+penguin org finance [--period <YYYY-MM>] [--json]
+```
+
+Every subcommand takes `--org-id <id>`, `--project-id`, `--json` and `--server`. **`--org-id` defaults to `PENGUIN_ORG_ID`**, the one variable company mode adds to the control environment described under "Server connection": the server injects it into every tool subprocess of a desk or ticket session, so an employee's own `penguin org` calls address its organization without naming it, while a person in a shell passes the flag. There is no default organization — with neither, the command fails before contacting any server. `create` is the exception: its `--org-id` is the id to create and never comes from the environment. `--json` prints the response as one line of JSON; the write commands otherwise print a one-line confirmation.
+
+The same environment identifies the caller inside a session:
+
+- `--agent-id` on the `calendar` commands and the positional of `desk` default to `PENGUIN_AGENT_ID` — an employee schedules its own events and renews its own desk. `calendar ls` without the flag lists every employee's events.
+- `ticket start` runs the ticket session as `--agent-id` when given, else `PENGUIN_AGENT_ID` when set, else the ticket's owner as the server picks it. It also carries `PENGUIN_SESSION_ID`, which is what lets the server apply the rule: **only the ticket's owner, or a person, starts its sessions** — an employee asking for anyone else's ticket (or for one with no employee owner) gets `403 not_ticket_owner`, printed verbatim, telling it to assign the ticket instead (`penguin org ticket assign <id> --owner agent:<employee>`) and let that desk pick it up in its next sweep. `--agent-id` is how the owner enlists a colleague on its own ticket.
+- The ticket writes (`create`, `assign`, `move`, `block`, `unblock`, `progress`) and the channel writes (`create`, `invite`, `join`, `archive`, `unarchive`, `send`) carry `PENGUIN_SESSION_ID` in their body, so the file records the session's employee rather than the token's user; `ticket attach` attaches that session when `--session` is omitted (a full id or a unique fragment, as everywhere).
+- The channel reads (`ls`, `show`, `tail`) and the member DELETE behind `leave` and `remove` have no body, so they carry the same session as `?sessionId=`. Without it the server answers an employee as the signed-in person, and `channel ls` would list every channel instead of the employee's own.
+
+`--channel` defaults to `default_channel`, the all-hands channel every employee and Project member is in; `ls` prints it first, under its localized label rather than its stored name. A new channel holds only its creator: an employee gets in when a member invites it, a person may `join` any channel and read every one of them. `join` and `leave` name the caller's own principal — the session's employee inside a desk or ticket session, the signed-in person outside one — so joining can never add somebody else. `join`, `remove`, `archive` and `unarchive` are people's actions, so inside a session the server answers them `403 not_a_member` — like every other API error, printed verbatim.
+
+Per group:
+
+- `ls` / `show` / `chart`: the project's organizations with employee, ticket and spend counts; one organization's overview — name, mission, status and working language, employees by state, tickets per column, the period's spend against the CEO's budget, and what waits for you (mentions, tickets to review, tickets blocked on you); and the reporting tree, indented by level, with each employee's title, live state, own and cumulative spend and budget. An organization or employee that fails validation is listed with `invalid: <reason>` rather than hidden.
+- `create`: `--ceo-budget` is the CEO's monthly budget in USD and defaults to **100**. Budgets are compared on the cumulative line — the employee plus every subordinate — so the CEO's is the whole company's: a new organization is capped rather than unbounded, and the initialization run's trigger block names the number so the CEO can size its hiring proposal to it. `0` is a real (zero) budget; clearing it again — back to unbounded — is `PATCH .../employees/<org_id>_ceo` with `budget: null`, which the Web App's employee editor sends. `--language zh|en` is the organization's working language; without it the mission decides it (one Han character anywhere makes it `zh`), and everything the organization writes — its handbook, the employee briefs, the CEO's initialization run, the desk session titles — follows.
+- `hire`: exactly one of `--agent-id` (an existing Agent) and `--new-agent` (creates it; `--name`, `--description` and `--skills` — extra library plugins, added on top of the `agent-company,agent-development` every employee needs — describe it). `--workspace` is a sub-directory of the organization's shared workspace (`.` for all of it) or an absolute path, never resolved against the CLI's cwd, and defaults to a sub-directory named after the employee — the shared root holds the shared inputs and is nobody's desk. A relative sub-directory is normalized — `./hr`, `hr/` and `hr` are one partition — and created by the server as the hire is written, so `--workspace hr` is enough and nothing has to exist first; an absolute path names a directory of the user's and must already exist; a spec that climbs out of the shared workspace with `..` is refused with 400 `invalid_workspace`. `employee set --workspace` does the same but has no default: it changes the partition only when it is given. A desk or ticket session creates the directory too when it opens. `--budget` is USD per month for the employee plus everyone below it. `employee set` changes only the given fields; the model pair is both-or-neither, as everywhere.
+- `calendar`: the same writer as `penguin schedule` — `add` is enabled by default with `--disabled` opting out, `--start-at now` is the current instant, `update` is read-modify-write, `rm` deletes without prompting. Events fire into the employee's desk session, and only while the organization and the employee are active; the status column says `paused` otherwise. `add` and `update` answer with the event plus the rota advice the write earned — another employee's recurring event on the same start minute, a second recurring event for the same employee on the same period, a recurring event started at `now` — printed one per line as `Rota notice: …`. They are advisory: the write always succeeds, and the lines stay in the server's English.
+- `ticket`: `ls` fetches the whole board and filters locally (`--status` is a column: `proposed`, `in_progress`, `review`, `done`, `rejected`); `show` prints the derived figures — column, running state, cost and rolled-up cost, contributing sessions, child tickets — then the ticket's own fields, its prose sections and its operation history under `History:`. `create` takes either `--goal` (with `--criteria`) or the whole Markdown body from `--body-file`; the frontmatter is generated either way. Under `--json`, `ls` prints the filtered list as `{ tickets, invalidFiles }`. `start` prints the bare session id, like `run --background`, for `penguin logs` / `penguin input` to pick up. `--owner <principal>` names the ONE principal responsible — an employee (an Agent id or `agent:<id>`) or a Project member (`user:<id>`), the caller by default; when no `--notify` is given it becomes the whole `notify` list, but only when it is an employee: a person is not notified about a ticket they own, and lists themselves in `--notify` to be told. Who filed a ticket is not a flag — it is the `created` entry of its history, taken from the environment the command ran in. A ticket id is `<yyyy-mm-dd>-<slug>` with the slug in lowercase English words joined by hyphens; `--slug <words>` names it, and a title with too little English in it needs that flag when the server cannot have the Project's model name it (400 `slug_required`). A write that claims work — `progress`, an edit of the body, `move --to review` — also books the calling session as one of the ticket's contributing sessions, so its cost is split onto the ticket; moving into any other column, `block` and `unblock` book nothing. `progress -m` takes one plain sentence — what was done and where — since the server records who wrote it and when. `--goal`, `--criteria` and `progress -m` ask for every input, deliverable and file to be named by its full path.
+- `channel tail` prints the day's last 20 messages (`-n` changes the count, `--date` picks another day) as `time sender text` — under `--json`, the day's response with those messages; `channel send` posts one — `@agent:<id>` and `@all` mentions trigger the mentioned employees' desks. A `system` line carries a structured `notice` beside its English text, so `tail` renders it in the CLI's own language; a kind this build does not know keeps the English.
+- `finance`: the period's spend per employee (own and cumulative along the reporting line, against the budget, with `warned` / `paused` marks) and per ticket, then the total; when some usage ran on a model without pricing, a note on stderr says the figures are a lower bound.
+
## Approval modes (--approve)
| Mode | Behavior |
diff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.md
index 5908b19f..77a751f6 100644
--- a/packages/docs/content/cli.zh.md
+++ b/packages/docs/content/cli.zh.md
@@ -5,7 +5,7 @@ description: penguin 命令的子命令与选项完整参考。
CLI 由 npm 包 `@prismshadow/penguin-cli` 提供,命令为 `penguin`。不带子命令执行 `penguin` 时打印帮助;`-v, --version` 打印当前构建的单行身份,`penguin version --json` 打印其完整信息。启动时自动加载工作目录下的 `.env`。
-CLI 是服务端的瘦客户端:所有会话相关命令(`run`、`chat`、`ls`、`input`、`logs`、`agent`、`project`、`cost`、`schedule`)都向 PenguinHarness 服务端发 HTTP 请求并渲染回复——Task 在服务端执行,Session 记录在服务端索引里,Web App 能看到 CLI 创建的一切(反之亦然)。只有 `config` 仍直接编辑 Project 配置文件,`server` / `web` 则负责启动服务本身。
+CLI 是服务端的瘦客户端:所有会话相关命令(`run`、`chat`、`ls`、`input`、`logs`、`agent`、`project`、`cost`、`schedule`、`org`)都向 PenguinHarness 服务端发 HTTP 请求并渲染回复——Task 在服务端执行,Session 记录在服务端索引里,Web App 能看到 CLI 创建的一切(反之亦然)。只有 `config` 仍直接编辑 Project 配置文件,`server` / `web` 则负责启动服务本身。
## 服务器连接
@@ -216,6 +216,72 @@ penguin schedule rm daily-report
| `--enable` / `--disable`(`update`) | 翻转启用位;`update` 对存储项读改写:未指定的字段保留原值,切换目标类型时清掉另一类字段 |
| `--project-id` / `--agent-id` / `--json` / `--server` | 同各处约定;`rm` 直接删除、不做确认(服务端的 owner 授权照旧生效) |
+## penguin org
+
+公司模式的命令族——组织 API 的瘦客户端。组织在 Project 目录下的文件(员工树、工位台账、日程、工单、频道)仍是唯一真相源;每个子命令要么读取它们的投影,要么经编辑它们的接口写入,契约与 `schedule` 的带校验写入器相同:API 错误原样透出,Agent 因此获得同步校验,而非手编文件时要等对账周期的滞后。自动生成的 id 按约定带前缀——组织 `co_`、频道 `ch_`——服务端只提议、不强制,因此这里传入的 id 一律按原样创建。
+
+```bash
+penguin org ls [--project-id <id>] [--json]
+penguin org create --org-id <id> --mission <s> [--name <s>] [--language <zh|en>] [--workspace <path>] [--ceo-budget <usd>] [--model-id <id> --provider <p>] [--project-id <id>] # 按约定取 `co_<slug>`
+penguin org show [--org-id <id>] [--json] # 概览:工作语言、员工与状态、看板计数、预算占用、待处理事项
+penguin org chart [--org-id <id>] [--json] # 员工树
+penguin org hire (--agent-id <id> | --new-agent <id> [--name <s>] [--description <s>] [--skills <a,b>]) --title <s> --reports-to <agent_id> [--workspace <path>] [--budget <usd>] [--duties <s>]
+penguin org employee set <agent_id> [--title <s>] [--reports-to <agent_id>] [--workspace <path>] [--budget <usd>] [--duties <s>] [--model-id <id> --provider <p>]
+penguin org leave <agent_id> # 移出组织(CEO 不可),不删 Agent
+penguin org desk show [<agent_id>] [--json] # 工位会话 id 与 Workspace(尚无工位时开一个)
+penguin org desk renew [<agent_id>] # 换新的工位会话(重置上下文)
+penguin org calendar ls [--agent-id <id>] [--json]
+penguin org calendar add <name> [--agent-id <id>] --prompt <s> --start-at <ISO|now> [--period <dur>] [--end-at <ISO>] [--title <s>] [--disabled]
+penguin org calendar update <name> [--agent-id <id>] [<同上字段>] [--enable|--disable]
+penguin org calendar rm <name> [--agent-id <id>]
+penguin org ticket ls [--status <col>] [--owner <principal>] [--blocked] [--json]
+penguin org ticket show <ticket_id> [--json]
+penguin org ticket create --title <s> (--goal <s> [--criteria <s>] | --body-file <path>) [--owner <principal>] [--slug <words>] [--parent <ticket_id>] [--notify <p,p>] [--priority P0|P1|P2] [--due <date>]
+penguin org ticket move <ticket_id> --to <col> [--reason <s>] # 移入 rejected 须给 reason
+penguin org ticket assign <ticket_id> --owner <principal>
+penguin org ticket block <ticket_id> --reason <s> [--by <principal|ticket_id>] # 工单留在所在列
+penguin org ticket unblock <ticket_id>
+penguin org ticket progress <ticket_id> -m <text> # 追加一条进展,记为当前会话所写
+penguin org ticket start <ticket_id> [-m <附言>] [--workspace <path>] [--agent-id <id>] [--json] # 新开一个后台处理该工单的工单会话,打印会话 id
+penguin org ticket attach <ticket_id> [--session <session_id>] # 把既有会话挂为贡献会话(缺省当前会话)
+penguin org channel ls [--json] # 人看到全部频道,员工只看到自己所在的
+penguin org channel create <channel_id> [--name <s>] [--purpose <s>] # 新频道只有创建者一人;按约定取 `ch_<slug>`
+penguin org channel show <channel_id> [--json] # 用途、成员数与成员清单
+penguin org channel invite <channel_id> <principal>... # 任一成员可邀请;每个 principal 一次 POST
+penguin org channel join <channel_id> # 仅限人;员工只能等成员邀请
+penguin org channel leave <channel_id> # 移出自己
+penguin org channel remove <channel_id> <principal> # 仅限人
+penguin org channel archive <channel_id> | unarchive <channel_id> # 仅限人;归档期间只读
+penguin org channel tail [--channel <id>] [--date <d>] [-n <count>] [--json]
+penguin org channel send -m <text> [--channel <id>] [--ref-ticket <id>] [--ref-session <id>]
+penguin org handbook list [--json]
+penguin org handbook show [path] [--json]
+penguin org handbook write <path> (-m <text> | --file <file>)
+penguin org handbook rm <path>
+penguin org finance [--period <YYYY-MM>] [--json]
+```
+
+每个子命令都接受 `--org-id <id>`、`--project-id`、`--json` 与 `--server`。**`--org-id` 缺省取 `PENGUIN_ORG_ID`**——公司模式在「服务器连接」一节所述控制环境之外多注入的一个变量:服务端把它注入工位会话与工单会话的每个工具子进程,员工自己的 `penguin org` 调用因此无需点名组织;人类在 shell 里则显式给出。没有缺省组织——两者都没有时,命令在联系任何服务器之前即失败。`create` 是例外:它的 `--org-id` 是要创建的 id,绝不取自环境。`--json` 把响应以单行 JSON 打印;写入类命令否则打印一行确认。
+
+同一套环境在会话内标识调用方:
+
+- `calendar` 各命令的 `--agent-id` 与 `desk` 的位置参数缺省取 `PENGUIN_AGENT_ID`——员工安排自己的日程、换自己的工位。`calendar ls` 不带该选项时列出全部员工的日程项。
+- `ticket start` 给了 `--agent-id` 就用它,否则用设置了的 `PENGUIN_AGENT_ID`,再否则由服务端取工单负责人。它同时携带 `PENGUIN_SESSION_ID`,服务端据此施加规则:**一张工单的会话只能由它的负责人或人发起**——员工对别人的工单(或没有员工负责人的工单)发起会得到 `403 not_ticket_owner`,原样打印,提示改用改派(`penguin org ticket assign <id> --owner agent:<员工>`),由那名员工的工位在下一次巡检时接手。`--agent-id` 则是负责人把同事拉进自己名下工单的方式。
+- 工单写入(`create`、`assign`、`move`、`block`、`unblock`、`progress`)与频道写入(`create`、`invite`、`join`、`archive`、`unarchive`、`send`)在请求体里携带 `PENGUIN_SESSION_ID`,文件因此记录该会话的员工而非 token 对应的用户;`ticket attach` 省略 `--session` 时挂接的就是它(完整 id 或唯一片段,同各处约定)。
+- 频道读取(`ls`、`show`、`tail`)以及 `leave` 与 `remove` 背后的成员 DELETE 没有请求体,同一个会话改由 `?sessionId=` 传入。不带它,服务端会把员工当作登录的那个人来应答,`channel ls` 便会列出全部频道而非该员工自己的。
+
+`--channel` 缺省为 `default_channel`,即全体员工与全体 Project 成员都在其中的全员频道;`ls` 把它排在最前,并显示本地化名称而非其存储的 name。新频道只有创建者一人:员工要由成员邀请才能进入,人可以自行 `join` 任何频道,也能读到全部频道。`join` 与 `leave` 提交的都是调用方自己的 principal——在工位会话或工单会话内是该会话的员工,在会话外是登录的那个人——因此 `join` 绝不会把别人拉进频道。`join`、`remove`、`archive` 与 `unarchive` 是人的操作,因此在会话内执行时服务端返回 `403 not_a_member`——与其他 API 错误一样原样透出。
+
+分组说明:
+
+- `ls` / `show` / `chart`:Project 的组织及其员工、工单与支出计数;单个组织的概览——名称、使命、状态与工作语言,按状态分的员工数,各列工单数,本期支出对照 CEO 预算,以及等你处理的事(@我、待审核工单、等我的阻塞);以及按层级缩进的汇报树,逐员工列出头衔、实时状态、自身与累计支出和预算。校验失败的组织或员工以 `invalid: <原因>` 列出,不隐藏。
+- `create`:`--ceo-budget` 是 CEO 的月预算(美元),缺省 **100**。预算按累计线比较——该员工及其全部下属——所以 CEO 的预算就是整家公司的:新组织一开始就有上限而非无限,初始化会话的触发块里也会带上这个数字,CEO 据此裁剪自己的招募方案。`0` 是真的零预算;要重新变回无限,用 `PATCH .../employees/<org_id>_ceo` 传 `budget: null`(Web App 的员工编辑即发此请求)。`--language zh|en` 指定组织的工作语言;不给则由使命决定(正文里出现任一汉字即为 `zh`),组织写下的一切——组织手册、员工简介、CEO 的初始化会话、工位会话标题——都随之而定。
+- `hire`:`--agent-id`(既有 Agent)与 `--new-agent`(新建)二选一;`--name`、`--description`、`--skills`(额外的插件库插件,追加在每个员工都需要的 `agent-company,agent-development` 之上)描述新 Agent。`--workspace` 是组织公共工作区的子目录(`.` 即整个工作区)或绝对路径,不按 CLI 的 cwd 解析;不给则缺省为以该员工命名的子目录——公共工作区的根目录放共享输入,不是任何人的工位。相对子目录会先归一化——`./hr`、`hr/` 与 `hr` 是同一个分区——并在写下这次招募时由服务端建好,因此 `--workspace hr` 就够了,无需事先存在;绝对路径指向用户自己的目录,必须已经存在;用 `..` 爬出公共工作区的写法直接以 400 `invalid_workspace` 拒收。`employee set --workspace` 规则相同,但没有缺省值:只有给出时才改动分区。工位会话与工单会话打开时也会补建该目录。`--budget` 是该员工及其全部下属的月预算(美元)。`employee set` 只改给出的字段;模型对「都给或都不给」,同各处约定。
+- `calendar`:与 `penguin schedule` 同一套写入器——`add` 缺省启用、`--disabled` 关闭,`--start-at now` 即当前时刻,`update` 读改写,`rm` 不做确认。日程项一律发往员工的工位会话,且只在组织与该员工都处于运行状态时触发;否则状态列显示 `paused`。`add` 与 `update` 在返回事件之外附上本次写入引出的排班提醒——同一起始分钟上已有另一位员工的常设日程项、同一员工已有同周期的常设日程项、常设日程项以 `now` 起算——每条一行,以「排班提醒:」打印。它们只是建议:写入一律成功,提醒文本保持服务端的英文。
+- `ticket`:`ls` 取整个看板后在本地过滤(`--status` 为列名:`proposed`、`in_progress`、`review`、`done`、`rejected`);`show` 先打印派生数据——所在列、运行状态、成本与含子工单成本、贡献会话数、子工单数——再打印工单自身的字段、正文各节,最后以 `History:` 打印操作历史。`create` 二选一:`--goal`(配合 `--criteria`)或以 `--body-file` 给出整个 Markdown 正文,frontmatter 都由服务端生成。`--json` 下 `ls` 以 `{ tickets, invalidFiles }` 打印过滤后的列表。`start` 像 `run --background` 一样打印裸 session id,供 `penguin logs` / `penguin input` 接续。`--owner <principal>` 指定这张工单**唯一**的责任人——组织的员工(Agent id 或 `agent:<id>`)或 Project 成员(`user:<id>`),缺省为调用方;没有 `--notify` 时它成为整个 `notify`,但仅限负责人是员工:人不会因为自己名下的工单收到通知,想收到就把自己写进 `--notify`。谁创建的不是一个选项——它记在工单 `history` 的 `created` 条目里,取自命令运行所在的环境。工单 id 形如 `<yyyy-mm-dd>-<slug>`,slug 是用连字符连接的小写英文单词;`--slug <words>` 直接指定它,标题里英文太少、服务端又无法让 Project 的模型代取时(400 `slug_required`)就必须用这个选项。声称做了活的写入——`progress`、正文编辑、`move --to review`——还会把调用方所在的会话记为该工单的贡献会话,其成本因此摊到工单上;移入其他列以及 `block`、`unblock` 都不记。`progress -m` 只写一句大白话——做了什么、东西在哪——谁写的、什么时候写的由服务端记录。`--goal`、`--criteria` 与 `progress -m` 要求把依赖的输入、预期交付物与涉及的文件一律写成完整路径。
+- `channel tail` 以 `time sender text` 打印当天最后 20 条消息(`-n` 改条数,`--date` 换一天),`--json` 下即当天的响应、只含这些消息;`channel send` 发一条——`@agent:<id>` 与 `@all` 会触发被提及员工的工位。`system` 消息在英文正文之外带一份结构化 `notice`,`tail` 因此按 CLI 自身的语言渲染;本版本不认识的种类保留英文原文。
+- `finance`:本期按员工(自身与沿汇报线累计,对照预算,附 `warned` / `paused` 标记)与按工单的支出,然后是合计;部分用量所用模型未配置价格时,stderr 上一行提示说明数字是下限。
+
## 审批模式(--approve)
| 模式 | 行为 |
diff --git a/packages/docs/content/company-mode.en.md b/packages/docs/content/company-mode.en.md
new file mode 100644
index 00000000..a09a34bd
--- /dev/null
+++ b/packages/docs/content/company-mode.en.md
@@ -0,0 +1,132 @@
+---
+title: Company Mode
+description: Turn a one-sentence mission into an organization of Agents — a CEO that hires, a calendar that drives every desk, a ticket board that carries the work, channels where only @mentions interrupt anyone, and budgets that pause spending before it runs away.
+---
+
+## What it is
+
+**Company mode is a beta feature**: it may still be unstable, so please report anything you hit.
+
+Development mode is one person talking to one Agent. Company mode is the second work mode of the Web App: a Project's Agents organized into a **company** that runs by itself for weeks — driven by a calendar, carrying its work on a ticket board, talking in channels — while you sit on the board and decide only what needs a person. You give it a mission in one sentence; it creates the CEO; the CEO hires HR, finance and whoever the mission needs, partitions the shared workspace, schedules everyone and files the first tickets.
+
+Everything the company is lives in **files** under the Project directory. SQLite keeps caches that are rebuilt from those files on every pass, plus each user's read cursor in each channel — the same rule development mode follows for Agent State and Traces. Delete the caches and nothing changes; edit a file by hand and the next pass picks it up.
+
+Switch modes with the Development | Company control at the top-left of the sidebar. It is there when the admin's master switch is on (System settings › Server › Company mode, **off by default** — an admin turns it on) and you have not hidden it yourself (System settings › Personal › Company mode).
+
+A desk or ticket session is stamped as the organization's on the row itself when it is opened, so it is listed in company mode and never in development mode's session list — including after the organization's directory is removed by hand or the master switch is turned off, when nothing else could tell whose it was. Organizations that already existed get their sessions stamped on the runtime's next pass over their files.
+
+## Creating one
+
+Three entry points, one server call behind all of them:
+
+- **the Web App** — 新建组织 in the organization switcher: the display name comes first, and a button beside the id field asks the server to derive an id from it (the Project's default model proposes a short English snake_case id, an ASCII slug of the name answers when it cannot, and a name neither can name is filled with a dated placeholder that says under the field why and asks to be replaced — the button always leaves an id in the box); four mission examples fill the mission with one click;
+- **the CLI** — `penguin org create --org-id <id> --mission <s> [--name <s>] [--language <zh|en>] [--workspace <path>] [--ceo-budget <usd>] [--model-id <id> --provider <p>]`;
+- **the general agent** — ask any Agent carrying the `agent-company` plugin to set a company up and its `company-setup` skill takes over: one question at a time (id, name, mission, shared workspace, model, CEO budget), a summary to confirm, then that same command. It stops there — hiring, scheduling and tickets are the CEO's, after the board answers. The plugin is not preinstalled, so an Agent that has never been part of a company needs it installed first — the Plugins field of the create-agent dialog, or the Skills tab of an Agent already in the Project; a CEO and its employees carry it from the day they are hired.
+
+Ids are lowercase snake_case, 2–64 characters, starting with a letter, and by convention they say what they name: an organization id starts with `co_` and a channel id with `ch_` (`co_plugin_marketplace`, `ch_site`). The App's id proposal and the `company-setup` skill both write the prefix; the server does not enforce it, so a hand-typed id is taken as written and ids created before the convention keep working.
+
+Creation writes the organization's directory, its all-hands channel and its handbook, and exactly one employee: the **CEO**, with a monthly budget of **100 USD** unless creation named another (`ceoBudget` in the API, `--ceo-budget` on the CLI, the CEO budget field in the dialog). Budgets are compared on the cumulative line, so that one number is the whole company's cap; it lives in `org_chart.yaml` and is raised, lowered or cleared from the org chart at any time. Then the CEO's desk opens with an initialization run, which posts one proposal in the all-hands channel and stops until the board answers it.
+
+An organization also works in one **language**. It is `language` in `org_config.toml`, detected from the mission at creation — one Han character anywhere makes it `zh`, everything else `en` — unless creation names one (`--language`, `language` in the API, the Working language field in the create dialog), and changed afterwards in the organization settings. The handbook, the employee briefs (`AGENTS.md`), the CEO's initialization run and the desk session titles are written in it, and the skills tell every employee to write its channel messages, tickets, documents and reports in it too; commands, ids, file names and field names stay ASCII whatever it is. An organization created before the field has none stored and reads as whatever its mission is written in, so nothing had to be migrated.
+
+## The pieces
+
+| Piece | What it is | Where it lives |
+| --- | --- | --- |
+| Organization | one company: a name, a mission, a status, a timezone, a working language, an approval mode | `<project>/organizations/<org_id>/org_config.toml` |
+| Employees | Agents in a reporting tree rooted at the CEO — no departments, no positions; each entry carries a title, duties, a workspace and a monthly budget | `org_chart.yaml` |
+| Desk sessions | one standing session per employee, opened the moment that employee is hired: calendar events, channel mentions and people land there; it schedules work and opens ticket sessions rather than doing the work itself. The reconcile pass opens the desk of an employee that has none — one added to `org_chart.yaml` by hand, or one whose session was deleted | `desks.toml` (written by the server) |
+| Calendar | per-employee events in the scheduled-task format, minus target fields — the only periodic driver | `calendar/<agent_id>/<event>.toml` |
+| Tickets | one Markdown file each — YAML frontmatter (`title`, `status`, `owner`, `notify`, `priority`, `due`, `blocked`, `sessions`, `history`) then `## Goal`, `## Acceptance criteria`, `## Progress`, `## Result` — in a column directory that is the status. The slug is lowercase English words joined by hyphens | `tickets/<yyyy-mm>/<column>/<yyyy-mm-dd>-<slug>.md` |
+| Channels | one directory per channel: an intent file with its name, purpose and members, and one JSON line per message, split by day | `channels/<channel_id>/channel.toml`, `channels/<channel_id>/<yyyy-mm-dd>.jsonl` |
+| Shared workspace | the company's working directory; its root holds the shared inputs and is nobody's desk — the CEO works in `ceo/`, a hire lands in a sub-directory named after its Agent id unless the CEO assigns another, and a relative sub-directory is created by the server as it is assigned (an absolute path must already exist) | `workspace/` |
+| Handbook | the company's knowledge base; its `README.md` is the index every work run reads first, the other documents are listed there and read on demand | `handbook/` |
+
+The handbook is progressive loading in practice: every trigger points at `handbook/README.md`, the index names the layout, the protocols, the role conventions and every document with one line saying when it matters, and a run reads a document only when that line says so. Board decisions go in `handbook/decisions/<yyyy-mm-dd>-<slug>.md`, conventions and how-tos next to them; the Handbook page of the Web App browses, edits and creates them, and `penguin org handbook list | show | write | rm` does the same from a session. The index cannot be deleted.
+
+An employee's company skills are kept current by the server: every reconcile pass compares the `agent-company` and `agent-development` each employee carries against the plugin library and reinstalls the whole plugin wherever it has fallen behind, so a skill added to the library reaches employees already at work without anyone updating each Agent by hand. Nothing is written while the versions match, and an update that fails is recorded as an error without disturbing the rest of the pass. Hiring is unchanged: a new employee installs the current version to begin with.
+
+People and employees are named the same way everywhere: `user:<user_id>` and `agent:<agent_id>`; `@all` is every member of the channel it is written in, `system` is the scheduler.
+
+## How work flows
+
+1. **A trigger reaches a desk.** A calendar event fires, someone mentions the employee in a channel it is in, or a person talks to the desk directly — that is the whole list. The server sends the desk session one message that starts with an `[org_trigger]` block — the organization, the employee, the kind of trigger and the employee's spend against its budget — followed by the content. The Web App folds the block into a one-line banner; the Trace keeps it verbatim. **A ticket change never starts a run**: an owner assigned, a ticket blocked, a blocker closed, done, rejected are recorded and listed in the body of that employee's next calendar sweep, under `## Since your last sweep`, one line per change with the ticket, its title, what happened and the reason or blocker it carries.
+2. **The desk schedules.** Following the `company-employee` skill it reads the handbook, looks at the board, and opens a **ticket session** for each ticket it should push (`penguin org ticket start <id>`), a separate ordinary session of the same Agent in the desk's workspace. The desk never edits a ticket's files itself: the moment it would, it starts the session and lets that session do it. **A ticket's sessions are started by its owner's desk, or by a person** — an employee asking for anyone else's ticket gets `403 not_ticket_owner`. Work moves between employees by reassigning the ticket (`penguin org ticket assign <id> --owner agent:<employee>`), which the new owner's desk picks up in its next sweep; a colleague is pulled onto a ticket the other way round, its owner starting a session with `--agent-id <colleague>`. Several sessions, from several employees, may contribute to one ticket; each is recorded in the ticket's `sessions` list.
+3. **The ticket session works and writes back.** It opens with where it stands — its workspace, the rule that every reference and deliverable is named by its full path, and the ticket as filed. Before it ends it appends progress (`penguin org ticket progress`) — a plain sentence saying what was done and where, with no ids and no names, because the server writes the `history` entry that records who and when — and moves the ticket (`penguin org ticket move`). A write that claims work — a progress line, an edit of the body, a move into review — books that session as one of the ticket's contributing sessions, so its cost is split onto the ticket; accepting, closing, blocking and unblocking book nothing. Stuck — waiting for a decision, another ticket, a missing key — it blocks the ticket with a reason and who can unblock it (`penguin org ticket block`) and stops; blocked tickets are skipped by every sweep until unblocked.
+4. **Closing notifies.** A ticket reaching done or rejected notifies its `notify` list, and its owner when an employee owns it: each hears about it in its own next sweep's list. **Ticket changes are never posted in a channel** — a channel holds what people and employees say to each other, and a board that narrates itself buries the conversation. You read closures on the board and in the overview's inbox, which lists the tickets closed this period. A ticket that was waiting on it tells its owner the blocker closed.
+5. **People decide in the channels and on the board.** The CEO never takes an important decision alone: hiring plans, budgets, rejecting someone else's ticket, anything that reaches outside the organization — it posts a proposal in the all-hands channel mentioning you, and waits for your answer before acting. Only `@<employee>` and `@all` deliver a message to a desk, and only inside that channel's membership: the trigger names the channel it came from, and the employee answers there. A message that names someone the channel does not hold is refused rather than half-delivered, and a message that reaches the mention-chain limit is recorded but delivers nothing, so two employees cannot ping-pong forever. Accepting, rejecting and reviewing tickets is yours or the CEO's, as the handbook says.
+
+Budgets are monthly caps per employee for its own sessions plus every subordinate's — the CEO's budget is the whole company. At 80% a system line appears in the all-hands channel; at 100% that employee's calendar (and its subordinates') is paused until the next month or a raised budget. Mentions and direct conversations keep working, so you can always tell a paused employee what to do.
+
+## Channels
+
+Talk is partitioned like the workspace. Every organization is created with one **all-hands channel**, `default_channel`, that every employee and every Project member is in implicitly — it is where proposals, budget alerts, hires and milestones go, and where the board reads. Anyone else may open a channel per stream or per big ticket, so a thread does not drown the all-hands one.
+
+- **Creating**: any person or employee may (`penguin org channel create ch_<id>`, or the **+** beside the channel list in the App). A new channel holds only its creator; the id follows the same rule as an organization id — `ch_` by convention — and `default_channel` is reserved.
+- **Getting in**: an employee reaches a channel only when a member invites it. A person may join any channel and read every channel — the board sees everything. Only members post.
+- **Delivery**: `@agent:<id>` wakes that employee's desk only inside the channel's membership, and `@all` is that channel's members minus the sender. A message naming a non-member is refused (`mention_not_member`) rather than written and silently undelivered.
+- **Lifecycle**: any member renames a channel or changes its purpose; people archive and unarchive it, which makes it read-only and folds it away. The all-hands channel cannot be archived, left, or have its membership edited — everyone is in it by definition, and only its rendered label ("All hands") is ever shown.
+
+The `system` lines a channel carries — hires and departures, a channel created, joined, left or archived, budget warnings and pauses, a ticket blocked, done or rejected — record a structured notice beside their English text, so the App and `penguin org channel tail` render them in the reader's language and with display names. Message bodies render as Markdown in the App.
+
+Unread counts and each person's read cursor are per channel, and a hire's or a leaver's channel membership is HR's to keep straight.
+
+## The example: a plugin marketplace
+
+The mission *"Build a DeepSeek Harness plugin marketplace, promote it on social media and SEO into the top three results, and earn from paid featured slots on the home page"* plays out like this:
+
+1. You create the organization from the switcher; the CEO's desk opens with an initialization run that posts one proposal in the all-hands channel — its reading of the mission, the first tickets, the roles it wants with budgets — and waits for your answer.
+2. You confirm; the CEO hires HR and finance, then a developer and a marketer, creates `workspace/site` and `workspace/marketing`, assigns them, opens a `ch_site` channel and a `ch_marketing` channel and invites each stream's owner into its own, and schedules everyone at their own hour (daily for the builders, every three days for HR, weekly for finance).
+3. It files a parent ticket for the marketplace and children per stream: build the site, SEO to the top three, the social launch, paid featured slots. Nothing wakes the owners: each hears about its assignment in its next sweep.
+4. The next sweep opens a ticket session for the site in `workspace/site`; the marketer blocks SEO on it ("nothing to index until the site is live") and says so in the `ch_marketing` channel, where the site's own back-and-forth never lands.
+5. The site session builds, writes progress, moves the ticket to review; the CEO reviews it to done. The developer's next sweep says so, the marketer's says its blocker closed, and it verifies and unblocks SEO.
+6. Marketing works SEO and the launch from one session attached to both tickets; finance rolls the spend up per employee and per ticket — the shared session is split between the tickets it serves, the parent sums its children.
+7. Paid featured slots ship and the CEO reports to the board in the all-hands channel, mentioning you.
+
+The server test `organization-scenario.test.ts` runs exactly this story on the runtime's seams.
+
+## A mirror organization
+
+The fourth mission example is a company with no work of its own. *"Set up a company that mirrors our real company: I will give the CEO our real org chart and the CEO creates one digital twin per real employee; each twin's desk session is bound to that colleague's Feishu bot. A twin only receives its own colleague's messages by default, answers what it can on its own and relays the rest to the relevant colleague's twin, who passes it on to the real person. The CEO hires nobody on its own, schedules nothing and files no tickets; the company only relays and solves what it can."*
+
+Such a mission puts the CEO on the `company-mirror` skill instead of the standard checklist, and the company it builds is shaped differently:
+
+- **The roster comes from outside.** The CEO's initialization run asks the board for the real org chart — every person's name, title, reporting line and which bot will be theirs — and ends there. Once the board answers and confirms the roster, the CEO hires one twin per person, `--reports-to` mirroring the real line, and writes each twin's brief.
+- **Nothing recurring drives it.** No calendar events, no tickets, no per-stream channels. A twin runs when its own human writes to it through the bound bot, or when another twin `@`-mentions it.
+- **The binding is the setup's last step.** Each twin's desk session has to be bound to that colleague's bot — open the desk session and use its Remote control panel, or take the session id from `penguin org desk show <agent_id>`. An unbound twin can neither hear its human nor answer them.
+- **Relay, then write it down.** A twin answers from the handbook when it can and otherwise relays the question to the right colleague's twin, which asks its own human and passes the answer back. Everything that comes back is written into the handbook (`people/<name>.md`, `faq.md`), so the same question is answered alone next time. Relays spend the mention chain, but a person's message (through the bot or the chat page) starts a fresh one, so a question out and an answer back always fit the default `mention_chain_limit`; only twins talking among themselves run into it.
+
+## Commands
+
+Inside a desk or ticket session the `penguin org` commands already know the organization, Project, Agent and session from the environment (`PENGUIN_ORG_ID` joins the other control variables). From a shell, pass `--org-id`. See [the CLI reference](/cli#penguin-org) for every subcommand; the essentials:
+
+```text
+penguin org show # employees, board counts, spend vs budget
+penguin org hire --new-agent <id> --title <s> --reports-to <agent_id> [--workspace <sub>] [--budget <usd>]
+penguin org calendar add <name> --prompt <s> --start-at 2026-09-03T09:00:00+08:00 --period 1d # a rota: own hour, role cadence
+penguin org ticket create --title <s> --goal <s> [--owner agent:<id>] [--parent <ticket_id>] [--slug <words>]
+penguin org ticket start <ticket_id> [-m <note>] [--agent-id <employee>] # a ticket session on a ticket you own, printed as its id
+penguin org ticket progress <ticket_id> -m <text>
+penguin org ticket move <ticket_id> --to review|done|rejected [--reason <s>]
+penguin org channel create ch_site --name "Site" --purpose "Shipping the marketplace site"
+penguin org channel invite ch_site agent:<employee> # an employee reaches a channel only by invitation
+penguin org channel tail [--channel <id>] [-n <count>]
+penguin org channel send -m "@<employee> …" [--channel <id>] # default: default_channel
+penguin org finance # spend per employee (cumulative) and per ticket
+```
+
+## The pages
+
+An organization opens on its **overview**: the mission folded to one line, this period's spend against the CEO's budget, a KPI strip, and then three full-width runs — the inbox (the all-hands messages that name you or `@all`, every blocked ticket whoever it waits on, and the tickets closed this period), today's timeline, and the budget alerts. No card is a link; each carries one corner button naming the page it summarizes.
+
+The **handbook** page lists the knowledge base as an explorer tree — folders before documents at every level, collapsed until opened, walked with the arrow keys — beside the rendered document. **Finance** reads the period in three rows: the KPI panel beside the daily trend, then the spend tree and the ticket table side by side, then the period's warnings and pauses. The **calendar** and the **board** each keep one create button while they are empty, under a hint that can be dismissed for good.
+
+## Switches
+
+- **Server**: the admin's company-mode switch, off by default — a fresh server enables it under System settings › Server › Company mode. Off stops the organization scheduler (nothing fires, nothing is backfilled when it is turned on again), every organization route answers 404, and the mode switch disappears for everyone.
+- **Personal**: hides the mode switch for you only; the organizations keep running.
+- **Organization**: pausing an organization stops all of its automatic triggers; people can still open any desk and talk.
+
+**There is no delete.** An organization is turned on or off, and that is its whole lifecycle. Deleting one would throw away the only way back to its conversations, employees, desks and tickets, while a paused organization costs nothing to keep — it fires nothing, and every desk is still there to talk to.
+
+Removing the organization's directory by hand is the only way one goes away. The runtime stops seeing it on its next pass, and the App says so and offers to create another in its place. Employees are ordinary Agents and their desk and ticket sessions are ordinary sessions: both survive, and the sessions keep the mark that says they were the organization's, so they never reappear in development mode's list.
diff --git a/packages/docs/content/company-mode.zh.md b/packages/docs/content/company-mode.zh.md
new file mode 100644
index 00000000..2af4a503
--- /dev/null
+++ b/packages/docs/content/company-mode.zh.md
@@ -0,0 +1,132 @@
+---
+title: 公司模式
+description: 把一句话使命变成一家由 Agent 组成的公司——CEO 负责招募,日程驱动每个工位,工单承载工作,频道里只有 @ 才会打扰谁,预算在失控前暂停支出。
+---
+
+## 是什么
+
+**公司模式目前是内测功能**:可能有不稳定的现象,遇到问题请反馈。
+
+开发模式是一个人和一个 Agent 对话。公司模式是 Web App 的第二种工作模式:把一个 Project 内的 Agent 组织成一家**公司**,由日程驱动、以工单承载工作、在频道里沟通,自主运转数周;你只做董事会,只在需要人拍板的地方出手。你用一句话给出使命,系统只生成 CEO;CEO 招募人事、财务和使命需要的角色,划分公共工作区,为大家安排日程,开出首批工单。
+
+公司的一切都是 Project 目录下的**文件**。SQLite 只存每一轮对账都能从文件重建的缓存,以及每个用户在每个频道里的已读游标——与开发模式对 Agent State 和 Trace 的规则相同。删掉缓存什么也不会变;手工改一个文件,下一轮对账就会生效。
+
+在侧栏左上角的「开发 | 公司」控件切换模式。它在管理员总开关打开(系统设置 › 服务器 › 公司模式,**缺省关闭**,需管理员打开)且你没有自己隐藏它(系统设置 › 个人 › 公司模式)时出现。
+
+工位会话与工单会话在打开时就被标记在会话记录本身上,因此它们只列在公司模式里,从不出现在开发模式的会话列表——包括组织目录被手工删除、总开关被关掉之后,那时已经没有别的东西能说明它们属于谁。已经存在的组织,其会话会在运行时下一次扫过它的文件时补上这个标记。
+
+## 怎么创建
+
+三个入口,背后是同一个服务端调用:
+
+- **Web App**——组织切换器里的「新建组织」:显示名在前,id 字段旁的按钮请服务端据名称推导一个 id(Project 的缺省 Model 提出一个简短的英文 snake_case id,模型给不出时以名称的 ASCII slug 兜底,两条路都命名不了的名称则填入一个带日期的占位 id,并在字段下方说明原因、请你改成有含义的名字——按钮一定会在框里留下一个 id);使命字段下另有四个示例,点一下即填入;
+- **CLI**——`penguin org create --org-id <id> --mission <s> [--name <s>] [--language <zh|en>] [--workspace <path>] [--ceo-budget <usd>] [--model-id <id> --provider <p>]`;
+- **通用 Agent**——让任何装有 `agent-company` 插件的 Agent 帮你开一家公司,它的 `company-setup` Skill 接手:一次只问一个问题(id、名称、使命、公共工作区、Model、CEO 预算),确认一屏摘要,然后执行上面这条命令。它到此为止——招募、排日程和开工单是 CEO 在董事会答复之后的事。该插件不预装,所以从未进过公司的 Agent 要先装上它——新建 Agent 对话框的「插件」字段,或 Project 里既有 Agent 的技能标签页;CEO 与员工自受雇之日起就带着它。
+
+id 一律是小写 snake_case、2–64 字符、以字母开头,并按约定表明它命名的是什么:组织 id 以 `co_` 开头,频道 id 以 `ch_` 开头(`co_plugin_marketplace`、`ch_site`)。App 的 id 推导与 `company-setup` Skill 都会带上前缀;服务端并不强制,手工输入的 id 按原样接受,约定之前建立的 id 也继续有效。
+
+创建会写下组织目录、全员频道与组织手册,以及唯一一名员工:**CEO**,月预算缺省 **100 美元**,除非创建时另行指定(API 的 `ceoBudget`、CLI 的 `--ceo-budget`、对话框里的 CEO 预算字段)。预算按累计线比较,所以这一个数字就是整家公司的上限;它写在 `org_chart.yaml` 里,随时可以在组织图上调高、调低或清除。随后 CEO 的工位随初始化会话打开,在全员频道里发出一份提案,然后停下来等董事会答复。
+
+组织还有唯一的**工作语言**。它是 `org_config.toml` 的 `language`,创建时从使命判定——正文里出现任一汉字即 `zh`,否则 `en`——除非创建时指定(`--language`、API 的 `language`、创建对话框里的「工作语言」);之后可在组织设置里修改。组织手册、员工简介(`AGENTS.md`)、CEO 的初始化会话与工位会话标题都用它书写,Skill 也要求每位员工用它写频道消息、工单、文档与汇报;无论哪种语言,命令、id、文件名与字段名都保持 ASCII。该字段出现之前创建的组织没有存这一项,读作它使命本身的语言,因此无需任何迁移。
+
+## 组成部分
+
+| 部分 | 是什么 | 在哪里 |
+| --- | --- | --- |
+| 组织 | 一家公司:名称、使命、状态、时区、工作语言、审批模式 | `<project>/organizations/<org_id>/org_config.toml` |
+| 员工 | 以 CEO 为根、经汇报线连成一棵树的 Agent——没有部门与岗位;每个条目带头衔、职责、工作区和月度预算 | `org_chart.yaml` |
+| 工位会话 | 每个员工一个常设会话,招募当时就开好:日程项、频道里的提及与人都发到这里;它负责调度、发起工单会话,不亲自做工单。对账扫描会为没有工位的员工补开——手工写进 `org_chart.yaml` 的人,或者会话被删掉的人 | `desks.toml`(服务端写入) |
+| 日程 | 按员工分组的日程项,格式同定时任务、去掉目标字段——唯一的周期性驱动 | `calendar/<agent_id>/<event>.toml` |
+| 工单 | 一个工单一个 Markdown 文件——YAML frontmatter(`title`、`status`、`owner`、`notify`、`priority`、`due`、`blocked`、`sessions`、`history`)加 `## Goal`、`## Acceptance criteria`、`## Progress`、`## Result` 四节;所在列目录即状态,slug 为用连字符连接的小写英文单词 | `tickets/<yyyy-mm>/<列>/<yyyy-mm-dd>-<slug>.md` |
+| 频道 | 一个频道一个目录:一份写有名称、用途与成员的意图文件,加上一行一条消息、按天分的 JSON Lines | `channels/<channel_id>/channel.toml`、`channels/<channel_id>/<yyyy-mm-dd>.jsonl` |
+| 公共工作区 | 公司的工作目录;根目录放共享输入、不是任何人的工位——CEO 在 `ceo/` 里工作,新员工不另行指定就落在以其 Agent id 命名的子目录里;相对子目录在指定时由服务端建好,绝对路径必须已经存在 | `workspace/` |
+| 组织手册 | 公司知识库;根部 `README.md` 是每个工作轮先读的索引,其余文档在索引中列出、按需读取 | `handbook/` |
+
+手册就是渐进加载的落地:每次触发都指向 `handbook/README.md`,索引写明目录布局、协议、职责约定,以及每份文档一行「何时需要读」,工作轮只在那一行说相关时才读对应文档。董事会的决策记在 `handbook/decisions/<yyyy-mm-dd>-<slug>.md`,约定与操作指南放在旁边;Web App 的「手册」页可以浏览、编辑与新建文档,会话里用 `penguin org handbook list | show | write | rm` 做同样的事。索引不可删除。
+
+员工装着的公司 Skill 由服务端保持在当前版本:每一轮对账都会把每位员工的 `agent-company` 与 `agent-development` 与插件库比对,落后的整包重装——插件库里新增的 Skill 因此也会落到早已在岗的员工身上,不必逐个 Agent 手工更新。版本一致时不写任何文件;某位员工更新失败只记一条错误,不影响该轮的其余工作。招募时不变:新员工装的本来就是当前版本。
+
+人和员工在所有结构化字段里都用同一种记号:`user:<user_id>` 与 `agent:<agent_id>`;`@all` 表示它所在频道的全体成员,`system` 是调度器。
+
+## 工作怎么流转
+
+1. **触发到达工位。** 日程项到期、有人在它所在的频道里 @ 了这位员工、或有人直接同工位说话——就这三种。服务端向工位会话发送一条以 `[org_trigger]` 块开头的消息——组织、员工、触发种类、该员工的支出与预算——后面跟着触发内容。Web App 把块折叠成一行提示,Trace 原样保留。**工单的变化从不启动一轮运行**:指派负责人、标记阻塞、阻塞解除、完成、拒绝,都只被记录下来,列在该员工下一次日历巡检正文的 `## Since your last sweep` 一节里——一条变化一行,写明工单、标题、发生了什么,以及工单自身带的理由或阻塞方。
+2. **工位负责调度。** 员工按 `company-employee` Skill 先读手册,再看看板,为该推进的工单各发起一个**工单会话**(`penguin org ticket start <id>`)——同一 Agent 在工位工作区里的另一个普通会话。工位自己绝不动工单的文件:一旦要动,就发起工单会话交给它做。**一张工单的会话只能由它的负责人的工位、或由人发起**——员工对别人的工单发起会话会得到 `403 not_ticket_owner`。要把活交给别的员工,就改派负责人(`penguin org ticket assign <id> --owner agent:<员工>`),新负责人的工位在下一次巡检时接手;反过来,要拉同事来帮自己的工单,则由负责人用 `--agent-id <同事>` 发起会话。一个工单可以由多个会话、多名员工共同贡献,每个会话都记录在工单的 `sessions` 列表里。
+3. **工单会话做事并回写。** 它以自己的处境开场——工作区、「一切引用与交付物都写完整路径」的规则,以及工单原文。结束前追加进展(`penguin org ticket progress`)——一句大白话,写清做了什么、东西在哪,不写 id 也不写人名,因为谁写的、什么时候写的由服务端记进 `history`——并移列(`penguin org ticket move`)。声称做了活的写入——一条进展、正文编辑、移入审核中——会把该会话记为这张工单的贡献会话,其成本因此摊到工单上;接受、关闭、阻塞与解除阻塞都不记。卡住了——等人拍板、等另一个工单、缺 key——就给工单标记阻塞、写明原因与等谁解开(`penguin org ticket block`),然后停手;被阻塞的工单会被每一次巡检跳过,直到解除。
+4. **结束即通知。** 工单进入已完成或已拒绝时通知它的 `notify` 名单,负责人是员工时也通知负责人:各自在自己下一次巡检的清单里看到。**工单的变化从不发到频道里**——频道装的是人和员工彼此说的话,一块自己讲述自己的看板只会把对话淹掉。完成的事,你在看板上看,也在组织概览的 inbox 里看(它列出本周期内关闭的工单)。等着它的工单会告诉负责人「阻塞已解除」。
+5. **人在频道与看板上拍板。** CEO 不会擅自做重大决定:招募计划、预算、拒绝他人的工单、任何触及组织之外的动作,都先在全员频道里 @ 你提案,等你答复后才执行。只有 `@<员工>` 和 `@all` 会把消息投递到工位,且只在该频道的成员范围内生效:触发块写明消息来自哪个频道,员工也回到那里作答。提及了不在该频道的人,整条消息会被拒收,而不是写下去却投递不出;达到 @ 连锁上限的消息只记录不投递,两个员工不会无休止地互相 @。接受、拒绝与审核工单由你或 CEO 决定,规则写在组织手册里。
+
+预算是每个员工的月度上限,口径是本人加全部下属的会话——CEO 的预算就是整家公司。到 80% 时全员频道里出现一条系统消息;到 100% 时该员工(及其下属)的日程暂停,直到下个月或上调预算。@提及和直接对话照常,你随时可以告诉一个被暂停的员工该做什么。
+
+## 频道
+
+沟通与工作区一样是分区的。每个组织创建时自带一个**全员频道** `default_channel`,全体员工与全体 Project 成员隐式在其中——提案、预算告警、招募与里程碑都发在这里,董事会也在这里读。其余频道由大家按条线或按大工单自行新建,以免一条线的讨论淹没全员频道。
+
+- **新建**:人和员工都可以(`penguin org channel create ch_<id>`,或 App 里频道列表标题旁的 **+**)。新频道只有创建者一人;id 规则同组织 id——按约定以 `ch_` 开头——`default_channel` 为保留字。
+- **加入**:员工只能由频道成员邀请进入;人可以自行加入任何频道,也能读到所有频道——董事会看得到全部。只有成员能发言。
+- **投递**:`@agent:<id>` 只在该频道的成员范围内唤醒对方工位,`@all` 指该频道的成员(不含发送者)。提及非成员的消息会被拒收(`mention_not_member`),而不是写下去却投递不出。
+- **生命周期**:任一成员可改名称与用途;归档与取消归档只有人能做,归档后频道只读并折叠收起。全员频道不能归档、不能退出、成员不可编辑——所有人本就在其中,界面上也只显示它的固定名称「全员频道」。
+
+频道里的 `system` 消息——招募与离任,频道的创建、加入、退出与归档,预算预警与暂停,工单被阻塞、完成或否决——在英文正文之外记下一份结构化 notice,App 与 `penguin org channel tail` 因此按读者的语言、用显示名渲染它们。消息正文在 App 里按 Markdown 渲染。
+
+未读计数与每个人的已读游标都按频道分别计算;新员工与离任员工的频道成员关系由人事负责维护。
+
+## 案例:插件 Marketplace
+
+使命是「做一个 DeepSeek Harness 插件 Marketplace,通过社交媒体和 SEO 把搜索排名做到前三,靠首页限时置顶曝光位盈利」,它会这样跑:
+
+1. 你在组织切换器里新建组织;CEO 的工位随初始化会话打开,在全员频道里发出一份提案——它对使命的理解、首批工单、拟招募的角色与预算——然后等你答复。
+2. 你确认后,CEO 先招募人事与财务,再招募开发与市场,建立 `workspace/site` 和 `workspace/marketing` 并指定给各工位,开出 `ch_site` 与 `ch_marketing` 两个频道、把各条线的负责人分别邀请进去,并按角色为每个人排定各自的时刻(建站的每日、人事每三天、财务每周)。
+3. 它开出一个 Marketplace 父工单,再按条线开子工单:建站、SEO 做到前三、社交媒体发布、付费置顶位。这不会惊动任何人:各负责人在自己下一次巡检里才看到指派。
+4. 下一次巡检为建站工单在 `workspace/site` 里发起工单会话;市场把 SEO 阻塞在建站上(「站点上线前没有可索引的内容」),并在 `ch_marketing` 频道里说明——建站自身的来回讨论从不落到这里。
+5. 建站会话完成开发、回写进展、把工单移到审核中;CEO 审核后移到已完成。开发在下一次巡检里看到这件事,市场在自己的巡检里看到「阻塞已解除」,核验后解除 SEO 的阻塞。
+6. 市场用一个挂在两个工单上的会话同时推进 SEO 与发布;财务按员工与工单上卷支出——共用会话在它服务的工单之间均分,父工单汇总子工单。
+7. 付费置顶位上线,CEO 在全员频道里 @ 你向董事会汇报。
+
+服务端测试 `organization-scenario.test.ts` 在运行时接缝上完整跑通了这个故事。
+
+## 镜像组织
+
+第四个使命示例是一家没有自己的活要干的公司:「新建一个公司,作为我们现实公司的镜像:我会把现实公司的组织图告诉 CEO,CEO 为每位现实员工创建一个数字分身;每个分身的工位会话绑定到那位同事的飞书机器人。分身默认只被动接收自己同事的消息,能自己解决的就直接回答,解决不了的转给相关同事的分身、再由对方分身转给真人。CEO 不主动招募、不排日程、不开工单,公司只做传话和自主解决问题。」
+
+这样的使命会让 CEO 改按 `company-mirror` Skill 行事,而不是走标准清单;由此建起来的公司形状也不同:
+
+- **花名册来自外部。** CEO 的初始化运行向董事会索要现实公司的组织图——每个人的姓名、头衔、向谁汇报,以及哪个机器人归他——然后就结束本轮。董事会答复并确认花名册之后,CEO 才为每人招募一个分身,`--reports-to` 照搬现实汇报线,并为每个分身写下简介。
+- **没有任何周期性驱动。** 不排日程、不开工单、不按工作线开频道。分身只在两种时候运行:自己的同事通过绑定的机器人写来消息,或别的分身在频道里 `@` 它。
+- **绑定是设置的最后一步。** 每个分身的工位会话都要绑定到那位同事的机器人——打开该工位会话、用它的「远程控制」面板,或者从 `penguin org desk show <agent_id>` 取会话 id。没绑定的分身既听不见自己的同事,也回不了话。
+- **先传话,再写下来。** 分身能从手册里答就直接答,答不了就把问题转给相关同事的分身,由它去问自己的真人再把答复带回来。带回来的东西一律写进手册(`people/<姓名>.md`、`faq.md`),下次同样的问题就能自己答掉。传话会消耗提及连锁,但真人的每条消息(经机器人或对话页)都开始一条新连锁,所以一问一答的往返总在缺省的 `mention_chain_limit` 之内;只有分身之间自说自话才会撞上它。
+
+## 命令
+
+在工位会话或工单会话里,`penguin org` 命令已经从环境里知道组织、Project、Agent 与当前会话(`PENGUIN_ORG_ID` 与其他控制变量一起注入);在 shell 里则传 `--org-id`。全部子命令见 [CLI 参考](/cli#penguin-org),常用的几条:
+
+```text
+penguin org show # 员工、看板计数、支出对预算
+penguin org hire --new-agent <id> --title <s> --reports-to <agent_id> [--workspace <sub>] [--budget <usd>]
+penguin org calendar add <name> --prompt <s> --start-at 2026-09-03T09:00:00+08:00 --period 1d # 排班:各占时刻,按角色定节奏
+penguin org ticket create --title <s> --goal <s> [--owner agent:<id>] [--parent <ticket_id>] [--slug <words>]
+penguin org ticket start <ticket_id> [-m <note>] [--agent-id <员工>] # 为自己名下的工单发起工单会话,打印会话 id
+penguin org ticket progress <ticket_id> -m <text>
+penguin org ticket move <ticket_id> --to review|done|rejected [--reason <s>]
+penguin org channel create ch_site --name "Site" --purpose "推进 Marketplace 站点"
+penguin org channel invite ch_site agent:<employee> # 员工只能由成员邀请进入频道
+penguin org channel tail [--channel <id>] [-n <count>]
+penguin org channel send -m "@<employee> …" [--channel <id>] # 缺省 default_channel
+penguin org finance # 按员工(累计)与按工单的支出
+```
+
+## 页面
+
+组织打开时落在**概览**:折成一行的使命、本期支出对照 CEO 预算、一条 KPI 带,然后是三段通栏——收件箱(全员频道里 @ 我或 `@all` 的消息、全部被阻塞的工单——无论它在等谁、以及本期内关闭的工单)、今日日程、告警。卡片本身都不是链接,而是各带一个角上的按钮,写明跳到哪一页。
+
+**手册**页把知识库画成资源管理器式的树——每一层文件夹在文档之前,默认收起,可用方向键走——正文渲染在旁边。**财务**页把本期分成三行:KPI 面板与逐日趋势并列,然后是支出树与工单表左右分列,最后是本期的预警与暂停。**日历**与**看板**在空态下只留一个新建按钮,下方的说明可以永久关掉。
+
+## 开关
+
+- **服务器**:管理员的公司模式总开关,缺省关闭——新装的服务器要先在系统设置 › 服务器 › 公司模式里打开它。关闭即停止组织调度器(不再触发任何东西,重新打开也不补发),所有组织路由回 404,模式切换对所有人消失。
+- **个人**:只对你自己隐藏模式切换,组织照常运转。
+- **组织**:暂停一个组织会停止它的一切自动触发;人仍可打开任一工位直接对话。
+
+**没有删除。** 组织只有开与关,这就是它的全部生命周期。删除会连回到它的对话、员工、工位与工单的路一并丢掉;而暂停着的组织并不占用什么——它不触发任何东西,每个工位也仍在那里可以对话。
+
+手工删掉组织目录是组织唯一的消失方式。运行时在下一轮对账时就不再看见它,App 会如实说明并给出新建一个的入口。员工就是普通 Agent,工位会话与工单会话就是普通会话:两者都保留,且会话上「属于该组织」的标记仍在,因此它们不会回到开发模式的会话列表里。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 4ad3a89f..8b7e9120 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -251,12 +251,53 @@ Benchmarks hang off the Project, not off an Agent: one Benchmark evaluates as ma
| GET | /benchmarks/:benchmarkId/cases/:caseId/files | Browse one case's `statement/`; add `/rubric` before `/files` for the rubric side |
| GET | /benchmarks/:benchmarkId/cases/:caseId/files/content | Read one file from that material (`?path=`, `?preview=1`, `?download=1`), with the same inline hardening as Workspace files |
+### Organizations (company mode)
+
+All paths below are under `/api/projects/:projectId/organizations`. Every route answers 404 while the admin's company-mode switch is off. Any Project member reads and writes. There is no route that deletes an organization: `status` (`active` / `paused`) is the off switch, and a paused organization keeps its conversations, employees, desks and tickets. Write bodies may carry `agentId` and `sessionId` — the calling employee and the calling session, which the CLI fills from `PENGUIN_AGENT_ID` and `PENGUIN_SESSION_ID` — so the file records the employee rather than the token's user; `agentId` wins when it names an employee, the session answers otherwise. The channel reads and the member DELETE, which have no body, take the same pair as `?agentId=` / `?sessionId=`. Both are honoured only for a request carrying the local API token, which is how an employee is answered as itself instead of as the signed-in person. See [Company Mode](/company-mode) for the files behind these routes.
+
+| 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` |
+| PATCH / DELETE | /:orgId/employees/:agentId | Change title, manager, workspace (created and validated as on hire), budget (`null` clears), duties, model / leave (subordinates move up to the manager; the CEO cannot leave) |
+| GET / POST | /:orgId/employees/:agentId/desk | The desk session (opened when missing) / a renewed desk session |
+| GET / PUT | /:orgId/handbook | The handbook index (`handbook/README.md`) |
+| GET | /:orgId/handbook/files | The knowledge-base files, the index first |
+| GET / PUT / DELETE | /:orgId/handbook/files/\<path\> | One document by relative path; the index cannot be deleted |
+| GET / POST | /:orgId/calendar | Every employee's events with their run state / create: `{agentId, name, prompt, enabled, startAt, period?, endAt?, title?}` → the stored event plus advisory `warnings`, one line each: another employee's recurring event on the same start minute, a second recurring event for the same employee on the same period, a recurring event started at `now`. The write is never refused for them |
+| GET / PUT / DELETE | /:orgId/calendar/:agentId/:name | One event; `PUT` answers as the create above does, `warnings` included |
+| GET / POST | /:orgId/tickets | The board by column (plus unparsable files) / create: `{title, goal?, acceptanceCriteria?, body?, owner?, parent?, notify?, priority?, due?, slug?}`. `owner` is the ONE responsible principal — an employee (a bare Agent id or `agent:<id>`) or a Project member (`user:<id>`) — and defaults to the caller; when `notify` is absent it becomes the whole `notify`, but only when it is an employee, so a person is not @-mentioned for a ticket they own. Who filed it is the `created` entry of the ticket's `history`. The id's slug comes from `slug` when given (lowercase English words joined by hyphens, 400 otherwise), else from the title; a title that yields fewer than two words is put to the Project's model, and 400 `slug_required` asks the caller to name it when that fails too |
+| GET / PUT | /:orgId/tickets/:ticketId | Ticket detail (frontmatter fields, prose sections, `progress` as plain sentences, `history`, contributing sessions, children, rolled-up cost) / update `{title?, owner?, parent?, notify?, priority?, due?, goal?, acceptanceCriteria?, result?}`. `owner` takes no `null`: a ticket always has one, so it is reassigned, never cleared; `parent` and `due` still take `null` to clear |
+| POST | /:orgId/tickets/:ticketId/move | `{status, reason?}` — moving into `rejected` needs a reason |
+| POST | /:orgId/tickets/:ticketId/block | `{reason, by?}` — `by` is a ticket id or a principal; the ticket stays in its column |
+| POST | /:orgId/tickets/:ticketId/unblock | Clears the block |
+| POST | /:orgId/tickets/:ticketId/progress | `{text}` — appends one plain sentence to `## Progress`; who wrote it and when is the `progress` entry appended to `history` |
+| POST | /:orgId/tickets/:ticketId/start | `{agentId?, message?, workspace?}` → 202 `{sessionId}`: a ticket session of that employee, recorded in the ticket's `sessions` and `history`. This is the one route whose `agentId` is not an identity claim — it names the employee the session runs as. Who may start one depends on the caller: a person may start any ticket's session (`agentId` names the employee, defaulting to the owner), while a caller writing as an employee — a desk or ticket session quoting its own `sessionId` — may start one only for a ticket it OWNS, and gets 403 `not_ticket_owner` for anyone else's or for a ticket with no employee owner. An owner may still pass `agentId` to enlist a colleague on its own ticket |
+| POST | /:orgId/tickets/:ticketId/attach | `{sessionId}` — records an existing session as contributing |
+| GET / POST | /:orgId/channels | Every channel the caller may see (people: all of them; an employee: the ones it is in), `default_channel` first / open one: `{channelId, name?, purpose?}` → 201, holding only its creator (409 when the id is taken) |
+| GET / PATCH | /:orgId/channels/:channelId | The channel and its members / rename, change `purpose`, set `archived` (people only, never on `default_channel`) |
+| POST | /:orgId/channels/:channelId/members | `{principal}` — any member invites an `agent:<id>` employee or a `user:<id>` Project member; a person may add itself, an employee may not. Adding an existing member is a no-op 201 |
+| DELETE | /:orgId/channels/:channelId/members/:principal | Remove a member: anyone removes itself, a person removes anyone, an employee only itself; removing a non-member is a no-op 204 |
+| GET / POST | /:orgId/channels/:channelId/messages | A day's messages (`?date=yyyy-mm-dd`, default today in the organization's timezone) with the caller's unread and mention counts / send `{text, refs?}`; mentions are resolved from the text and must all be members. A `system` line also carries `notice` — a `kind` (`employee_joined`, `employee_left`, `channel_created`, `channel_archived`, `channel_unarchived`, `channel_joined`, `channel_invited`, `channel_left`, `channel_removed`, `budget_warned`, `budget_paused`, and the legacy `ticket_blocked`, `ticket_done`, `ticket_rejected` — nothing writes those three any more, they are kept so lines already on disk still render) and string `params` — beside its English `text`, so a client renders the sentence in the reader's language; lines written before the field have none |
+| POST | /:orgId/channels/:channelId/read | `{upTo}` — the caller's read cursor in this channel |
+| GET | /:orgId/finance | Spend per employee (own and cumulative along the reporting line), per ticket (rolled up along `Parent`), daily trend, alerts; `?period=yyyy-mm` |
+| GET | /:orgId/sessions | The organization's desk sessions and ticket sessions grouped by ticket |
+
+Channel errors: `channel_not_found` (404 — also for an id no channel could carry), `channel_exists` (409), `channel_archived` (409 — an archived channel takes no writes until it is unarchived), `not_a_member` (403 — reading, posting or inviting without membership, and any people-only action attempted by an employee), `all_hands_immutable` (400 — archiving `default_channel` or editing its membership), `mention_not_member` (400 — the message names principals the channel does not hold; nothing is written), `invalid_principal` (400).
+
+User-level events on `GET /api/events`: `org_run` (a work run or ticket session started), `org_channel` (a new message, with its `channelId` and mentions), `org_ticket` (a ticket's status, owner, block or sessions changed), `org_budget` (warned / paused / resumed).
+
+A desk session is driven by three things only: a calendar event, a channel `@`-mention, and a person talking to it (the CEO's creation-time initialization run is the one exception). **A ticket write starts no run.** `move`, `block`, `unblock` and an owner set through `PUT /:orgId/tickets/:ticketId` are recorded — in the ticket file, in the all-hands `system` line where the change has one, and as an `org_ticket` event — and queued for the employees they concern; the next calendar event of each carries them in its body under `## Since your last sweep`, one line per change. A queue survives a paused organization or employee and is delivered by the sweep that eventually fires; an employee that leaves takes its undelivered lines with it.
+
### Session Creation and Directory Browsing
| Method | Path | Description |
| --- | --- | --- |
| GET | /agents/:agentId/sessions | List Sessions (including run state); every row is listed whichever client created it |
-| POST | /agents/:agentId/sessions | Create a Session: `{modelId?, provider?, workspace?, approvalMode?, client?, source?}` → 201. `client` is the creating-client hint stored on the row (`"cli"` from the CLI; default `"web"`) — informational provenance, never a list filter; `source` accepts only `"benchmark"` (a Benchmark evaluation or optimization), since `subagent` and `schedule` are set by the server itself |
+| POST | /agents/:agentId/sessions | Create a Session: `{modelId?, provider?, workspace?, approvalMode?, client?, source?}` → 201. `client` is the creating-client hint stored on the row (`"cli"` from the CLI; default `"web"`) — informational provenance, never a list filter; `source` accepts only `"benchmark"` (a Benchmark evaluation or optimization), since `subagent` and `schedule` are set by the server itself `org` is the value the server itself writes for an organization's desk and ticket sessions (company mode); a client cannot pass it. |
| GET | /dirs?path= | Server-side directory browser (backs the Workspace picker) |
On Session creation, `modelId` and `provider` are both-or-neither: send the complete pair to pick a model, or omit both to take the Project's default model — one without the other is a 400. The Workspace defaults to an auto-created temporary workspace, and the approval mode defaults to `allow-all`.
@@ -282,7 +323,7 @@ The paths below omit the `/api/sessions/:sessionId` prefix. For the storage mode
| Method | Path | Description |
| --- | --- | --- |
-| GET | / | Session info (the single-session GET additionally carries `tracePath`, the absolute path of the latest Trace file; list rows omit it) |
+| GET | / | Session info (the single-session GET additionally carries `tracePath`, the absolute path of the latest Trace file; list rows omit it). `orgId` marks a Session the company-mode caches own — a desk session, or a session contributing to one of that organization's tickets — and is absent on every ordinary Session; the list route stamps it too |
| PATCH | / | Update: `{approvalMode?, thinkingLevel?, archived?, title?}`. `thinkingLevel` pins the level on this Session (durable) and applies from its very next LLM request — the thinking level is soft-limited: changeable mid-context, at the cost of the provider's cached context, which is why the picker advises compacting first — and it comes back as `SessionInfo.thinkingLevel` (absent = never pinned: the Agent config applies) |
| DELETE | / | Delete the Session (along with its Traces and scratch files) |
| GET | /messages | Without parameters, the full OmniMessage history; `tailLimit=n` or `before=<cursor>&limit=n` reads a Task-aligned window instead (the bundled Web App opens a conversation on its latest 50 turns and backfills on scroll), and the response then carries `page` (the next-page cursor `before`, the turns before the window `earlierTurns`, and the cumulative `prior` stats). While a Task runs the response also carries `live` (the in-progress stream tail, see below) |
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 7b86a22d..cd70bd82 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -251,12 +251,53 @@ Benchmark 挂在 Project 上而非某个 Agent 上:一个 Benchmark 评测过
| GET | /benchmarks/:benchmarkId/cases/:caseId/files | 浏览某道题的 `statement/`;在 `/files` 前加 `/rubric` 即评分细则一侧 |
| GET | /benchmarks/:benchmarkId/cases/:caseId/files/content | 读取该材料下的单个文件(`?path=`、`?preview=1`、`?download=1`),内联渲染的加固规则与 Workspace 文件一致 |
+### 组织(公司模式)
+
+以下路径都在 `/api/projects/:projectId/organizations` 之下。管理员的公司模式总开关关闭时所有路由回 404。Project 成员可读写。没有删除组织的路由:`status`(`active` / `paused`)就是它的开关,暂停的组织仍保留其对话、员工、工位与工单。写入体可带 `agentId` 与 `sessionId`——调用方所在的员工与会话,CLI 从 `PENGUIN_AGENT_ID` 与 `PENGUIN_SESSION_ID` 填入——文件里记录的就是该员工而不是 token 的用户;`agentId` 指向某名员工时以它为准,否则看会话。频道的读取与成员 DELETE 没有请求体,同样两项改由 `?agentId=` / `?sessionId=` 传入。两者都仅对携带本机 API token 的请求生效,员工因此被当作它自己而不是登录的那个人来应答。这些路由背后的文件见[公司模式](/company-mode)。
+
+| 方法 | 路径 | 说明 |
+| --- | --- | --- |
+| 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` |
+| PATCH / DELETE | /:orgId/employees/:agentId | 改头衔、汇报对象、工作区(校验与创建同招募)、预算(`null` 清除)、职责、Model / 离任(下属上移到其上级;CEO 不可离任) |
+| GET / POST | /:orgId/employees/:agentId/desk | 工位会话(无则创建)/ 换新的工位会话 |
+| GET / PUT | /:orgId/handbook | 组织手册索引(`handbook/README.md`) |
+| GET | /:orgId/handbook/files | 知识库文件清单,索引在前 |
+| GET / PUT / DELETE | /:orgId/handbook/files/\<path\> | 按相对路径读写、删除一份文档;索引不可删 |
+| GET / POST | /:orgId/calendar | 全员日程项及运行状态 / 新建:`{agentId, name, prompt, enabled, startAt, period?, endAt?, title?}` → 除写下的事件外还带一组建议性的 `warnings`(每条一行):同一起始分钟上已有另一位员工的常设日程项、同一员工已有同周期的常设日程项、常设日程项以 `now` 起算。写入绝不因此被拒 |
+| GET / PUT / DELETE | /:orgId/calendar/:agentId/:name | 单个日程项;`PUT` 的响应与上面的新建相同,同样带 `warnings` |
+| GET / POST | /:orgId/tickets | 按列的看板(含无法解析的文件)/ 新建:`{title, goal?, acceptanceCriteria?, body?, owner?, parent?, notify?, priority?, due?, slug?}`。`owner` 是这张工单**唯一**的责任人——本组织的员工(裸 Agent id 或 `agent:<id>`)或 Project 成员(`user:<id>`),缺省为调用方;没有 `notify` 时它成为整个 `notify`,但仅限它是员工时,人不会因为自己名下的工单被 @。谁创建的记在工单 `history` 的 `created` 条目里。id 的 slug 优先取 `slug`(小写英文单词以连字符连接,否则 400),否则由标题推导;标题推不出两个词时交给 Project 的模型来取,模型也取不出则回 400 `slug_required`,请调用方自己取 |
+| GET / PUT | /:orgId/tickets/:ticketId | 工单详情(frontmatter 字段、正文各节、`progress` 为纯句子、`history`、贡献会话、子工单、上卷成本)/ 更新 `{title?, owner?, parent?, notify?, priority?, due?, goal?, acceptanceCriteria?, result?}`。`owner` 不接受 `null`:工单永远有负责人,只能改派、不能清空;`parent` 与 `due` 仍可传 `null` 清除 |
+| POST | /:orgId/tickets/:ticketId/move | `{status, reason?}`——移入 `rejected` 须给理由 |
+| POST | /:orgId/tickets/:ticketId/block | `{reason, by?}`——`by` 为工单 id 或主体;工单留在所在列 |
+| POST | /:orgId/tickets/:ticketId/unblock | 解除阻塞 |
+| POST | /:orgId/tickets/:ticketId/progress | `{text}`——往 `## Progress` 追加一句大白话;谁写的、什么时候写的记为 `history` 里的一条 `progress` |
+| POST | /:orgId/tickets/:ticketId/start | `{agentId?, message?, workspace?}` → 202 `{sessionId}`:该员工的一个工单会话,记入工单的 `sessions` 与 `history`。本路由是唯一一个 `agentId` 不表示调用方身份的路由——它指的是这个会话以谁的身份运行。谁能发起取决于调用方:人可以为任何工单发起(`agentId` 指定员工,缺省取负责人);而以员工身份写入的调用方——工位会话或工单会话在请求体里带上自己的 `sessionId`——只能为**自己名下**的工单发起,对别人的工单或没有员工负责人的工单一律回 403 `not_ticket_owner`。负责人仍可用 `agentId` 把同事拉进自己名下的工单 |
+| POST | /:orgId/tickets/:ticketId/attach | `{sessionId}`——把既有会话记为贡献会话 |
+| GET / POST | /:orgId/channels | 调用方可见的全部频道(人:全部;员工:自己所在的),`default_channel` 在前 / 新建:`{channelId, name?, purpose?}` → 201,初始成员只有创建者(id 被占用则 409) |
+| GET / PATCH | /:orgId/channels/:channelId | 频道及其成员 / 改名称、改 `purpose`、设 `archived`(仅限人,且 `default_channel` 不可归档) |
+| POST | /:orgId/channels/:channelId/members | `{principal}`——任一成员可邀请 `agent:<id>` 员工或 `user:<id>` Project 成员;人可以自行加入,员工不可。重复添加已有成员为幂等的 201 |
+| DELETE | /:orgId/channels/:channelId/members/:principal | 移出成员:任何人都可移出自己,人可移出任何人,员工只能移出自己;移出非成员为幂等的 204 |
+| GET / POST | /:orgId/channels/:channelId/messages | 某一天的消息(`?date=yyyy-mm-dd`,缺省为组织时区的今天)及调用方的未读与 @ 计数 / 发送 `{text, refs?}`;@ 从正文解析,且必须都是频道成员。`system` 消息在英文 `text` 之外还带 `notice`——一个 `kind`(`employee_joined`、`employee_left`、`channel_created`、`channel_archived`、`channel_unarchived`、`channel_joined`、`channel_invited`、`channel_left`、`channel_removed`、`budget_warned`、`budget_paused`,以及遗留的 `ticket_blocked`、`ticket_done`、`ticket_rejected`——这三种已不再写入,保留只是为了让磁盘上已有的行仍能渲染)与一组字符串 `params`——客户端据此按读者的语言渲染该句;该字段出现之前写下的消息没有它 |
+| POST | /:orgId/channels/:channelId/read | `{upTo}`——调用方在该频道的已读游标 |
+| GET | /:orgId/finance | 按员工(本人与沿汇报线累计)、按工单(沿 `Parent` 上卷)的支出、逐日趋势与告警;`?period=yyyy-mm` |
+| GET | /:orgId/sessions | 组织的工位会话与按工单分组的工单会话 |
+
+频道相关错误:`channel_not_found`(404,频道 id 不合法时同样如此)、`channel_exists`(409)、`channel_archived`(409,归档频道在取消归档前不接受写入)、`not_a_member`(403,无成员身份的读取、发言与邀请,以及员工尝试仅限人的操作)、`all_hands_immutable`(400,归档 `default_channel` 或编辑其成员)、`mention_not_member`(400,消息提及了不在该频道的对象,整条不写入)、`invalid_principal`(400)。
+
+`GET /api/events` 上的用户级事件:`org_run`(工作轮或工单会话开始)、`org_channel`(新消息,带 `channelId` 与 @ 名单)、`org_ticket`(工单的状态、负责人、阻塞或会话变化)、`org_budget`(告警 / 暂停 / 解除)。
+
+驱动工位会话的只有三样:日程项、频道里的 @ 提及、直接同它说话的人(CEO 创建时的初始化运行是唯一例外)。**工单写入不会启动任何一轮运行。** `move`、`block`、`unblock` 以及经 `PUT /:orgId/tickets/:ticketId` 设定负责人,都只被记录——写进工单文件、该变化在全员频道有系统消息时写进全员频道、并发出 `org_ticket` 事件——同时排入相关员工的队列;每人的下一条日程项在正文的 `## Since your last sweep` 一节里带上它们,一条变化一行。组织或员工被暂停期间队列照常积累,由此后真正触发的那次巡检送达;员工离职时,尚未送达的行随之删除。
+
### Session 创建与目录浏览
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| GET | /agents/:agentId/sessions | Session 列表(含运行状态);无论由哪个客户端创建,所有行都会列出 |
-| POST | /agents/:agentId/sessions | 创建 Session:`{modelId?, provider?, workspace?, approvalMode?, client?, source?}` → 201。`client` 是存入索引行的创建客户端标记(CLI 传 `"cli"`,缺省 `"web"`)——仅作来源信息,绝不参与列表过滤;`source` 只接受 `"benchmark"`(Benchmark 评估或优化创建),`subagent` 与 `schedule` 由服务端自己写入 |
+| POST | /agents/:agentId/sessions | 创建 Session:`{modelId?, provider?, workspace?, approvalMode?, client?, source?}` → 201。`client` 是存入索引行的创建客户端标记(CLI 传 `"cli"`,缺省 `"web"`)——仅作来源信息,绝不参与列表过滤;`source` 只接受 `"benchmark"`(Benchmark 评估或优化创建),`subagent` 与 `schedule` 由服务端自己写入 `org` 是服务端为组织的工位与工单会话(公司模式)自行写入的值,客户端不能传。 |
| GET | /dirs?path= | 服务器端目录浏览(Workspace 选择器数据源) |
创建 Session 时,`modelId` 与 `provider` 要么成对给出、要么都不给:给出完整二元组即指定模型,两个都省略则取 Project 默认模型,只给一个返回 400。Workspace 默认自动创建临时工作区,审批模式默认 `allow-all`。
@@ -282,7 +323,7 @@ Trace 下载对任意成员开放;导入仅限 owner(同 Agent 快照导入
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | / | Session 信息(单会话 GET 额外携带 `tracePath`:最新 Trace 文件的绝对路径;列表行不含) |
+| GET | / | Session 信息(单会话 GET 额外携带 `tracePath`:最新 Trace 文件的绝对路径;列表行不含)。`orgId` 标出被公司模式缓存认领的会话——工位会话,或参与该组织某个工单的会话——普通会话没有这个字段;列表路由同样带上它 |
| PATCH | / | 更新:`{approvalMode?, thinkingLevel?, archived?, title?}`。`thinkingLevel` 将思考等级钉在该 Session 上并持久化,自下一次 LLM 请求起生效——思考等级是软限制参数:允许中途更换,代价是提供商的缓存失效,因此选择器会建议先压缩;读取时由 `SessionInfo.thinkingLevel` 返回(缺省即从未钉住:按 Agent 配置生效) |
| DELETE | / | 删除 Session(连同 Trace 与暂存文件) |
| GET | /messages | 无参数时返回完整 OmniMessage 历史;`tailLimit=n` 或 `before=<游标>&limit=n` 改为读取一个按 Task 切分的窗口(自带 Web App 打开对话只读最近 50 轮,滚动到顶部再续载),此时响应携带 `page`(下一页游标 `before`、窗口前的轮数 `earlierTurns` 与累计统计 `prior`)。Task 运行期间响应额外携带 `live`(进行中的流式尾部,见下) |
diff --git a/packages/docs/content/skills.en.md b/packages/docs/content/skills.en.md
index 526d8f51..02329a52 100644
--- a/packages/docs/content/skills.en.md
+++ b/packages/docs/content/skills.en.md
@@ -22,7 +22,7 @@ plugins/<plugin>/
| `description` / `description_zh` | One-line description (English required) |
| `short_description` / `short_description_zh` | Card labels (optional; the full description stands in) |
| `version` | `YYYY.MM.DD.N` — the date plus a sequence number for that day |
-| `category` | One of `office-productivity`, `software-development`, `ai-app-development`; missing or unknown lands in "Other" |
+| `category` | One of `office-productivity`, `software-development`, `ai-app-development`, `agent-company`; missing or unknown lands in "Other" |
| `preinstall` | Optional; `false` keeps the plugin out of `default_agent`'s preinstalled set — install it manually from the library |
| `hooks.stop` / `hooks.pre_tool_use` / `hooks.user_prompt` | The hook package's commands per [hook point](/agent-loop#stop-hooks): `[{ "command": "stop.mjs", "timeout": 60 }]`, paths relative to `hooks/`, timeout in seconds |
@@ -106,6 +106,7 @@ The built-in plugins, by category (`PLUGIN_CATEGORIES` in `packages/core/src/plu
| | `model-development` | Model development on your own hardware — three skills: `llamafactory` (fine-tune), `ollama` (run local models) and `vllm` (serve behind an OpenAI-compatible endpoint) |
| | `skill-porting` | Port skills from external sources — plugin marketplaces, skills.sh registries, GitHub repos or local folders — into the agent after review and normalization |
| | `agent-tuning` | The tuning loop as four skills: `agent-initialization` (set an agent up from a requirement), `benchmark-design` (design and calibrate a capability Benchmark), `agent-evaluation` (execute and score one isolated Case) and `agent-optimization` (improve the agent from measured results) |
+| Agent Company | `agent-company` | The whole toolkit of [company mode](/company-mode) — six skills: `company-setup` (create an organization with the user: one question at a time, a summary to confirm, then `penguin org create` — it never hires or files tickets), `company-employee` (the protocol every desk and ticket session follows: trigger blocks, the ticket board, blocking, channel etiquette, budgets), `company-ceo` (mission to tickets, hiring, workspace partitioning, review, reporting to the board), `company-hr` (calendar coverage, hiring and offboarding, evaluation), `company-finance` (budgets, the daily audit, alerts and pauses) and `company-mirror` (a company of digital twins: one twin per real colleague, bound to that colleague's bot, relaying instead of filing tickets) (not preinstalled: the organization installs it when it creates the CEO and hires employees, and an Agent that should be able to create one installs it from the library) |
## Writing and optimizing Skills
diff --git a/packages/docs/content/skills.zh.md b/packages/docs/content/skills.zh.md
index 5e93bce8..65312b3b 100644
--- a/packages/docs/content/skills.zh.md
+++ b/packages/docs/content/skills.zh.md
@@ -22,7 +22,7 @@ plugins/<plugin>/
| `description` / `description_zh` | 单行描述(英文必填) |
| `short_description` / `short_description_zh` | 卡片短标签(可选;缺省显示完整描述) |
| `version` | `YYYY.MM.DD.N`——日期加当日序号 |
-| `category` | `office-productivity`、`software-development`、`ai-app-development` 之一;缺失或未知归入「其他」 |
+| `category` | `office-productivity`、`software-development`、`ai-app-development`、`agent-company` 之一;缺失或未知归入「其他」 |
| `preinstall` | 可选;`false` 表示不进入 `default_agent` 的预装集合,仅可从插件库手动安装 |
| `hooks.stop` / `hooks.pre_tool_use` / `hooks.user_prompt` | 钩子包在各[钩子点](/agent-loop#stop-hook)的命令:`[{ "command": "stop.mjs", "timeout": 60 }]`,路径相对 `hooks/`,超时以秒计 |
@@ -106,6 +106,7 @@ Skill 采用「先索引、后正文」的设计:系统 Prompt 经 `{{SKILL_ME
| | `model-development` | 在自己的硬件上做模型开发——三个 Skill:`llamafactory`(微调)、`ollama`(运行本地模型)、`vllm`(以 OpenAI 兼容端点部署服务) |
| | `skill-porting` | 从外部来源移植 Skill——插件市场、skills.sh 注册表、GitHub 仓库或本地目录——经审阅与规范化后装入 Agent |
| | `agent-tuning` | 调优闭环的四个 Skill:`agent-initialization`(依据需求初始化 Agent)、`benchmark-design`(设计并校准能力 Benchmark)、`agent-evaluation`(隔离执行并评分单个 Case)、`agent-optimization`(根据测得结果改进 Agent) |
+| Agent 公司 | `agent-company` | [公司模式](/company-mode)的整套工具箱——六个 Skill:`company-setup`(与用户一起创建组织:一次只问一个问题,确认摘要后执行 `penguin org create`;它自己不招募、不建工单)、`company-employee`(每个工位会话与工单会话都遵循的协议:触发块、工单看板、阻塞、频道礼仪、预算)、`company-ceo`(使命拆解为工单、招募、划分工作区、审核、向董事会汇报)、`company-hr`(保证日程有安排、招募与离任、评估)、`company-finance`(预算、每日巡检、告警与暂停处置)、`company-mirror`(数字分身公司:为每位现实同事建一个分身、绑定到他的机器人、只传话不开工单)(不预装:组织创建 CEO 与招募员工时自行安装;想让某个 Agent 能创建组织,从技能库装上它即可) |
## 编写与优化
diff --git a/packages/docs/src/lib/nav.ts b/packages/docs/src/lib/nav.ts
index 1e23760e..d48cb6fc 100644
--- a/packages/docs/src/lib/nav.ts
+++ b/packages/docs/src/lib/nav.ts
@@ -40,7 +40,7 @@ export const DOCS_NAV: DocsSectionDef[] = [
},
],
},
- { id: "guides", pages: pages("web-app", "goal-mode", "self-improvement") },
+ { id: "guides", pages: pages("web-app", "goal-mode", "company-mode", "self-improvement") },
{
id: "design",
pages: pages(
diff --git a/packages/landing/src/lib/strings-en.ts b/packages/landing/src/lib/strings-en.ts
index ea38de11..9c6885b6 100644
--- a/packages/landing/src/lib/strings-en.ts
+++ b/packages/landing/src/lib/strings-en.ts
@@ -459,7 +459,7 @@ penguin run --message "Analyze data.csv and summarize quarterly sales"`,
skills: {
eyebrow: "Built-in Skills",
title: "The built-in Skill library at a glance",
- subtitle: "Three Skill groups out of the box — agents can write and optimize their own, too.",
+ subtitle: "Four Skill groups out of the box — agents can write and optimize their own, too.",
groups: [
{
title: "Office Productivity",
@@ -486,6 +486,17 @@ penguin run --message "Analyze data.csv and summarize quarterly sales"`,
"agent-optimization",
],
},
+ {
+ title: "Agent Company",
+ skills: [
+ "company-setup",
+ "company-employee",
+ "company-ceo",
+ "company-hr",
+ "company-finance",
+ "company-mirror",
+ ],
+ },
],
},
diff --git a/packages/landing/src/lib/strings.ts b/packages/landing/src/lib/strings.ts
index eaa59e6c..3126f80d 100644
--- a/packages/landing/src/lib/strings.ts
+++ b/packages/landing/src/lib/strings.ts
@@ -440,7 +440,7 @@ penguin run --message "分析 data.csv,输出季度销售额"`,
skills: {
eyebrow: "内置 Skill",
title: "内置 Skill 库一览",
- subtitle: "三组 Skill 开箱即用,Agent 也能编写并优化自己的 Skill。",
+ subtitle: "四组 Skill 开箱即用,Agent 也能编写并优化自己的 Skill。",
groups: [
{ title: "办公效率", skills: ["data-analysis", "firecrawl", "bento-slides", "humanizer"] },
{
@@ -464,6 +464,17 @@ penguin run --message "分析 data.csv,输出季度销售额"`,
"agent-optimization",
],
},
+ {
+ title: "Agent 公司",
+ skills: [
+ "company-setup",
+ "company-employee",
+ "company-ceo",
+ "company-hr",
+ "company-finance",
+ "company-mirror",
+ ],
+ },
],
},
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index eb188b8d..7ec56ec0 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -141,6 +141,12 @@ export interface MeResponse {
* just an admin's.
*/
uploadLimits: UploadLimits;
+ /**
+ * Whether company mode is enabled server-wide (the admin switch in server settings, default
+ * on). Off hides the mode switch in every client and 404s every organization route; the
+ * user's own preference (`UiPrefs.companyMode`) only hides the switch for that user.
+ */
+ companyMode: boolean;
}
/**
@@ -241,6 +247,13 @@ export interface ServerSettings {
* image and the JSON framing), which is why raising it needs no separate setting.
*/
attachmentTotalMb: number;
+ /**
+ * Company mode master switch (default on). Off stops the organization scheduler (no
+ * calendar event or chat mention fires, nothing is backfilled when it is turned on again),
+ * every `/api/projects/:projectId/organizations` route answers 404, and `GET /api/me`
+ * reports it so clients hide the mode switch. Organizations on disk are untouched.
+ */
+ companyMode: boolean;
}
export interface ServerSettingsResponse {
@@ -251,6 +264,8 @@ export interface ServerSettingsResponse {
export interface ServerSettingsUpdateRequest {
proxyForApp?: boolean;
proxyForAgent?: boolean;
+ /** Company mode master switch; see `ServerSettings.companyMode`. */
+ companyMode?: boolean;
/**
* New proxy address. Accepted forms: any proxy URL undici's dispatcher takes —
* `http://`, `https://`, `socks5://` / `socks://`, credentials allowed — or bare
@@ -364,6 +379,12 @@ export interface UiPrefs {
* known key holding user-authored text rather than a flag or an id.
*/
draftShortcuts?: DraftShortcut[];
+ /** Personal company-mode switch (default on): off only hides this user's mode switch; organizations keep running. */
+ companyMode?: boolean;
+ /** The work mode the user last chose in the shell: development (default) or company. */
+ workMode?: "dev" | "company";
+ /** The organization last opened in company mode, as `<projectId>/<orgId>`. */
+ lastOrgKey?: string;
[key: string]: unknown;
}
@@ -1348,6 +1369,25 @@ export interface SessionInfo {
tracePath?: string;
/** Present when the Session has an ENABLED messaging binding: its channel (the sidebar row's per-channel indicator). */
messagingChannel?: MessagingChannel;
+ /**
+ * Company mode: the organization that owns this Session — a desk session of one of its
+ * employees, or a session contributing to one of its tickets — read from the organization
+ * caches. Absent for every ordinary Session. Development mode's list and its time buckets
+ * hide every row that carries it (only while company mode is available to that user: it is
+ * stamped either way, and company mode is what lists these Sessions instead), and the
+ * company sidebar's 工位 / 工单会话 groups are where they are listed.
+ */
+ orgId?: string;
+ /**
+ * Which client opened the Session, as stored on the index row: "cli" from the CLI (a
+ * Session adopted from a legacy CLI-direct Trace included), "org" from the organization
+ * runtime (a desk or a ticket session), "web" otherwise. Absent only on a row that
+ * predates the column, which reads as "web". Unlike {@link SessionInfo.orgId} — projected
+ * from the organization caches, so it disappears with the organization and is not read
+ * while company mode is off — this is a durable stamp on the row: development mode's list
+ * hides an "org" Session either way.
+ */
+ client?: "web" | "cli" | "org";
/**
* Background work the Session's loaded runtime still owns: command sessions running past
* their yield window (`exec_command` promotions and `run_in_background` launches) and
@@ -1441,10 +1481,14 @@ export interface SessionCreateRequest {
approvalMode?: ApprovalMode;
/**
* Creating-client hint stored on the Session row: "cli" when the CLI creates the
- * Session through the API; defaults to "web". Informational provenance only — lists
- * serve every row regardless of client.
+ * Session through the API, "org" when the organization runtime opened it (a desk or a
+ * ticket session — company mode's own, kept out of development mode's lists whether or
+ * not the organization still exists); defaults to "web". A REQUEST may send only "web" or
+ * "cli": the runtime writes "org" by calling the service directly, so no caller can claim
+ * an organization's provenance for its own Session. Lists serve every row regardless of
+ * client; only development mode's session list filters on it.
*/
- client?: "web" | "cli";
+ client?: "web" | "cli" | "org";
/**
* Marks the Session as created by a Benchmark evaluation or optimization (the Evaluation
* Center's Use flows, and the Test Sessions agent-evaluation launches through the CLI). Only
@@ -2430,7 +2474,8 @@ export type ServerEvent =
source: SessionSource;
}
| ScheduleServerEvent
- | GoalServerEvent;
+ | GoalServerEvent
+ | CompanyServerEvent;
/** Goal-mode progress on the session channel (the chat page drives its goal banner from these). */
export type GoalServerEvent =
@@ -3857,6 +3902,736 @@ export interface MachinesResponse {
job: MachineJob | null;
}
+// ---------------------------------------------------------------------------
+// Company mode: organizations (files are the truth; every DTO here is a projection)
+// ---------------------------------------------------------------------------
+
+/**
+ * Organization status: `paused` stops every automatic trigger; humans can still talk to any
+ * desk. These two values are the whole lifecycle — no route deletes an organization, so a
+ * paused one keeps its conversations, employees, desks and tickets.
+ */
+export type OrgStatus = "active" | "paused";
+/** Approval mode for desk and ticket sessions; unattended runs never get always-ask. */
+export type OrgApprovalMode = "allow-all" | "read-only" | "deny-all";
+/** The five kanban columns, each a directory under `tickets/<yyyy-mm>/`. */
+export type OrgTicketStatus = "proposed" | "in_progress" | "review" | "done" | "rejected";
+export type OrgTicketPriority = "P0" | "P1" | "P2";
+/** Live employee state: running when the desk or any ticket session has a Task in progress; paused when budget-paused. */
+export type OrgEmployeeState = "running" | "idle" | "paused";
+/**
+ * The trigger kinds an `[org_trigger]` block carries. `ticket_notice` is read-only: a ticket
+ * change starts no run of its own, so nothing writes that kind any more, and it stays in the
+ * union because Traces recorded while it did still carry it.
+ */
+export type OrgTriggerKind = "init" | "event" | "mention" | "ticket_notice" | "ticket_work";
+/** The ticket changes an employee is told about, listed in the body of its next calendar sweep. */
+export type OrgTicketChange = "assigned" | "blocked" | "blocker_closed" | "done" | "rejected";
+/** What the last evaluation of a calendar event did. */
+export type OrgCalendarOutcome = "fired" | "queued" | "paused" | "missed" | "error";
+/**
+ * The organization's working language: the language its handbook, its CEO's initialization
+ * run, every employee brief and every desk and ticket run are written in. Detected from the
+ * mission at creation (CJK text → `zh`, anything else → `en`) unless the request names one.
+ */
+export type OrgLanguage = "zh" | "en";
+
+/** The organization's settings as `org_config.toml` records them. */
+export interface OrganizationSettings {
+ name: string;
+ mission: string;
+ status: OrgStatus;
+ /** IANA timezone: budget periods (natural months) and chat day files follow it. */
+ timezone: string;
+ approvalMode: OrgApprovalMode;
+ /** Chat @-chain limit: a message whose hop reaches it records its mentions without triggering anyone. */
+ mentionChainLimit: number;
+ budgetWarnRatio: number;
+ budgetPauseRatio: number;
+ createdBy: string;
+ /** The shared workspace root when it is not the organization's own `workspace/` (absolute path). */
+ workspace?: string;
+ /** The model desks and ticket sessions run on when the employee names none; absent = the Project default. */
+ model?: { provider: string; modelId: string };
+ /** The working language (`language` in `org_config.toml`); absent on an organization written before the field existed, which reads as `en`. */
+ language?: OrgLanguage;
+}
+
+/** Period spend against the CEO's budget (= the whole organization). */
+export interface OrgSpendSummary {
+ /** `yyyy-mm` in the organization's timezone. */
+ period: string;
+ cost: number;
+ budget?: number;
+ /** cost / budget; absent without a budget. */
+ ratio?: number;
+}
+
+export interface OrganizationSummary {
+ projectId: string;
+ orgId: string;
+ name: string;
+ mission: string;
+ status: OrgStatus;
+ employeeCount: number;
+ runningCount: number;
+ pausedCount: number;
+ /** proposed + in_progress + review. */
+ openTickets: number;
+ blockedTickets: number;
+ createdBy: string;
+ spend: OrgSpendSummary;
+ /** Present when `org_config.toml` / `org_chart.yaml` fail validation: the organization is listed but every automatic trigger is held until it is fixed. */
+ invalid?: string;
+}
+
+export interface OrganizationsResponse {
+ organizations: OrganizationSummary[];
+}
+
+export interface OrgEmployeeItem {
+ agentId: string;
+ /** Agent display name (system_config.yaml); falls back to the id. */
+ name: string;
+ title: string;
+ /** null for the CEO (the root). */
+ reportsTo: string | null;
+ duties?: string;
+ /** As written in the chart: a sub-directory of the shared workspace (`.` = all of it) or an absolute path. */
+ workspace: string;
+ /** Where that resolves to; absent when the directory does not exist (the entry is then invalid). */
+ resolvedWorkspace?: string;
+ /** Monthly budget in USD for this employee plus all subordinates; absent = unbounded. */
+ budget?: number;
+ model?: { provider: string; modelId: string };
+ state: OrgEmployeeState;
+ desk?: { sessionId: string; workspace: string; openedAt: string };
+ /** Period spend: own sessions, and cumulative (own + every subordinate). */
+ spend: { own: number; cumulative: number; ratio?: number };
+ /** Why the entry cannot be triggered (missing Agent, missing workspace directory). */
+ invalid?: string;
+}
+
+export interface OrgChartResponse {
+ ceoAgentId: string;
+ employees: OrgEmployeeItem[];
+}
+
+export interface OrgCalendarItem {
+ agentId: string;
+ name: string;
+ title?: string;
+ prompt: string;
+ enabled: boolean;
+ startAt: string;
+ period?: string;
+ endAt?: string;
+ status: ScheduleStatus;
+ invalidReason?: string;
+ nextFireAt?: string;
+ lastFiredAt?: string;
+ /** What the most recent evaluation did (absent until the event has been evaluated once). */
+ lastOutcome?: OrgCalendarOutcome;
+ /** The organization or this employee is paused, so due slots are skipped, not fired. */
+ paused: boolean;
+}
+
+export interface OrgCalendarResponse {
+ events: OrgCalendarItem[];
+ invalidFiles: Array<{ agentId: string; name: string; error: string }>;
+}
+
+/**
+ * One line of a ticket's operation history, kept in the file's frontmatter apart from the
+ * progress prose: what was done, by whom (`agent:<id>` / `user:<id>` — an employee is recognised
+ * from the Agent id its command subprocesses carry, a person otherwise), and when.
+ */
+export type OrgTicketHistoryAction =
+ | "created"
+ | "assigned"
+ | "moved"
+ | "blocked"
+ | "unblocked"
+ | "progress"
+ | "session_started"
+ | "session_attached"
+ | "edited";
+
+export interface OrgTicketHistoryEntry {
+ at: string;
+ by: string;
+ action: OrgTicketHistoryAction;
+ /** The action's detail: the column moved to, the new owner, the block reason, the session id. */
+ note?: string;
+}
+
+/**
+ * The ticket id's slug: lowercase letters in hyphen-joined words, no digits (the date prefix
+ * already carries the numbers), chosen for meaning — derived from an ASCII title, proposed by
+ * the Project's model for a title in another language, or passed explicitly.
+ */
+export const TICKET_SLUG_PATTERN = /^[a-z]+(?:-[a-z]+)*$/;
+
+export interface OrgTicketItem {
+ ticketId: string;
+ title: string;
+ status: OrgTicketStatus;
+ /** The ONE responsible principal (`agent:<id>` / `user:<id>`); who filed it is the history's `created` entry. */
+ owner: string;
+ parent?: string;
+ notify: string[];
+ priority: OrgTicketPriority;
+ due?: string;
+ /** Non-empty = blocked; the ticket stays in its column. */
+ blocked?: string;
+ blockedBy?: string;
+ /** Contributing session ids, in the order they were attached. */
+ sessions: string[];
+ /** Any contributing session has a Task in progress. */
+ running: boolean;
+ /** Period cost of the contributing sessions (a session attached to n tickets counts 1/n here). */
+ cost: number;
+ /** Header/column disagreement or a duplicate id: shown with a danger mark, left where it is. */
+ invalid?: string;
+}
+
+export interface OrgTicketSessionItem {
+ sessionId: string;
+ agentId: string;
+ title?: string;
+ status: SessionStatus;
+ lastActiveAt?: string;
+}
+
+export interface OrgTicketDetail extends OrgTicketItem {
+ goal: string;
+ acceptanceCriteria: string;
+ /** `## Progress` as plain sentences; who wrote one and when is the matching history entry. */
+ progress: string[];
+ result: string;
+ /** The operation history from the frontmatter, oldest first. */
+ history: OrgTicketHistoryEntry[];
+ /** The whole file, for the Markdown view and for clients that prefer to edit it as text. */
+ body: string;
+ children: string[];
+ /** Own cost plus every descendant's along `Parent`. */
+ rolledUpCost: number;
+ sessionItems: OrgTicketSessionItem[];
+}
+
+export interface OrgTicketsResponse {
+ columns: Record<OrgTicketStatus, OrgTicketItem[]>;
+ /** Files that failed to parse (skipped; also recorded as errors). */
+ invalidFiles: Array<{ path: string; error: string }>;
+}
+
+/**
+ * What a `system` line records, structured: the kind of event and its parameters, so a client
+ * renders the sentence in the reader's language and with the principals' display names instead
+ * of showing the English `text` verbatim. `text` stays the English sentence (the CLI, older
+ * clients and the file itself read it); `notice` is the same fact for a client that can do better.
+ */
+export type OrgChannelNoticeKind =
+ | "employee_joined"
+ | "employee_left"
+ | "channel_created"
+ | "channel_archived"
+ | "channel_unarchived"
+ | "channel_joined"
+ | "channel_invited"
+ | "channel_left"
+ | "channel_removed"
+ | "budget_warned"
+ | "budget_paused"
+ /**
+ * Legacy, read-only: ticket changes no longer write into a channel — the board is read from
+ * the board and the overview's inbox. These three kinds stay so the lines already in an
+ * organization's message files keep rendering; nothing writes them any more.
+ */
+ | "ticket_blocked"
+ | "ticket_done"
+ | "ticket_rejected";
+
+/**
+ * The parameters each kind carries, all strings: principals as `agent:<id>` / `user:<id>`
+ * (`agent`, `principal`, `by`, `reportsTo`), a ticket as `ticket` + `title`, a budget event as
+ * `agent`, `period`, `percent`, `cost`, `budget`.
+ */
+export interface OrgChannelNotice {
+ kind: OrgChannelNoticeKind;
+ params: Record<string, string>;
+}
+
+export interface OrgChannelMessage {
+ id: string;
+ /** ISO 8601 UTC. */
+ time: string;
+ /** `agent:<id>` / `user:<id>` / `system`. */
+ sender: string;
+ hop: number;
+ text: string;
+ /** Principals mentioned, `all` included. */
+ mentions: string[];
+ refs?: { ticket?: string; session?: string; replyTo?: string };
+ /** Present on `system` lines the server wrote with a structured notice; absent on lines from before the field existed. */
+ notice?: OrgChannelNotice;
+}
+
+/**
+ * One channel as the API reports it. The all-hands channel (`default_channel`,
+ * `everyone: true`) exists for as long as the organization does and every employee and
+ * Project member is in it; every other channel carries the membership its members edit.
+ */
+export interface OrgChannelItem {
+ channelId: string;
+ /** As stored; the UI renders the all-hands channel's label itself. */
+ name: string;
+ /** "" when unset. */
+ purpose: string;
+ /** True only for `default_channel`: membership is implicit. */
+ everyone: boolean;
+ /** An archived channel is read-only and folded away. */
+ archived: boolean;
+ /** `user:<id>` / `agent:<id>` / `system`. */
+ createdBy: string;
+ /** ISO 8601 UTC. */
+ createdAt: string;
+ /** Implicit membership counted for the all-hands channel. */
+ memberCount: number;
+ /** Whether the caller (person or employee) is a member. */
+ isMember: boolean;
+ /** People only; 0 for an employee caller. */
+ unread: number;
+ /** People only; 0 for an employee caller. */
+ mentionsMe: number;
+ lastMessageAt: string | null;
+}
+
+export interface OrgChannelMember {
+ /** `agent:<id>` or `user:<id>`. */
+ principal: string;
+ name: string;
+ kind: "agent" | "user";
+}
+
+export interface OrgChannelDetail extends OrgChannelItem {
+ /** The all-hands channel resolves to every employee plus every Project member. */
+ members: OrgChannelMember[];
+}
+
+export interface OrgChannelsResponse {
+ /** `default_channel` first, then by name. */
+ channels: OrgChannelItem[];
+}
+
+export interface OrgChannelCreateRequest {
+ channelId: string;
+ name?: string;
+ purpose?: string;
+}
+
+export interface OrgChannelPatchRequest {
+ name?: string;
+ purpose?: string;
+ archived?: boolean;
+}
+
+export interface OrgChannelMemberRequest {
+ /** `agent:<id>` (an employee) or `user:<id>` (a Project member). */
+ principal: string;
+}
+
+export interface OrgChannelMessagesResponse {
+ /** The channel served. */
+ channelId: string;
+ /** The day file served (`yyyy-mm-dd` in the organization's timezone). */
+ date: string;
+ /** The days this channel has a file for, newest first, for paging back. */
+ days: string[];
+ messages: OrgChannelMessage[];
+ /** Messages of this channel after the caller's read cursor in it, across the recent days. */
+ unread: number;
+ /** Of those, the ones that mention the caller (or all). */
+ mentionsMe: number;
+ lastReadId?: string;
+}
+
+export interface OrgBudgetAlert {
+ agentId: string;
+ period: string;
+ warnedAt?: string;
+ pausedAt?: string;
+}
+
+export interface OrgFinanceEmployee {
+ agentId: string;
+ name: string;
+ title: string;
+ reportsTo: string | null;
+ own: number;
+ cumulative: number;
+ budget?: number;
+ ratio?: number;
+ warned: boolean;
+ paused: boolean;
+}
+
+export interface OrgFinanceTicket {
+ ticketId: string;
+ title: string;
+ status: OrgTicketStatus;
+ parent?: string;
+ cost: number;
+ rolledUp: number;
+}
+
+export interface OrgFinanceResponse {
+ period: string;
+ currency: "USD";
+ employees: OrgFinanceEmployee[];
+ tickets: OrgFinanceTicket[];
+ /** Daily cost of the organization's sessions over the period. */
+ daily: Array<{ date: string; cost: number }>;
+ alerts: OrgBudgetAlert[];
+ total: number;
+ /** Some usage ran on a model without pricing: tokens were counted, cost is a lower bound. */
+ unpriced: boolean;
+}
+
+export interface OrgDeskItem {
+ agentId: string;
+ name: string;
+ sessionId: string;
+ title?: string;
+ status: SessionStatus;
+ workspace: string;
+ lastActiveAt?: string;
+}
+
+export interface OrgSessionsResponse {
+ desks: OrgDeskItem[];
+ tickets: Array<{
+ ticketId: string;
+ title: string;
+ status: OrgTicketStatus;
+ sessions: OrgTicketSessionItem[];
+ }>;
+}
+
+export interface OrgDeskResponse {
+ agentId: string;
+ sessionId: string;
+ workspace: string;
+ openedAt: string;
+ /** True when this call created the desk session. */
+ created: boolean;
+}
+
+export interface OrganizationDetail extends OrganizationSummary {
+ settings: OrganizationSettings;
+ board: Record<OrgTicketStatus, number>;
+ /** Today's calendar events (organization timezone) with their outcomes. */
+ today: OrgCalendarItem[];
+ pending: {
+ /** Unread messages mentioning the caller (or all). */
+ mentions: number;
+ reviewTickets: OrgTicketItem[];
+ blockedByMe: OrgTicketItem[];
+ };
+ /** The last messages of the all-hands channel. */
+ recentMessages: OrgChannelMessage[];
+ alerts: OrgBudgetAlert[];
+ /** What the overview's inbox lists; absent only from a server older than the field. */
+ inbox?: OrgInbox;
+ /** The CEO's desk session once opened (creation opens it). */
+ ceoDeskSessionId?: string;
+}
+
+/**
+ * The overview's inbox: the three things a person is waited on or told about — messages
+ * that name them (or `@all`) in the all-hands channel, the tickets that are blocked (all of
+ * them, whoever they wait on), and the tickets closed as done this period. Newest first in
+ * each list; each capped at a page.
+ */
+export interface OrgInbox {
+ mentions: OrgChannelMessage[];
+ blockedTickets: OrgTicketItem[];
+ doneTickets: Array<OrgTicketItem & { closedAt?: string }>;
+}
+
+export interface OrganizationCreateRequest {
+ /** Semantic id, unique within the Project; also the directory name. */
+ orgId: string;
+ name?: string;
+ mission: string;
+ timezone?: string;
+ /** An existing absolute directory to use as the shared workspace; default = the organization's own `workspace/`. */
+ workspace?: string;
+ /** The model for desks and ticket sessions (a configured pair); default = the Project default. */
+ model?: { provider: string; modelId: string };
+ /**
+ * The CEO's monthly budget in USD, written as the `budget` of its `org_chart.yaml` entry.
+ * Budgets are compared on the cumulative line, so the CEO's is the whole company's.
+ * Omitted = 100; 0 is a real (zero) budget, not "unbounded" — only clearing the field
+ * later (`PATCH …/employees/:agentId` with `budget: null`) leaves the CEO unbounded.
+ */
+ ceoBudget?: number;
+ /** The working language; omitted = detected from the mission. */
+ language?: OrgLanguage;
+}
+
+export interface OrganizationPatchRequest {
+ name?: string;
+ mission?: string;
+ status?: OrgStatus;
+ approvalMode?: OrgApprovalMode;
+ timezone?: string;
+ mentionChainLimit?: number;
+ budgetWarnRatio?: number;
+ budgetPauseRatio?: number;
+ /** null returns to the organization's own `workspace/`. */
+ workspace?: string | null;
+ /** null returns to the Project default. */
+ model?: { provider: string; modelId: string } | null;
+ language?: OrgLanguage;
+}
+
+/**
+ * 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
+ * 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). */
+ 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. */
+ taken?: string[];
+}
+
+/**
+ * Why a proposal fell all the way through to a placeholder — what the client tells the user to
+ * explain the id it was just handed. `no_default_model`: the Project has no default model to
+ * ask. `model_failed`: it was asked and the request failed (no credential, a rejection, a
+ * timeout). `unusable_answer`: it answered twice and neither answer yielded an id.
+ * `no_ascii`: no model was consulted at all and the name carries no ASCII to transliterate.
+ */
+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`. */
+ id: string;
+ /** Who produced it: the model, the ASCII fallback, or the dated placeholder that names nothing. */
+ source: "model" | "fallback" | "placeholder";
+ /** Present only with `source: "placeholder"`: why the two real paths produced nothing. */
+ reason?: SemanticIdSuggestReason;
+}
+
+export interface OrgHireRequest {
+ /** Employ an existing Agent … */
+ agentId?: string;
+ /** … or create one (the two are exclusive). Plugins default to agent-company + agent-development. */
+ newAgent?: { agentId: string; name?: string; description?: string; plugins?: string[] };
+ title: string;
+ reportsTo: string;
+ workspace?: string;
+ budget?: number;
+ duties?: string;
+ model?: { provider: string; modelId: string };
+}
+
+export interface OrgEmployeePatchRequest {
+ title?: string;
+ reportsTo?: string;
+ workspace?: string;
+ /** null clears the budget. */
+ budget?: number | null;
+ duties?: string;
+ /** null clears the model (back to the Project default). */
+ model?: { provider: string; modelId: string } | null;
+}
+
+export interface OrgCalendarUpsertRequest {
+ /** POST only: the employee the event belongs to. */
+ agentId?: string;
+ /** POST only: the file name. */
+ name?: string;
+ title?: string;
+ prompt: string;
+ enabled: boolean;
+ startAt: string;
+ period?: string;
+ endAt?: string;
+}
+
+/**
+ * What a calendar write answers: the stored event, plus advisory `warnings` — one line each —
+ * about the rota: another employee's recurring event on the same start minute, or the same
+ * employee already holding a recurring event (desks that fire together compete for the same
+ * budget minute and the same tickets). The write succeeds regardless; the CLI prints the
+ * lines so the scheduling employee can stagger.
+ */
+export interface OrgCalendarWriteResponse extends OrgCalendarItem {
+ warnings?: string[];
+}
+
+export interface OrgTicketCreateRequest {
+ title: string;
+ /** Overrides the slug derived from the title; lowercase English words joined by hyphens. */
+ slug?: string;
+ goal?: string;
+ acceptanceCriteria?: string;
+ /** The whole Markdown body instead of goal + acceptanceCriteria (the frontmatter is still generated). */
+ body?: string;
+ /**
+ * The responsible principal: an employee's `agent:<id>` (or bare Agent id) or a member's
+ * `user:<id>`. Default = the caller — the session's employee inside a desk or ticket
+ * session, else the token's or cookie's user.
+ */
+ owner?: string;
+ parent?: string;
+ notify?: string[];
+ priority?: OrgTicketPriority;
+ due?: string;
+}
+
+export interface OrgTicketUpdateRequest {
+ title?: string;
+ /** The new responsible principal; never null — a ticket always has an owner. */
+ owner?: string;
+ parent?: string | null;
+ notify?: string[];
+ priority?: OrgTicketPriority;
+ due?: string | null;
+ goal?: string;
+ acceptanceCriteria?: string;
+ result?: string;
+}
+
+export interface OrgTicketMoveRequest {
+ status: OrgTicketStatus;
+ /** Required when moving into rejected; recorded under Result. */
+ reason?: string;
+}
+
+export interface OrgTicketBlockRequest {
+ reason: string;
+ /** A ticket id or a principal. */
+ by?: string;
+}
+
+export interface OrgTicketProgressRequest {
+ text: string;
+ /**
+ * The calling session (CLI: PENGUIN_SESSION_ID); the session is booked as a contributing
+ * session and the history entry is attributed to its employee. Honoured only for a request
+ * carrying the local API token — the control environment's credential; a signed-in user's
+ * write is attributed to the user.
+ */
+ sessionId?: string;
+ /**
+ * The calling employee's Agent id (CLI: PENGUIN_AGENT_ID from the control environment), the
+ * identity a write is recorded under; it wins over the session's employee, is honoured only
+ * with the local API token, like sessionId, and is ignored — the write falls back to the
+ * session's employee, then to the person — when it names no employee.
+ */
+ agentId?: string;
+}
+
+export interface OrgTicketStartRequest {
+ /** The employee the ticket session runs as (CLI: PENGUIN_AGENT_ID); defaults to the ticket owner. */
+ agentId?: string;
+ message?: string;
+ /** Another directory inside the shared workspace; defaults to the employee's desk workspace. */
+ workspace?: string;
+}
+
+export interface OrgTicketStartResponse {
+ sessionId: string;
+}
+
+export interface OrgTicketAttachRequest {
+ sessionId: string;
+}
+
+export interface OrgChannelMessageSendRequest {
+ text: string;
+ refs?: { ticket?: string; session?: string; replyTo?: string };
+ /**
+ * The calling session (CLI: PENGUIN_SESSION_ID): the message is sent as its Agent and
+ * inherits its hop. Honoured only for a request carrying the local API token — the control
+ * environment's credential; a signed-in user's message is sent as the user, at hop 0.
+ */
+ sessionId?: string;
+}
+
+export interface OrgChannelReadRequest {
+ /** Mark everything up to this message id as read. */
+ upTo: string;
+}
+
+/** The handbook index (`handbook/README.md`), the file every work run reads first. */
+export interface OrgHandbookResponse {
+ content: string;
+}
+
+/** One file of the organization handbook (`handbook/`, the company's knowledge base); `path` is relative to that directory. */
+export interface OrgHandbookFile {
+ path: string;
+ size: number;
+ updatedAt: string;
+}
+
+export interface OrgHandbookFilesResponse {
+ /** The index first, then the other documents by path. */
+ files: OrgHandbookFile[];
+}
+
+export interface OrgHandbookFileResponse {
+ path: string;
+ content: string;
+}
+
+export interface OrgHandbookFileWriteRequest {
+ content: string;
+}
+
+/** Company-mode notifications on the user-level event stream (best effort; the query routes carry the durable state). */
+export type CompanyServerEvent =
+ /** A work run (desk session) or ticket session was started by the organization scheduler or a ticket start. */
+ | {
+ type: "org_run";
+ projectId: string;
+ orgId: string;
+ agentId: string;
+ sessionId: string;
+ kind: OrgTriggerKind;
+ }
+ /** A new channel message (mentions included, so the client can tell whether it is addressed). */
+ | {
+ type: "org_channel";
+ projectId: string;
+ orgId: string;
+ channelId: string;
+ message: OrgChannelMessage;
+ }
+ /** A ticket's status, owner, blocked state or contributing sessions changed. */
+ | { type: "org_ticket"; projectId: string; orgId: string; ticketId: string; change: string }
+ /** Budget warning, pause or resume for an employee. */
+ | {
+ type: "org_budget";
+ projectId: string;
+ orgId: string;
+ agentId: string;
+ state: "warned" | "paused" | "resumed";
+ ratio: number;
+ };
+
// ---------------------------------------------------------------------------
// Web contributions (GET /api/contributions)
// ---------------------------------------------------------------------------
diff --git a/packages/server/src/db/migrations.ts b/packages/server/src/db/migrations.ts
index 0b0c25a2..29f83f96 100644
--- a/packages/server/src/db/migrations.ts
+++ b/packages/server/src/db/migrations.ts
@@ -244,6 +244,194 @@ export const MIGRATIONS: readonly Migration[] = [
if (has("display_name")) db.exec("ALTER TABLE users DROP COLUMN display_name");
},
},
+ {
+ version: 6,
+ name: "company-mode-org-caches",
+ // Additive: seven new tables for company mode (organizations of Agents), no change to any
+ // existing table. Every row is either rebuildable from the organization's files (desks.toml,
+ // the tickets' Sessions headers, the calendar files, usage records) or a user's own read
+ // cursor; a predecessor build never touches them.
+ swapSafe: true,
+ up(db) {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS org_sessions ( -- DERIVED CACHE (company mode): desk sessions, rebuilt from each organization's desks.toml (current + previous); trigger_hop is chat-chain accounting and reads 0 after a rebuild
+ session_id TEXT PRIMARY KEY,
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ current INTEGER NOT NULL DEFAULT 1,
+ trigger_hop INTEGER NOT NULL DEFAULT 0
+ );
+ CREATE INDEX IF NOT EXISTS idx_org_sessions_org ON org_sessions(project_id, org_id);
+ CREATE TABLE IF NOT EXISTS org_ticket_sessions ( -- DERIVED CACHE (company mode): ticket <-> contributing session, rebuilt from each ticket's Sessions header
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ ticket_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ trigger_hop INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (project_id, org_id, ticket_id, session_id)
+ );
+ CREATE INDEX IF NOT EXISTS idx_org_ticket_sessions_session ON org_ticket_sessions(session_id);
+ CREATE TABLE IF NOT EXISTS org_calendar_state ( -- calendar run state (company mode; the files are declarative intent), same rules as schedule_state
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ name TEXT NOT NULL,
+ start_at_ms INTEGER NOT NULL,
+ def_hash TEXT NOT NULL,
+ last_slot_ms INTEGER,
+ last_fired_at TEXT,
+ fired_once INTEGER NOT NULL DEFAULT 0,
+ missed INTEGER NOT NULL DEFAULT 0,
+ invalid_reason TEXT,
+ last_outcome TEXT,
+ PRIMARY KEY (project_id, org_id, agent_id, name)
+ );
+ CREATE TABLE IF NOT EXISTS org_ticket_state ( -- DERIVED CACHE (company mode): the last (status, owner, blocked) seen per ticket, so a change is notified once; rebuilt silently from the ticket files
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ ticket_id TEXT NOT NULL,
+ status TEXT NOT NULL,
+ owner TEXT NOT NULL DEFAULT '',
+ blocked TEXT NOT NULL DEFAULT '',
+ blocked_by TEXT NOT NULL DEFAULT '',
+ PRIMARY KEY (project_id, org_id, ticket_id)
+ );
+ CREATE TABLE IF NOT EXISTS org_chat_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per chat day file
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ date TEXT NOT NULL,
+ offset_bytes INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (project_id, org_id, date)
+ );
+ CREATE TABLE IF NOT EXISTS org_chat_reads ( -- user data (company mode): each user's read cursor in an organization's chat
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ last_read_id TEXT NOT NULL,
+ PRIMARY KEY (project_id, org_id, user_id)
+ );
+ CREATE TABLE IF NOT EXISTS org_budget_state ( -- DERIVED CACHE (company mode): warn / pause marks per employee and period, recomputed from usage and the chart's budgets
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ period TEXT NOT NULL,
+ warned_at TEXT,
+ paused_at TEXT,
+ PRIMARY KEY (project_id, org_id, agent_id, period)
+ );
+ `);
+ },
+ // Drops the seven tables. LOSES: chat read cursors (each user's "read up to here" marks) and
+ // the run marks that stop a calendar slot, a ticket change or a budget alert from firing
+ // twice — a build with this migration re-registers everything from the files, without
+ // backfilling missed slots, and users see every chat message as unread once.
+ down(db) {
+ db.exec(`
+ DROP INDEX IF EXISTS idx_org_ticket_sessions_session;
+ DROP INDEX IF EXISTS idx_org_sessions_org;
+ DROP TABLE IF EXISTS org_budget_state;
+ DROP TABLE IF EXISTS org_chat_reads;
+ DROP TABLE IF EXISTS org_chat_state;
+ DROP TABLE IF EXISTS org_ticket_state;
+ DROP TABLE IF EXISTS org_calendar_state;
+ DROP TABLE IF EXISTS org_ticket_sessions;
+ DROP TABLE IF EXISTS org_sessions;
+ `);
+ },
+ },
+ {
+ version: 7,
+ name: "company-mode-channels",
+ // The organization's single group chat became channels: a message lives in
+ // `channels/<channel_id>/<date>.jsonl`, so the tail-scan cursor and each user's read
+ // cursor are per channel. `org_chat_state` / `org_chat_reads` are dropped for
+ // `org_channel_state` / `org_channel_reads`: the tables are renamed and the channel
+ // belongs in the primary key, neither of which SQLite does in place. Nothing is carried
+ // over: company mode is unreleased, and every row was either rebuildable from the files
+ // (the scan cursor) or one pass of "everything looks unread" (the read cursor). A
+ // predecessor build reads neither table's shape, only its own writes, so this is
+ // swap-safe.
+ swapSafe: true,
+ up(db) {
+ db.exec(`
+ DROP TABLE IF EXISTS org_chat_state;
+ DROP TABLE IF EXISTS org_chat_reads;
+ CREATE TABLE IF NOT EXISTS org_channel_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per channel and day file
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ channel_id TEXT NOT NULL,
+ date TEXT NOT NULL,
+ offset_bytes INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (project_id, org_id, channel_id, date)
+ );
+ CREATE TABLE IF NOT EXISTS org_channel_reads ( -- user data (company mode): each user's read cursor in one channel
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ channel_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ last_read_id TEXT NOT NULL,
+ PRIMARY KEY (project_id, org_id, channel_id, user_id)
+ );
+ `);
+ },
+ // Recreates the two tables under their old names, exactly as migration 6 declared them —
+ // EMPTY. LOSES every scan cursor (re-derived by the next pass, which republishes the
+ // messages it re-reads) and every read cursor (users see the recent days as unread once).
+ down(db) {
+ db.exec(`
+ DROP TABLE IF EXISTS org_channel_state;
+ DROP TABLE IF EXISTS org_channel_reads;
+ CREATE TABLE IF NOT EXISTS org_chat_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per chat day file
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ date TEXT NOT NULL,
+ offset_bytes INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (project_id, org_id, date)
+ );
+ CREATE TABLE IF NOT EXISTS org_chat_reads ( -- user data (company mode): each user's read cursor in an organization's chat
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ last_read_id TEXT NOT NULL,
+ PRIMARY KEY (project_id, org_id, user_id)
+ );
+ `);
+ },
+ },
+ {
+ version: 8,
+ name: "company-mode-desk-notices",
+ // Additive: one new table and its index. A ticket change no longer starts a work run at
+ // the owner's desk; it is queued here and delivered inside the body of that employee's
+ // next calendar sweep. A predecessor build never reads the table, so a rollback survives
+ // it — with whatever rows are in it left undelivered.
+ swapSafe: true,
+ up(db) {
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS org_desk_notices ( -- DERIVED CACHE (company mode): ticket changes waiting for an employee's next calendar sweep; dropping it loses only the digests not delivered yet
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ ticket_id TEXT NOT NULL,
+ change TEXT NOT NULL,
+ at TEXT NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS idx_org_desk_notices_agent ON org_desk_notices(project_id, org_id, agent_id);
+ `);
+ },
+ // LOSES every queued notice: the ticket changes an employee has not been told about yet.
+ // The change itself is in the ticket file and its history either way; what
+ // goes is the "Since your last sweep" line that would have named it.
+ down(db) {
+ db.exec(`
+ DROP INDEX IF EXISTS idx_org_desk_notices_agent;
+ DROP TABLE IF EXISTS org_desk_notices;
+ `);
+ },
+ },
];
/** The highest version this build knows how to reach. */
diff --git a/packages/server/src/db/repos/organizations.ts b/packages/server/src/db/repos/organizations.ts
new file mode 100644
index 00000000..657a01eb
--- /dev/null
+++ b/packages/server/src/db/repos/organizations.ts
@@ -0,0 +1,665 @@
+/**
+ * Company-mode caches. Every table here is a projection of an organization's files (which
+ * desk session an employee has, which sessions contribute to a ticket, how far a calendar
+ * event or a channel scan has got, what a ticket looked like when it was last notified) or a
+ * user's own read cursor. The service rebuilds the projections every reconcile pass, so a
+ * dropped table costs one pass of silence, never a wrong answer. `org_desk_notices` is the
+ * one queue in the family: the ticket changes an employee has not been told about yet, held
+ * until its next calendar sweep carries them, so dropping it loses those digests and nothing
+ * else — the changes themselves live in the ticket files and the all-hands channel.
+ */
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Db } from "../../hmr/capabilities.js";
+import type { OrgCache } from "../../mechanisms/organization.js";
+import type { OrgCalendarOutcome, OrgTicketChange } from "../../api/types.js";
+
+export interface OrgSessionRow {
+ sessionId: string;
+ projectId: string;
+ orgId: string;
+ agentId: string;
+ /** The employee's current desk (renewed desks stay for cost attribution). */
+ current: boolean;
+ /** Hop of the last mention-chain trigger delivered to this session. */
+ triggerHop: number;
+}
+
+export interface OrgTicketSessionRow {
+ projectId: string;
+ orgId: string;
+ ticketId: string;
+ sessionId: string;
+ agentId: string;
+ triggerHop: number;
+}
+
+export interface OrgCalendarStateRow {
+ projectId: string;
+ orgId: string;
+ agentId: string;
+ name: string;
+ startAtMs: number;
+ defHash: string;
+ lastSlotMs: number | null;
+ lastFiredAt: string | null;
+ firedOnce: boolean;
+ missed: boolean;
+ invalidReason: string | null;
+ lastOutcome: OrgCalendarOutcome | null;
+}
+
+export interface OrgTicketStateRow {
+ projectId: string;
+ orgId: string;
+ ticketId: string;
+ status: string;
+ owner: string;
+ blocked: string;
+ blockedBy: string;
+}
+
+export interface OrgBudgetStateRow {
+ projectId: string;
+ orgId: string;
+ agentId: string;
+ period: string;
+ warnedAt: string | null;
+ pausedAt: string | null;
+}
+
+/**
+ * One ticket change waiting for an employee's next calendar sweep. `seq` is the delivery
+ * order (a rowid alias, so it never repeats) and `at` is when the change was noticed.
+ */
+export interface OrgDeskNoticeRow {
+ seq: number;
+ projectId: string;
+ orgId: string;
+ agentId: string;
+ ticketId: string;
+ change: OrgTicketChange;
+ at: string;
+}
+
+/** Where a session belongs, when it belongs to an organization at all. */
+export interface OrgSessionOwner {
+ projectId: string;
+ orgId: string;
+ agentId: string;
+ kind: "desk" | "ticket";
+ triggerHop: number;
+}
+
+const calendarRow = (r: Record<string, unknown>): OrgCalendarStateRow => ({
+ projectId: r.project_id as string,
+ orgId: r.org_id as string,
+ agentId: r.agent_id as string,
+ name: r.name as string,
+ startAtMs: Number(r.start_at_ms),
+ defHash: r.def_hash as string,
+ lastSlotMs: r.last_slot_ms === null ? null : Number(r.last_slot_ms),
+ lastFiredAt: (r.last_fired_at as string | null) ?? null,
+ firedOnce: Number(r.fired_once) === 1,
+ missed: Number(r.missed) === 1,
+ invalidReason: (r.invalid_reason as string | null) ?? null,
+ lastOutcome: (r.last_outcome as OrgCalendarOutcome | null) ?? null,
+});
+
+@Component()
+export class OrgCacheRepo implements OrgCache {
+ @Use() private readonly db!: Db;
+
+ // ---- desk sessions ----
+
+ deskSessions(projectId: string, orgId: string): OrgSessionRow[] {
+ const rows = this.db
+ .prepare(
+ "SELECT * FROM org_sessions WHERE project_id = ? AND org_id = ? ORDER BY agent_id, current DESC",
+ )
+ .all(projectId, orgId) as Record<string, unknown>[];
+ return rows.map((r) => ({
+ sessionId: r.session_id as string,
+ projectId: r.project_id as string,
+ orgId: r.org_id as string,
+ agentId: r.agent_id as string,
+ current: Number(r.current) === 1,
+ triggerHop: Number(r.trigger_hop),
+ }));
+ }
+
+ /** Makes the table match the ledger: unknown rows are added, rows for sessions no longer in it removed, hops kept. */
+ syncDeskSessions(
+ projectId: string,
+ orgId: string,
+ rows: Array<{ sessionId: string; agentId: string; current: boolean }>,
+ ): void {
+ const keep = new Set(rows.map((r) => r.sessionId));
+ for (const existing of this.deskSessions(projectId, orgId)) {
+ if (!keep.has(existing.sessionId)) {
+ this.db.prepare("DELETE FROM org_sessions WHERE session_id = ?").run(existing.sessionId);
+ }
+ }
+ const upsert = this.db.prepare(
+ `INSERT INTO org_sessions (session_id, project_id, org_id, agent_id, current)
+ VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT(session_id) DO UPDATE SET project_id = excluded.project_id, org_id = excluded.org_id,
+ agent_id = excluded.agent_id, current = excluded.current`,
+ );
+ for (const r of rows) upsert.run(r.sessionId, projectId, orgId, r.agentId, r.current ? 1 : 0);
+ }
+
+ // ---- ticket sessions ----
+
+ ticketSessions(projectId: string, orgId: string): OrgTicketSessionRow[] {
+ const rows = this.db
+ .prepare(
+ "SELECT * FROM org_ticket_sessions WHERE project_id = ? AND org_id = ? ORDER BY ticket_id, session_id",
+ )
+ .all(projectId, orgId) as Record<string, unknown>[];
+ return rows.map((r) => ({
+ projectId: r.project_id as string,
+ orgId: r.org_id as string,
+ ticketId: r.ticket_id as string,
+ sessionId: r.session_id as string,
+ agentId: r.agent_id as string,
+ triggerHop: Number(r.trigger_hop),
+ }));
+ }
+
+ syncTicketSessions(
+ projectId: string,
+ orgId: string,
+ rows: Array<{ ticketId: string; sessionId: string; agentId: string }>,
+ ): void {
+ const keep = new Set(rows.map((r) => `${r.ticketId}\0${r.sessionId}`));
+ for (const existing of this.ticketSessions(projectId, orgId)) {
+ if (!keep.has(`${existing.ticketId}\0${existing.sessionId}`)) {
+ this.db
+ .prepare(
+ "DELETE FROM org_ticket_sessions WHERE project_id = ? AND org_id = ? AND ticket_id = ? AND session_id = ?",
+ )
+ .run(projectId, orgId, existing.ticketId, existing.sessionId);
+ }
+ }
+ const upsert = this.db.prepare(
+ `INSERT INTO org_ticket_sessions (project_id, org_id, ticket_id, session_id, agent_id)
+ VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT(project_id, org_id, ticket_id, session_id) DO UPDATE SET agent_id = excluded.agent_id`,
+ );
+ for (const r of rows) upsert.run(projectId, orgId, r.ticketId, r.sessionId, r.agentId);
+ }
+
+ addTicketSession(
+ projectId: string,
+ orgId: string,
+ ticketId: string,
+ sessionId: string,
+ agentId: string,
+ ): void {
+ this.db
+ .prepare(
+ `INSERT OR IGNORE INTO org_ticket_sessions (project_id, org_id, ticket_id, session_id, agent_id)
+ VALUES (?, ?, ?, ?, ?)`,
+ )
+ .run(projectId, orgId, ticketId, sessionId, agentId);
+ }
+
+ /** Which organization a session belongs to (desk first, then ticket), or null. */
+ ownerOfSession(sessionId: string): OrgSessionOwner | null {
+ const desk = this.db
+ .prepare("SELECT * FROM org_sessions WHERE session_id = ?")
+ .get(sessionId) as Record<string, unknown> | undefined;
+ if (desk) {
+ return {
+ projectId: desk.project_id as string,
+ orgId: desk.org_id as string,
+ agentId: desk.agent_id as string,
+ kind: "desk",
+ triggerHop: Number(desk.trigger_hop),
+ };
+ }
+ const ticket = this.db
+ .prepare("SELECT * FROM org_ticket_sessions WHERE session_id = ? ORDER BY ticket_id LIMIT 1")
+ .get(sessionId) as Record<string, unknown> | undefined;
+ if (!ticket) return null;
+ return {
+ projectId: ticket.project_id as string,
+ orgId: ticket.org_id as string,
+ agentId: ticket.agent_id as string,
+ kind: "ticket",
+ triggerHop: Number(ticket.trigger_hop),
+ };
+ }
+
+ /**
+ * Every organization-owned session of a Project, session id -> organization id, desk and
+ * ticket sessions together. Two queries for the whole Project, so a session list can stamp
+ * `SessionInfo.orgId` on its rows without a lookup per row; `ownerOfSession` stays the
+ * point query for the single-session GET. Desk rows win a collision, as they do there.
+ */
+ orgIdsOfProject(projectId: string): Map<string, string> {
+ const ids = new Map<string, string>();
+ for (const table of ["org_ticket_sessions", "org_sessions"]) {
+ const rows = this.db
+ .prepare(`SELECT session_id, org_id FROM ${table} WHERE project_id = ?`)
+ .all(projectId) as Array<{ session_id: string; org_id: string }>;
+ for (const r of rows) ids.set(r.session_id, r.org_id);
+ }
+ return ids;
+ }
+
+ /** Records the hop of the trigger just delivered to a session (both tables, whichever holds it). */
+ setTriggerHop(sessionId: string, hop: number): void {
+ this.db
+ .prepare("UPDATE org_sessions SET trigger_hop = ? WHERE session_id = ?")
+ .run(hop, sessionId);
+ this.db
+ .prepare("UPDATE org_ticket_sessions SET trigger_hop = ? WHERE session_id = ?")
+ .run(hop, sessionId);
+ }
+
+ // ---- calendar state (mirrors schedule_state) ----
+
+ findCalendar(
+ projectId: string,
+ orgId: string,
+ agentId: string,
+ name: string,
+ ): OrgCalendarStateRow | null {
+ const r = this.db
+ .prepare(
+ "SELECT * FROM org_calendar_state WHERE project_id = ? AND org_id = ? AND agent_id = ? AND name = ?",
+ )
+ .get(projectId, orgId, agentId, name) as Record<string, unknown> | undefined;
+ return r ? calendarRow(r) : null;
+ }
+
+ listCalendar(projectId: string, orgId: string): OrgCalendarStateRow[] {
+ const rows = this.db
+ .prepare(
+ "SELECT * FROM org_calendar_state WHERE project_id = ? AND org_id = ? ORDER BY agent_id, name",
+ )
+ .all(projectId, orgId) as Record<string, unknown>[];
+ return rows.map(calendarRow);
+ }
+
+ /** Same identity rule as schedules: a `start_at` change resets the run state, a content change only clears the invalid mark. */
+ registerCalendar(args: {
+ projectId: string;
+ orgId: string;
+ agentId: string;
+ name: string;
+ startAtMs: number;
+ defHash: string;
+ }): { row: OrgCalendarStateRow; fresh: boolean } {
+ const existing = this.findCalendar(args.projectId, args.orgId, args.agentId, args.name);
+ let fresh = false;
+ if (!existing) {
+ this.db
+ .prepare(
+ `INSERT INTO org_calendar_state (project_id, org_id, agent_id, name, start_at_ms, def_hash)
+ VALUES (?, ?, ?, ?, ?, ?)`,
+ )
+ .run(args.projectId, args.orgId, args.agentId, args.name, args.startAtMs, args.defHash);
+ fresh = true;
+ } else if (existing.startAtMs !== args.startAtMs) {
+ this.db
+ .prepare(
+ `UPDATE org_calendar_state
+ SET start_at_ms = ?, def_hash = ?, last_slot_ms = NULL, last_fired_at = NULL,
+ fired_once = 0, missed = 0, invalid_reason = NULL, last_outcome = NULL
+ WHERE project_id = ? AND org_id = ? AND agent_id = ? AND name = ?`,
+ )
+ .run(args.startAtMs, args.defHash, args.projectId, args.orgId, args.agentId, args.name);
+ fresh = true;
+ } else if (existing.defHash !== args.defHash) {
+ this.db
+ .prepare(
+ `UPDATE org_calendar_state SET def_hash = ?, invalid_reason = NULL
+ WHERE project_id = ? AND org_id = ? AND agent_id = ? AND name = ?`,
+ )
+ .run(args.defHash, args.projectId, args.orgId, args.agentId, args.name);
+ }
+ const row = this.findCalendar(args.projectId, args.orgId, args.agentId, args.name);
+ if (!row) throw new Error("Failed to read back org_calendar_state after registration");
+ return { row, fresh };
+ }
+
+ markCalendarSlot(
+ projectId: string,
+ orgId: string,
+ agentId: string,
+ name: string,
+ slotMs: number,
+ ): void {
+ this.db
+ .prepare(
+ `UPDATE org_calendar_state SET last_slot_ms = ?
+ WHERE project_id = ? AND org_id = ? AND agent_id = ? AND name = ?`,
+ )
+ .run(slotMs, projectId, orgId, agentId, name);
+ }
+
+ markCalendarFired(
+ projectId: string,
+ orgId: string,
+ agentId: string,
+ name: string,
+ firedAt: string,
+ oneShot: boolean,
+ ): void {
+ this.db
+ .prepare(
+ `UPDATE org_calendar_state
+ SET last_fired_at = ?, fired_once = CASE WHEN ? THEN 1 ELSE fired_once END
+ WHERE project_id = ? AND org_id = ? AND agent_id = ? AND name = ?`,
+ )
+ .run(firedAt, oneShot ? 1 : 0, projectId, orgId, agentId, name);
+ }
+
+ markCalendarMissed(projectId: string, orgId: string, agentId: string, name: string): void {
+ this.db
+ .prepare(
+ `UPDATE org_calendar_state SET missed = 1
+ WHERE project_id = ? AND org_id = ? AND agent_id = ? AND name = ?`,
+ )
+ .run(projectId, orgId, agentId, name);
+ }
+
+ markCalendarOutcome(
+ projectId: string,
+ orgId: string,
+ agentId: string,
+ name: string,
+ outcome: OrgCalendarOutcome,
+ ): void {
+ this.db
+ .prepare(
+ `UPDATE org_calendar_state SET last_outcome = ?
+ WHERE project_id = ? AND org_id = ? AND agent_id = ? AND name = ?`,
+ )
+ .run(outcome, projectId, orgId, agentId, name);
+ }
+
+ /** Reconciliation cleanup: rows whose file is gone. */
+ deleteMissingCalendar(
+ projectId: string,
+ orgId: string,
+ present: Array<{ agentId: string; name: string }>,
+ ): void {
+ const keep = new Set(present.map((p) => `${p.agentId}\0${p.name}`));
+ for (const row of this.listCalendar(projectId, orgId)) {
+ if (!keep.has(`${row.agentId}\0${row.name}`)) {
+ this.db
+ .prepare(
+ "DELETE FROM org_calendar_state WHERE project_id = ? AND org_id = ? AND agent_id = ? AND name = ?",
+ )
+ .run(projectId, orgId, row.agentId, row.name);
+ }
+ }
+ }
+
+ deleteCalendar(projectId: string, orgId: string, agentId: string, name: string): void {
+ this.db
+ .prepare(
+ "DELETE FROM org_calendar_state WHERE project_id = ? AND org_id = ? AND agent_id = ? AND name = ?",
+ )
+ .run(projectId, orgId, agentId, name);
+ }
+
+ // ---- ticket state ----
+
+ findTicketState(projectId: string, orgId: string, ticketId: string): OrgTicketStateRow | null {
+ const r = this.db
+ .prepare(
+ "SELECT * FROM org_ticket_state WHERE project_id = ? AND org_id = ? AND ticket_id = ?",
+ )
+ .get(projectId, orgId, ticketId) as Record<string, unknown> | undefined;
+ return r
+ ? {
+ projectId: r.project_id as string,
+ orgId: r.org_id as string,
+ ticketId: r.ticket_id as string,
+ status: r.status as string,
+ owner: r.owner as string,
+ blocked: r.blocked as string,
+ blockedBy: r.blocked_by as string,
+ }
+ : null;
+ }
+
+ upsertTicketState(row: OrgTicketStateRow): void {
+ this.db
+ .prepare(
+ `INSERT INTO org_ticket_state (project_id, org_id, ticket_id, status, owner, blocked, blocked_by)
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(project_id, org_id, ticket_id) DO UPDATE SET status = excluded.status,
+ owner = excluded.owner, blocked = excluded.blocked, blocked_by = excluded.blocked_by`,
+ )
+ .run(
+ row.projectId,
+ row.orgId,
+ row.ticketId,
+ row.status,
+ row.owner,
+ row.blocked,
+ row.blockedBy,
+ );
+ }
+
+ deleteMissingTicketState(projectId: string, orgId: string, presentIds: string[]): void {
+ const keep = new Set(presentIds);
+ const rows = this.db
+ .prepare("SELECT ticket_id FROM org_ticket_state WHERE project_id = ? AND org_id = ?")
+ .all(projectId, orgId) as Array<{ ticket_id: string }>;
+ for (const r of rows) {
+ if (!keep.has(r.ticket_id)) {
+ this.db
+ .prepare(
+ "DELETE FROM org_ticket_state WHERE project_id = ? AND org_id = ? AND ticket_id = ?",
+ )
+ .run(projectId, orgId, r.ticket_id);
+ }
+ }
+ }
+
+ // ---- channel cursors ----
+
+ channelOffset(projectId: string, orgId: string, channelId: string, date: string): number {
+ const r = this.db
+ .prepare(
+ "SELECT offset_bytes FROM org_channel_state WHERE project_id = ? AND org_id = ? AND channel_id = ? AND date = ?",
+ )
+ .get(projectId, orgId, channelId, date) as { offset_bytes: number } | undefined;
+ return r ? Number(r.offset_bytes) : 0;
+ }
+
+ setChannelOffset(
+ projectId: string,
+ orgId: string,
+ channelId: string,
+ date: string,
+ offset: number,
+ ): void {
+ this.db
+ .prepare(
+ `INSERT INTO org_channel_state (project_id, org_id, channel_id, date, offset_bytes) VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT(project_id, org_id, channel_id, date) DO UPDATE SET offset_bytes = excluded.offset_bytes`,
+ )
+ .run(projectId, orgId, channelId, date, offset);
+ }
+
+ readCursor(projectId: string, orgId: string, channelId: string, userId: string): string | null {
+ const r = this.db
+ .prepare(
+ "SELECT last_read_id FROM org_channel_reads WHERE project_id = ? AND org_id = ? AND channel_id = ? AND user_id = ?",
+ )
+ .get(projectId, orgId, channelId, userId) as { last_read_id: string } | undefined;
+ return r ? r.last_read_id : null;
+ }
+
+ setReadCursor(
+ projectId: string,
+ orgId: string,
+ channelId: string,
+ userId: string,
+ lastReadId: string,
+ ): void {
+ this.db
+ .prepare(
+ `INSERT INTO org_channel_reads (project_id, org_id, channel_id, user_id, last_read_id) VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT(project_id, org_id, channel_id, user_id) DO UPDATE SET last_read_id = excluded.last_read_id`,
+ )
+ .run(projectId, orgId, channelId, userId, lastReadId);
+ }
+
+ // ---- budget marks ----
+
+ budgetState(
+ projectId: string,
+ orgId: string,
+ agentId: string,
+ period: string,
+ ): OrgBudgetStateRow | null {
+ const r = this.db
+ .prepare(
+ "SELECT * FROM org_budget_state WHERE project_id = ? AND org_id = ? AND agent_id = ? AND period = ?",
+ )
+ .get(projectId, orgId, agentId, period) as Record<string, unknown> | undefined;
+ return r ? budgetRow(r) : null;
+ }
+
+ listBudgetStates(projectId: string, orgId: string, period: string): OrgBudgetStateRow[] {
+ const rows = this.db
+ .prepare(
+ "SELECT * FROM org_budget_state WHERE project_id = ? AND org_id = ? AND period = ? ORDER BY agent_id",
+ )
+ .all(projectId, orgId, period) as Record<string, unknown>[];
+ return rows.map(budgetRow);
+ }
+
+ markBudget(
+ projectId: string,
+ orgId: string,
+ agentId: string,
+ period: string,
+ patch: { warnedAt?: string | null; pausedAt?: string | null },
+ ): void {
+ this.db
+ .prepare(
+ `INSERT INTO org_budget_state (project_id, org_id, agent_id, period) VALUES (?, ?, ?, ?)
+ ON CONFLICT(project_id, org_id, agent_id, period) DO NOTHING`,
+ )
+ .run(projectId, orgId, agentId, period);
+ if (patch.warnedAt !== undefined) {
+ this.db
+ .prepare(
+ "UPDATE org_budget_state SET warned_at = ? WHERE project_id = ? AND org_id = ? AND agent_id = ? AND period = ?",
+ )
+ .run(patch.warnedAt, projectId, orgId, agentId, period);
+ }
+ if (patch.pausedAt !== undefined) {
+ this.db
+ .prepare(
+ "UPDATE org_budget_state SET paused_at = ? WHERE project_id = ? AND org_id = ? AND agent_id = ? AND period = ?",
+ )
+ .run(patch.pausedAt, projectId, orgId, agentId, period);
+ }
+ }
+
+ // ---- desk notices (the queue delivered in the next calendar sweep) ----
+
+ /** Records a ticket change for an employee. Nothing is sent: the next sweep carries it. */
+ queueDeskNotice(row: Omit<OrgDeskNoticeRow, "seq">): void {
+ this.db
+ .prepare(
+ `INSERT INTO org_desk_notices (project_id, org_id, agent_id, ticket_id, change, at)
+ VALUES (?, ?, ?, ?, ?, ?)`,
+ )
+ .run(row.projectId, row.orgId, row.agentId, row.ticketId, row.change, row.at);
+ }
+
+ /**
+ * The employee's queued changes in delivery order, removed as they are read: one
+ * transaction, so a sweep never carries a notice a second sweep also carries.
+ */
+ takeDeskNotices(projectId: string, orgId: string, agentId: string): OrgDeskNoticeRow[] {
+ this.db.exec("BEGIN IMMEDIATE");
+ try {
+ const rows = this.db
+ .prepare(
+ `SELECT * FROM org_desk_notices
+ WHERE project_id = ? AND org_id = ? AND agent_id = ? ORDER BY seq`,
+ )
+ .all(projectId, orgId, agentId) as Record<string, unknown>[];
+ this.db
+ .prepare(
+ "DELETE FROM org_desk_notices WHERE project_id = ? AND org_id = ? AND agent_id = ?",
+ )
+ .run(projectId, orgId, agentId);
+ this.db.exec("COMMIT");
+ return rows.map((r) => ({
+ seq: Number(r.seq),
+ projectId: r.project_id as string,
+ orgId: r.org_id as string,
+ agentId: r.agent_id as string,
+ ticketId: r.ticket_id as string,
+ change: r.change as OrgTicketChange,
+ at: r.at as string,
+ }));
+ } catch (err) {
+ this.db.exec("ROLLBACK");
+ throw err;
+ }
+ }
+
+ /** An employee that left takes its undelivered notices with it: no sweep will ever carry them. */
+ deleteDeskNotices(projectId: string, orgId: string, agentId: string): void {
+ this.db
+ .prepare("DELETE FROM org_desk_notices WHERE project_id = ? AND org_id = ? AND agent_id = ?")
+ .run(projectId, orgId, agentId);
+ }
+
+ // ---- lifecycle ----
+
+ deleteOrg(projectId: string, orgId: string): void {
+ for (const table of [
+ "org_sessions",
+ "org_ticket_sessions",
+ "org_calendar_state",
+ "org_ticket_state",
+ "org_channel_state",
+ "org_channel_reads",
+ "org_budget_state",
+ "org_desk_notices",
+ ]) {
+ this.db
+ .prepare(`DELETE FROM ${table} WHERE project_id = ? AND org_id = ?`)
+ .run(projectId, orgId);
+ }
+ }
+
+ deleteProject(projectId: string): void {
+ for (const table of [
+ "org_sessions",
+ "org_ticket_sessions",
+ "org_calendar_state",
+ "org_ticket_state",
+ "org_channel_state",
+ "org_channel_reads",
+ "org_budget_state",
+ "org_desk_notices",
+ ]) {
+ this.db.prepare(`DELETE FROM ${table} WHERE project_id = ?`).run(projectId);
+ }
+ }
+}
+
+const budgetRow = (r: Record<string, unknown>): OrgBudgetStateRow => ({
+ projectId: r.project_id as string,
+ orgId: r.org_id as string,
+ agentId: r.agent_id as string,
+ period: r.period as string,
+ warnedAt: (r.warned_at as string | null) ?? null,
+ pausedAt: (r.paused_at as string | null) ?? null,
+});
diff --git a/packages/server/src/db/repos/server-settings.ts b/packages/server/src/db/repos/server-settings.ts
index 2cf213d4..12061808 100644
--- a/packages/server/src/db/repos/server-settings.ts
+++ b/packages/server/src/db/repos/server-settings.ts
@@ -34,6 +34,8 @@ const ATTACHMENT_MAX_MB_KEY = "attachment_max_mb";
/** Key of the per-message total attachment limit, in whole MB; default DEFAULT_ATTACHMENT_TOTAL_MB. */
const ATTACHMENT_TOTAL_MB_KEY = "attachment_total_mb";
+/** Key of the company-mode master switch; default off (see getCompanyMode). */
+const COMPANY_MODE_KEY = "companyMode";
@Component()
export class ServerSettingsRepo implements Settings {
@@ -146,4 +148,23 @@ export class ServerSettingsRepo implements Settings {
attachmentTotalMb: this.getAttachmentTotalMb(),
};
}
+
+ /**
+ * Company mode master switch (default OFF): an absent row — and an unreadable one — means
+ * off, so the whole mode stays out of the way until an admin turns it on under
+ * System settings > Server > Company mode.
+ */
+ getCompanyMode(): boolean {
+ const raw = this.get(COMPANY_MODE_KEY);
+ if (raw === null) return false;
+ try {
+ return JSON.parse(raw) === true;
+ } catch {
+ return false;
+ }
+ }
+
+ setCompanyMode(value: boolean): void {
+ this.set(COMPANY_MODE_KEY, JSON.stringify(value));
+ }
}
diff --git a/packages/server/src/db/repos/sessions.ts b/packages/server/src/db/repos/sessions.ts
index 9ef1e287..bfc7577f 100644
--- a/packages/server/src/db/repos/sessions.ts
+++ b/packages/server/src/db/repos/sessions.ts
@@ -30,14 +30,17 @@ export interface SessionRow {
archivedAt?: string | null;
/**
* Creating client: "web" (created via the Web App), "cli" (created through the API by
- * the CLI, or adopted from a Trace a legacy CLI-direct run left behind); NULL = legacy
- * row from before the column existed, treated as web. Informational provenance only —
- * no list filters on it. The schedule/subagent SOURCE is deliberately NOT a row field —
- * core session_meta in the Trace stays the single source of truth for it
+ * the CLI, or adopted from a Trace a legacy CLI-direct run left behind), "org" (opened by
+ * the organization runtime — a desk or a ticket session); NULL = legacy row from before
+ * the column existed, treated as web. Free text in SQLite, so a new value needs no
+ * migration. Provenance that outlives its organization: development mode's list is the
+ * one reader that filters on it, and it hides "org" rows whether or not the organization
+ * still exists. The schedule/subagent SOURCE is deliberately NOT a row field — core
+ * session_meta in the Trace stays the single source of truth for it
* (runtime/session-sources.ts); `client` is a separate, DB-only axis that meta never
* records.
*/
- client?: "web" | "cli" | null;
+ client?: "web" | "cli" | "org" | null;
/** Cache: a Trace record exists (set at task start / adoption / subagent registration; backfilled by list hydration). */
hasTrace?: boolean;
/**
@@ -64,7 +67,7 @@ function mapRow(r: Record<string, unknown>): SessionRow {
thinkingLevel: (r.thinking_level as ThinkingLevelName | null) ?? null,
title: (r.title as string | null) ?? null,
archivedAt: (r.archived_at as string | null) ?? null,
- client: (r.client as "web" | "cli" | null) ?? null,
+ client: (r.client as "web" | "cli" | "org" | null) ?? null,
hasTrace: (r.has_trace as number) === 1,
// The open-time backfill leaves no NULLs; the coalesce only hardens against a row
// somehow inserted as NULL (degrades to createdAt instead of surfacing undefined).
@@ -146,6 +149,24 @@ export class SessionsRepo implements SessionIndex {
);
}
+ /**
+ * Stamp `client = "org"` on the rows an organization's files name, leaving the ones
+ * already stamped alone. The reconcile pass calls it with every session the desk ledger
+ * and the tickets' `Sessions` headers claim, so a row opened before the marker existed
+ * carries the organization's provenance from the next pass on — and keeps it when the
+ * organization is deleted or company mode is switched off, which is exactly when the
+ * organization caches can no longer answer for it. Chunked because the id list is
+ * unbounded while SQLite's parameter count is not.
+ */
+ markOrgClient(sessionIds: readonly string[]): void {
+ const stmt = (n: number): string =>
+ `UPDATE sessions SET client = 'org' WHERE session_id IN (${Array.from({ length: n }, () => "?").join(", ")}) AND client IS NOT 'org'`;
+ for (let i = 0; i < sessionIds.length; i += 400) {
+ const chunk = sessionIds.slice(i, i + 400);
+ this.db.prepare(stmt(chunk.length)).run(...chunk);
+ }
+ }
+
/** Flip the has_trace cache once a Trace record exists (discovery hydration); idempotent. */
markHasTrace(sessionId: string): void {
this.db.prepare("UPDATE sessions SET has_trace = 1 WHERE session_id = ?").run(sessionId);
diff --git a/packages/server/src/db/repos/usage.ts b/packages/server/src/db/repos/usage.ts
index 03fa0a5d..343c8e36 100644
--- a/packages/server/src/db/repos/usage.ts
+++ b/packages/server/src/db/repos/usage.ts
@@ -40,6 +40,8 @@ export interface UsageFilter {
/** Provider filter paired with modelId (the frontend dropdown always sends them together). */
provider?: string;
modelId?: string;
+ /** Restrict to these sessions (company mode attributes cost by the sessions an organization owns); an empty list matches nothing. */
+ sessionIds?: readonly string[];
}
/** Raw Token sums for a single Model (paired reference) — the smallest unit for cost conversion. */
@@ -247,6 +249,17 @@ export class UsageRepo implements UsageStore {
conds.push("model_id = :modelId");
params.modelId = f.modelId;
}
+ if (f.sessionIds !== undefined) {
+ if (f.sessionIds.length === 0) {
+ conds.push("0");
+ } else {
+ const keys = f.sessionIds.map((id, i) => {
+ params[`s${i}`] = id;
+ return `:s${i}`;
+ });
+ conds.push(`session_id IN (${keys.join(", ")})`);
+ }
+ }
return { where: conds.join(" AND "), params };
}
diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts
index fa6041ab..303fd9b2 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -185,4 +185,83 @@ CREATE TABLE IF NOT EXISTS trace_sessions ( -- per-session facts read ONCE at
meta_read INTEGER NOT NULL DEFAULT 0 -- 1 once the head parsed; 0 = facts unknown, retried by the next reconcile that touches the session
);
CREATE INDEX IF NOT EXISTS idx_trace_sessions_agent ON trace_sessions(project_id, agent_id);
+CREATE TABLE IF NOT EXISTS org_sessions ( -- DERIVED CACHE (company mode): desk sessions, rebuilt from each organization's desks.toml (current + previous); trigger_hop is mention-chain accounting and reads 0 after a rebuild
+ session_id TEXT PRIMARY KEY,
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ current INTEGER NOT NULL DEFAULT 1,
+ trigger_hop INTEGER NOT NULL DEFAULT 0
+);
+CREATE INDEX IF NOT EXISTS idx_org_sessions_org ON org_sessions(project_id, org_id);
+CREATE TABLE IF NOT EXISTS org_ticket_sessions ( -- DERIVED CACHE (company mode): ticket <-> contributing session, rebuilt from each ticket's Sessions header
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ ticket_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ trigger_hop INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (project_id, org_id, ticket_id, session_id)
+);
+CREATE INDEX IF NOT EXISTS idx_org_ticket_sessions_session ON org_ticket_sessions(session_id);
+CREATE TABLE IF NOT EXISTS org_calendar_state ( -- calendar run state (company mode; the files are declarative intent), same rules as schedule_state
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ name TEXT NOT NULL,
+ start_at_ms INTEGER NOT NULL,
+ def_hash TEXT NOT NULL,
+ last_slot_ms INTEGER,
+ last_fired_at TEXT,
+ fired_once INTEGER NOT NULL DEFAULT 0,
+ missed INTEGER NOT NULL DEFAULT 0,
+ invalid_reason TEXT,
+ last_outcome TEXT,
+ PRIMARY KEY (project_id, org_id, agent_id, name)
+);
+CREATE TABLE IF NOT EXISTS org_ticket_state ( -- DERIVED CACHE (company mode): the last (status, owner, blocked) seen per ticket, so a change is notified once; rebuilt silently from the ticket files
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ ticket_id TEXT NOT NULL,
+ status TEXT NOT NULL,
+ owner TEXT NOT NULL DEFAULT '',
+ blocked TEXT NOT NULL DEFAULT '',
+ blocked_by TEXT NOT NULL DEFAULT '',
+ PRIMARY KEY (project_id, org_id, ticket_id)
+);
+CREATE TABLE IF NOT EXISTS org_channel_state ( -- DERIVED CACHE (company mode): tail-scan byte cursor per channel and day file
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ channel_id TEXT NOT NULL,
+ date TEXT NOT NULL,
+ offset_bytes INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (project_id, org_id, channel_id, date)
+);
+CREATE TABLE IF NOT EXISTS org_channel_reads ( -- user data (company mode): each user's read cursor in one channel
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ channel_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ last_read_id TEXT NOT NULL,
+ PRIMARY KEY (project_id, org_id, channel_id, user_id)
+);
+CREATE TABLE IF NOT EXISTS org_budget_state ( -- DERIVED CACHE (company mode): warn / pause marks per employee and period, recomputed from usage and the chart's budgets
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ period TEXT NOT NULL,
+ warned_at TEXT,
+ paused_at TEXT,
+ PRIMARY KEY (project_id, org_id, agent_id, period)
+);
+CREATE TABLE IF NOT EXISTS org_desk_notices ( -- DERIVED CACHE (company mode): ticket changes waiting for an employee's next calendar sweep; dropping it loses only the digests not delivered yet
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ ticket_id TEXT NOT NULL,
+ change TEXT NOT NULL,
+ at TEXT NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_org_desk_notices_agent ON org_desk_notices(project_id, org_id, agent_id);
`;
diff --git a/packages/server/src/http/routes/admin-settings.ts b/packages/server/src/http/routes/admin-settings.ts
index 0782f7a1..03ead49b 100644
--- a/packages/server/src/http/routes/admin-settings.ts
+++ b/packages/server/src/http/routes/admin-settings.ts
@@ -92,6 +92,7 @@ export function adminSettingsRoutes(deps: AdminSettingsRouteDeps): Hono<AppEnv>
proxyForAgent: deps.serverSettingsRepo.getProxyForAgent(),
proxyUrl: deps.serverSettingsRepo.getProxyUrl(),
...deps.serverSettingsRepo.getAttachmentLimitsMb(),
+ companyMode: deps.serverSettingsRepo.getCompanyMode(),
},
});
@@ -103,6 +104,7 @@ export function adminSettingsRoutes(deps: AdminSettingsRouteDeps): Hono<AppEnv>
// field must leave the others untouched too.
const proxyForApp = optionalBoolean(body, "proxyForApp");
const proxyForAgent = optionalBoolean(body, "proxyForAgent");
+ const companyMode = optionalBoolean(body, "companyMode");
const proxyUrlProvided = body.proxyUrl !== undefined;
const proxyUrl = proxyUrlProvided ? parseProxyUrl(body.proxyUrl) : null;
const attachmentMaxMb =
@@ -127,6 +129,9 @@ export function adminSettingsRoutes(deps: AdminSettingsRouteDeps): Hono<AppEnv>
`attachmentTotalMb (${effectiveTotal}) must not be below attachmentMaxMb (${effectiveMax}).`,
);
}
+ // Read per tick by the organization scheduler and per request by the organization routes, so
+ // flipping it needs no restart: off holds every automatic trigger and 404s the routes.
+ if (companyMode !== undefined) deps.serverSettingsRepo.setCompanyMode(companyMode);
if (proxyForApp !== undefined) deps.serverSettingsRepo.setProxyForApp(proxyForApp);
if (proxyForAgent !== undefined) deps.serverSettingsRepo.setProxyForAgent(proxyForAgent);
if (proxyUrlProvided) deps.serverSettingsRepo.setProxyUrl(proxyUrl);
diff --git a/packages/server/src/http/routes/me.ts b/packages/server/src/http/routes/me.ts
index 02694040..9632bd8b 100644
--- a/packages/server/src/http/routes/me.ts
+++ b/packages/server/src/http/routes/me.ts
@@ -145,6 +145,7 @@ export function meRoutes(deps: MeRouteDeps): Hono<AppEnv> {
attachmentLimitMinMb: MIN_ATTACHMENT_MB,
attachmentLimitMaxMb: MAX_ATTACHMENT_MB,
},
+ companyMode: deps.serverSettingsRepo.getCompanyMode(),
} satisfies MeResponse);
});
diff --git a/packages/server/src/http/routes/organizations.ts b/packages/server/src/http/routes/organizations.ts
new file mode 100644
index 00000000..736a42bd
--- /dev/null
+++ b/packages/server/src/http/routes/organizations.ts
@@ -0,0 +1,962 @@
+/**
+ * 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
+ * PATCH|DELETE …/:orgId/employees/:agentId
+ * GET|POST …/:orgId/employees/:agentId/desk # the desk session (GET opens it if needed; POST renews)
+ * GET|PUT …/:orgId/handbook (the index, handbook/README.md)
+ * GET …/:orgId/handbook/files
+ * GET|PUT|DELETE …/:orgId/handbook/files/<path>
+ * GET|POST …/:orgId/calendar ; GET|PUT|DELETE …/:orgId/calendar/:agentId/:name
+ * GET|POST …/:orgId/tickets ; GET|PUT …/:orgId/tickets/:ticketId
+ * POST …/:orgId/tickets/:ticketId/(move|block|unblock|progress|start|attach)
+ * GET|POST …/:orgId/channels ; GET|PATCH …/:orgId/channels/:channelId
+ * POST …/:orgId/channels/:channelId/members
+ * DELETE …/:orgId/channels/:channelId/members/:principal
+ * GET|POST …/:orgId/channels/:channelId/messages ; POST …/:orgId/channels/:channelId/read
+ * GET …/:orgId/finance ; GET …/:orgId/sessions
+ *
+ * Authorization is the Project's: any member reads and writes (tickets, channels, calendar, the
+ * tree, the handbook) and creates organizations, like creating an Agent. There is no route
+ * that deletes an organization: `status` (`active` / `paused`) is its whole lifecycle, so the
+ * conversations, employees, desks and tickets of an organization that is switched off stay
+ * reachable. Every route answers 404 while the admin master switch is off. A write carries the
+ * caller's Agent id and session id when it comes from inside a session (the CLI's control
+ * environment), so the file records the employee rather than the token's user — see
+ * {@link callerSessionId} for why only the control environment may make that claim.
+ */
+import { Hono } from "hono";
+import type { Context } from "hono";
+import { isValidId } from "@prismshadow/penguin-core";
+import type {
+ OrgApprovalMode,
+ OrgLanguage,
+ OrgStatus,
+ OrgTicketPriority,
+ OrgTicketStatus,
+ OrganizationsResponse,
+ SemanticIdSuggestRequest,
+} from "../../api/types.js";
+import type { AppEnv } from "../../auth/middleware.js";
+import type { SessionVia } from "../../auth/service.js";
+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Settings } from "../../mechanisms/settings.js";
+import type { ProjectLifecycle } from "../../mechanisms/projects.js";
+import { TICKET_ID_PATTERN } from "../../organization/files.js";
+import { ORG_TICKET_COLUMNS, isCalendarEventName, isChannelId } from "../../organization/paths.js";
+import { parsePrincipal } from "../../organization/principal.js";
+import type { Actor, OrgService } from "../../runtime/organization/service.js";
+import { HttpError } from "../errors.js";
+import {
+ badRequest,
+ optionalBoolean,
+ optionalEnum,
+ optionalNumber,
+ optionalString,
+ optionalStringArray,
+ readJson,
+ requireEnum,
+ requireString,
+ requireValidId,
+} from "../validate.js";
+
+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.");
+ return raw;
+}
+
+function requireName(raw: string | undefined, label: string): string {
+ if (!raw || !isValidId(raw)) throw badRequest(`Invalid ${label}.`);
+ return raw;
+}
+
+/** A calendar event name must be one the store lists, or the file would be written and never read. */
+function requireEventName(raw: string | undefined): string {
+ if (!raw || !isCalendarEventName(raw)) throw badRequest("Invalid name.");
+ return raw;
+}
+
+/** A nullable optional string field: absent → undefined, null → null (clear), string → validated. */
+function nullableString(
+ body: Record<string, unknown>,
+ key: string,
+ rule: { maxLen?: number } = {},
+): string | null | undefined {
+ if (body[key] === null) return null;
+ return optionalString(body, key, { minLen: 1, maxLen: rule.maxLen ?? 200 });
+}
+
+/**
+ * The body's `sessionId` is an identity claim — "this write comes from inside that Session" —
+ * and the only credential that backs it is the boot's local API token: `controlEnv` (app.ts)
+ * hands it to a Session's subprocesses together with PENGUIN_SESSION_ID, and holding it is
+ * already admin authority. A cookie proves a person, not a session, so a cookie-authenticated
+ * claim is dropped and the write is attributed to that person; otherwise any Project member
+ * could quote the CEO desk session id `GET /:orgId` returns and write as `agent:<org>_ceo`.
+ * Dropped rather than rejected because the field is not always a claim: `tickets/:id/attach`
+ * takes the Session to attach in the same field, and the Web App sends it over a cookie.
+ */
+function callerSessionId(
+ c: { var: { sessionVia: SessionVia } },
+ body: Record<string, unknown>,
+): string | undefined {
+ const sessionId = optionalString(body, "sessionId", { minLen: 1, maxLen: 200 });
+ return c.var.sessionVia === "token" ? sessionId : undefined;
+}
+
+/**
+ * Who performs this write. `agentId` is the same kind of identity claim as `sessionId` — the
+ * `PENGUIN_AGENT_ID` a Session hands its command subprocesses — and is backed by the same
+ * credential, so a cookie-authenticated body's `agentId` is dropped. It names the operator
+ * more precisely than the session does, so the service prefers it.
+ *
+ * `identityAgentId: false` is for the one route whose body already uses `agentId` for
+ * something else: `tickets/:id/start` names there the employee the ticket session is to run
+ * as, which may be a colleague the owner enlists — reading it as the caller would hand the
+ * ownership check the wrong principal.
+ */
+function actorOf(
+ c: { var: { user: { userId: string }; sessionVia: SessionVia } },
+ body: Record<string, unknown>,
+ opts: { identityAgentId?: boolean } = {},
+): Actor {
+ const sessionId = callerSessionId(c, body);
+ const agentId =
+ opts.identityAgentId !== false && c.var.sessionVia === "token"
+ ? optionalString(body, "agentId", { minLen: 2, maxLen: 64 })
+ : undefined;
+ return {
+ userId: c.var.user.userId,
+ ...(sessionId !== undefined ? { sessionId } : {}),
+ ...(agentId !== undefined ? { agentId } : {}),
+ };
+}
+
+/**
+ * The same identity claim on a read, where there is no body to carry it: `?sessionId=` and
+ * `?agentId=` are how a desk or ticket session asks "which channels am I in". Both are backed
+ * by exactly the credential {@link callerSessionId} requires — the boot's local API token —
+ * so a cookie request's query parameters are dropped and the read is answered as that person.
+ */
+function actorOfQuery(c: Context<AppEnv>): Actor {
+ const byToken = c.var.sessionVia === "token";
+ const sessionId = c.req.query("sessionId");
+ const agentId = c.req.query("agentId");
+ return {
+ userId: c.var.user.userId,
+ ...(byToken && sessionId !== undefined && sessionId !== "" ? { sessionId } : {}),
+ ...(byToken && agentId !== undefined && agentId !== "" ? { agentId } : {}),
+ };
+}
+
+/** A channel id in the path: an id no channel could carry names no channel. */
+function requireChannelParam(c: Context<AppEnv>): string {
+ const raw = c.req.param("channelId");
+ if (raw === undefined || !isChannelId(raw)) {
+ throw new HttpError(404, "channel_not_found", "Channel does not exist.");
+ }
+ return raw;
+}
+
+/** What this route group needs — declared here, at the consumer. */
+export interface OrgRouteDeps {
+ orgService: OrgService;
+ projectService: Pick<ProjectLifecycle, "requireProjectAccess">;
+ serverSettingsRepo: Pick<Settings, "getCompanyMode">;
+}
+
+export function organizationRoutes(deps: OrgRouteDeps): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+
+ app.use("*", async (c, next) => {
+ if (!deps.serverSettingsRepo.getCompanyMode()) {
+ throw new HttpError(404, "company_mode_off", "Company mode is turned off on this server.");
+ }
+ await next();
+ });
+
+ const member = (c: { var: { user: { userId: string } } }, projectId: string): void => {
+ deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ };
+
+ // ---- organizations ----
+
+ app.get("/", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ member(c, projectId);
+ const res: OrganizationsResponse = { organizations: await deps.orgService.list(projectId) };
+ return c.json(res);
+ });
+
+ app.post("/", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ member(c, projectId);
+ const body = await readJson(c);
+ const orgId = requireString(body, "orgId", { minLen: 2, maxLen: 64 });
+ const mission = requireString(body, "mission", { minLen: 1, maxLen: 4000 });
+ const name = optionalString(body, "name", { minLen: 1, maxLen: 100 });
+ const timezone = optionalString(body, "timezone", { minLen: 1, maxLen: 64 });
+ const workspace = optionalString(body, "workspace", { minLen: 1, maxLen: 4096 });
+ const ceoBudget = optionalNumber(body, "ceoBudget", { nonNegative: true });
+ const language = optionalEnum(body, "language", LANGUAGES);
+ const model = parseModel(body);
+ const detail = await deps.orgService.create(
+ projectId,
+ {
+ orgId,
+ mission,
+ ...(name !== undefined ? { name } : {}),
+ ...(timezone !== undefined ? { timezone } : {}),
+ ...(workspace !== undefined ? { workspace } : {}),
+ ...(ceoBudget !== undefined ? { ceoBudget } : {}),
+ ...(language !== undefined ? { language } : {}),
+ ...(model !== undefined && model !== null ? { model } : {}),
+ },
+ c.var.user.userId,
+ );
+ 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");
+ member(c, projectId);
+ return c.json(await deps.orgService.detail(projectId, orgId, c.var.user.userId));
+ });
+
+ app.patch("/:orgId", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ member(c, projectId);
+ const body = await readJson(c);
+ const name = optionalString(body, "name", { minLen: 1, maxLen: 100 });
+ const mission = optionalString(body, "mission", { minLen: 1, maxLen: 4000 });
+ const status = optionalEnum(body, "status", STATUSES);
+ const approvalMode = optionalEnum(body, "approvalMode", APPROVAL_MODES);
+ const timezone = optionalString(body, "timezone", { minLen: 1, maxLen: 64 });
+ const language = optionalEnum(body, "language", LANGUAGES);
+ const mentionChainLimit = optionalNumber(body, "mentionChainLimit", {
+ integer: true,
+ nonNegative: true,
+ });
+ const budgetWarnRatio = optionalNumber(body, "budgetWarnRatio", { nonNegative: true });
+ const budgetPauseRatio = optionalNumber(body, "budgetPauseRatio", { nonNegative: true });
+ const workspace =
+ body.workspace === null
+ ? null
+ : optionalString(body, "workspace", { minLen: 1, maxLen: 4096 });
+ const model = parseModel(body);
+ const settings = await deps.orgService.patch(
+ projectId,
+ orgId,
+ {
+ ...(name !== undefined ? { name } : {}),
+ ...(mission !== undefined ? { mission } : {}),
+ ...(status !== undefined ? { status } : {}),
+ ...(approvalMode !== undefined ? { approvalMode } : {}),
+ ...(timezone !== undefined ? { timezone } : {}),
+ ...(language !== undefined ? { language } : {}),
+ ...(mentionChainLimit !== undefined ? { mentionChainLimit } : {}),
+ ...(budgetWarnRatio !== undefined ? { budgetWarnRatio } : {}),
+ ...(budgetPauseRatio !== undefined ? { budgetPauseRatio } : {}),
+ ...(workspace !== undefined ? { workspace } : {}),
+ ...(model !== undefined ? { model } : {}),
+ },
+ c.var.user.userId,
+ );
+ return c.json(settings);
+ });
+
+ // ---- employees ----
+
+ app.get("/:orgId/chart", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ member(c, projectId);
+ return c.json(await deps.orgService.chart(projectId, orgId));
+ });
+
+ app.post("/:orgId/employees", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ member(c, projectId);
+ const body = await readJson(c);
+ const agentId = optionalString(body, "agentId", { minLen: 2, maxLen: 64 });
+ let newAgent:
+ { agentId: string; name?: string; description?: string; plugins?: string[] } | undefined;
+ if (body.newAgent !== undefined) {
+ if (body.newAgent === null || typeof body.newAgent !== "object")
+ throw badRequest("newAgent must be an object.");
+ const n = body.newAgent as Record<string, unknown>;
+ const id = requireString(n, "agentId", { minLen: 2, maxLen: 64, label: "newAgent.agentId" });
+ const name = optionalString(n, "name", { minLen: 1, maxLen: 100, label: "newAgent.name" });
+ const description = optionalString(n, "description", {
+ maxLen: 2000,
+ label: "newAgent.description",
+ });
+ const plugins = optionalStringArray(n, "plugins", "newAgent.plugins");
+ newAgent = {
+ agentId: id,
+ ...(name !== undefined ? { name } : {}),
+ ...(description !== undefined ? { description } : {}),
+ ...(plugins !== undefined ? { plugins } : {}),
+ };
+ }
+ const title = requireString(body, "title", { minLen: 1, maxLen: 100 });
+ const reportsTo = requireString(body, "reportsTo", { minLen: 2, maxLen: 64 });
+ const workspace = optionalString(body, "workspace", { minLen: 1, maxLen: 4096 });
+ const budget = optionalNumber(body, "budget", { nonNegative: true });
+ const duties = optionalString(body, "duties", { maxLen: 2000 });
+ const model = parseModel(body);
+ const item = await deps.orgService.hire(projectId, orgId, {
+ ...(agentId !== undefined ? { agentId } : {}),
+ ...(newAgent !== undefined ? { newAgent } : {}),
+ title,
+ reportsTo,
+ ...(workspace !== undefined ? { workspace } : {}),
+ ...(budget !== undefined ? { budget } : {}),
+ ...(duties !== undefined ? { duties } : {}),
+ ...(model !== undefined && model !== null ? { model } : {}),
+ });
+ return c.json(item, 201);
+ });
+
+ app.patch("/:orgId/employees/:agentId", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const agentId = requireValidId(c, "agentId");
+ member(c, projectId);
+ const body = await readJson(c);
+ const title = optionalString(body, "title", { minLen: 1, maxLen: 100 });
+ const reportsTo = optionalString(body, "reportsTo", { minLen: 2, maxLen: 64 });
+ const workspace = optionalString(body, "workspace", { minLen: 1, maxLen: 4096 });
+ const budget =
+ body.budget === null ? null : optionalNumber(body, "budget", { nonNegative: true });
+ const duties = optionalString(body, "duties", { maxLen: 2000 });
+ const model = parseModel(body);
+ const item = await deps.orgService.patchEmployee(projectId, orgId, agentId, {
+ ...(title !== undefined ? { title } : {}),
+ ...(reportsTo !== undefined ? { reportsTo } : {}),
+ ...(workspace !== undefined ? { workspace } : {}),
+ ...(budget !== undefined ? { budget } : {}),
+ ...(duties !== undefined ? { duties } : {}),
+ ...(model !== undefined ? { model } : {}),
+ });
+ return c.json(item);
+ });
+
+ app.delete("/:orgId/employees/:agentId", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const agentId = requireValidId(c, "agentId");
+ member(c, projectId);
+ await deps.orgService.leave(projectId, orgId, agentId);
+ return c.body(null, 204);
+ });
+
+ app.get("/:orgId/employees/:agentId/desk", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const agentId = requireValidId(c, "agentId");
+ member(c, projectId);
+ return c.json(await deps.orgService.desk(projectId, orgId, agentId, {}));
+ });
+
+ app.post("/:orgId/employees/:agentId/desk", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const agentId = requireValidId(c, "agentId");
+ member(c, projectId);
+ return c.json(await deps.orgService.desk(projectId, orgId, agentId, { renew: true }), 201);
+ });
+
+ // ---- handbook ----
+
+ app.get("/:orgId/handbook", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ member(c, projectId);
+ return c.json({ content: await deps.orgService.handbook(projectId, orgId) });
+ });
+
+ app.put("/:orgId/handbook", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ member(c, projectId);
+ const body = await readJson(c);
+ const content = requireString(body, "content", { maxLen: 200_000 });
+ await deps.orgService.writeHandbook(projectId, orgId, content);
+ return c.json({ content });
+ });
+
+ app.get("/:orgId/handbook/files", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ member(c, projectId);
+ return c.json(await deps.orgService.handbookFiles(projectId, orgId));
+ });
+
+ app.get("/:orgId/handbook/files/:path{.+}", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ member(c, projectId);
+ return c.json(await deps.orgService.handbookFile(projectId, orgId, c.req.param("path")));
+ });
+
+ app.put("/:orgId/handbook/files/:path{.+}", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ member(c, projectId);
+ const body = await readJson(c);
+ const content = requireString(body, "content", { maxLen: 200_000 });
+ return c.json(
+ await deps.orgService.writeHandbookFile(projectId, orgId, c.req.param("path"), content),
+ );
+ });
+
+ app.delete("/:orgId/handbook/files/:path{.+}", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ member(c, projectId);
+ await deps.orgService.deleteHandbookFile(projectId, orgId, c.req.param("path"));
+ return c.body(null, 204);
+ });
+
+ // ---- calendar ----
+
+ const calendarFields = (body: Record<string, unknown>) => {
+ if (typeof body.enabled !== "boolean") throw badRequest("enabled must be a boolean.");
+ const title = optionalString(body, "title", { minLen: 1, maxLen: 200 });
+ const period = optionalString(body, "period", { minLen: 1, maxLen: 20 });
+ const endAt = optionalString(body, "endAt", { minLen: 1, maxLen: 100 });
+ return {
+ ...(title !== undefined ? { title } : {}),
+ prompt: requireString(body, "prompt", { minLen: 1, maxLen: 100_000 }),
+ enabled: body.enabled,
+ startAt: requireString(body, "startAt", { minLen: 1, maxLen: 100 }),
+ ...(period !== undefined ? { period } : {}),
+ ...(endAt !== undefined ? { endAt } : {}),
+ };
+ };
+
+ app.get("/:orgId/calendar", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ member(c, projectId);
+ return c.json(await deps.orgService.calendar(projectId, orgId));
+ });
+
+ app.post("/:orgId/calendar", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ member(c, projectId);
+ const body = await readJson(c);
+ const agentId = requireName(
+ requireString(body, "agentId", { minLen: 2, maxLen: 64 }),
+ "agentId",
+ );
+ const name = requireEventName(requireString(body, "name", { minLen: 1, maxLen: 100 }));
+ const item = await deps.orgService.upsertCalendar(
+ projectId,
+ orgId,
+ agentId,
+ name,
+ calendarFields(body),
+ {
+ create: true,
+ },
+ );
+ return c.json(item, 201);
+ });
+
+ app.get("/:orgId/calendar/:agentId/:name", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const agentId = requireValidId(c, "agentId");
+ const name = requireEventName(c.req.param("name"));
+ member(c, projectId);
+ const list = await deps.orgService.calendar(projectId, orgId);
+ const item = list.events.find((e) => e.agentId === agentId && e.name === name);
+ if (!item)
+ throw new HttpError(
+ 404,
+ "calendar_event_not_found",
+ `Calendar event does not exist: ${agentId}/${name}`,
+ );
+ return c.json(item);
+ });
+
+ app.put("/:orgId/calendar/:agentId/:name", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const agentId = requireValidId(c, "agentId");
+ const name = requireEventName(c.req.param("name"));
+ member(c, projectId);
+ const body = await readJson(c);
+ return c.json(
+ await deps.orgService.upsertCalendar(projectId, orgId, agentId, name, calendarFields(body), {
+ create: false,
+ }),
+ );
+ });
+
+ app.delete("/:orgId/calendar/:agentId/:name", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const agentId = requireValidId(c, "agentId");
+ const name = requireEventName(c.req.param("name"));
+ member(c, projectId);
+ await deps.orgService.deleteCalendar(projectId, orgId, agentId, name);
+ return c.body(null, 204);
+ });
+
+ // ---- tickets ----
+
+ app.get("/:orgId/tickets", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ member(c, projectId);
+ return c.json(await deps.orgService.tickets(projectId, orgId));
+ });
+
+ app.post("/:orgId/tickets", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ member(c, projectId);
+ const body = await readJson(c);
+ const title = requireString(body, "title", { minLen: 1, maxLen: 200 });
+ const slug = optionalString(body, "slug", { minLen: 1, maxLen: 64 });
+ const goal = optionalString(body, "goal", { maxLen: 100_000 });
+ const acceptanceCriteria = optionalString(body, "acceptanceCriteria", { maxLen: 100_000 });
+ const text = optionalString(body, "body", { maxLen: 200_000 });
+ // Absent means "the caller owns it"; an empty string is no principal at all.
+ const owner = optionalString(body, "owner", { minLen: 1, maxLen: 100 });
+ const parent = optionalString(body, "parent", { minLen: 1, maxLen: 100 });
+ const notify = optionalStringArray(body, "notify");
+ const priority = optionalEnum(body, "priority", PRIORITIES);
+ const due = optionalString(body, "due", { minLen: 10, maxLen: 40 });
+ const detail = await deps.orgService.createTicket(
+ projectId,
+ orgId,
+ {
+ title,
+ ...(slug !== undefined ? { slug } : {}),
+ ...(goal !== undefined ? { goal } : {}),
+ ...(acceptanceCriteria !== undefined ? { acceptanceCriteria } : {}),
+ ...(text !== undefined ? { body: text } : {}),
+ ...(owner !== undefined ? { owner } : {}),
+ ...(parent !== undefined ? { parent: requireTicketId(parent) } : {}),
+ ...(notify !== undefined ? { notify } : {}),
+ ...(priority !== undefined ? { priority } : {}),
+ ...(due !== undefined ? { due } : {}),
+ },
+ actorOf(c, body),
+ );
+ return c.json(detail, 201);
+ });
+
+ app.get("/:orgId/tickets/:ticketId", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const ticketId = requireTicketId(c.req.param("ticketId"));
+ member(c, projectId);
+ return c.json(await deps.orgService.ticket(projectId, orgId, ticketId));
+ });
+
+ app.put("/:orgId/tickets/:ticketId", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const ticketId = requireTicketId(c.req.param("ticketId"));
+ member(c, projectId);
+ const body = await readJson(c);
+ const title = optionalString(body, "title", { minLen: 1, maxLen: 200 });
+ // No null: a ticket always has an owner — reassign it, never clear it.
+ const owner = optionalString(body, "owner", { minLen: 1, maxLen: 100 });
+ const parent = nullableString(body, "parent", { maxLen: 100 });
+ const notify = optionalStringArray(body, "notify");
+ const priority = optionalEnum(body, "priority", PRIORITIES);
+ const due = nullableString(body, "due", { maxLen: 40 });
+ const goal = optionalString(body, "goal", { maxLen: 100_000 });
+ const acceptanceCriteria = optionalString(body, "acceptanceCriteria", { maxLen: 100_000 });
+ const result = optionalString(body, "result", { maxLen: 100_000 });
+ const detail = await deps.orgService.updateTicket(
+ projectId,
+ orgId,
+ ticketId,
+ {
+ ...(title !== undefined ? { title } : {}),
+ ...(owner !== undefined ? { owner } : {}),
+ ...(parent !== undefined
+ ? { parent: parent === null ? null : requireTicketId(parent) }
+ : {}),
+ ...(notify !== undefined ? { notify } : {}),
+ ...(priority !== undefined ? { priority } : {}),
+ ...(due !== undefined ? { due } : {}),
+ ...(goal !== undefined ? { goal } : {}),
+ ...(acceptanceCriteria !== undefined ? { acceptanceCriteria } : {}),
+ ...(result !== undefined ? { result } : {}),
+ },
+ actorOf(c, body),
+ );
+ return c.json(detail);
+ });
+
+ app.post("/:orgId/tickets/:ticketId/move", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const ticketId = requireTicketId(c.req.param("ticketId"));
+ member(c, projectId);
+ const body = await readJson(c);
+ const status = requireEnum(body, "status", ORG_TICKET_COLUMNS as readonly OrgTicketStatus[]);
+ const reason = optionalString(body, "reason", { maxLen: 4000 });
+ return c.json(
+ await deps.orgService.moveTicket(
+ projectId,
+ orgId,
+ ticketId,
+ status,
+ reason,
+ actorOf(c, body),
+ ),
+ );
+ });
+
+ app.post("/:orgId/tickets/:ticketId/block", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const ticketId = requireTicketId(c.req.param("ticketId"));
+ member(c, projectId);
+ const body = await readJson(c);
+ const reason = requireString(body, "reason", { minLen: 1, maxLen: 2000 });
+ const by = optionalString(body, "by", { minLen: 1, maxLen: 100 });
+ return c.json(
+ await deps.orgService.blockTicket(projectId, orgId, ticketId, reason, by, actorOf(c, body)),
+ );
+ });
+
+ app.post("/:orgId/tickets/:ticketId/unblock", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const ticketId = requireTicketId(c.req.param("ticketId"));
+ member(c, projectId);
+ const body = await readJson(c).catch(() => ({}) as Record<string, unknown>);
+ return c.json(
+ await deps.orgService.unblockTicket(projectId, orgId, ticketId, actorOf(c, body)),
+ );
+ });
+
+ app.post("/:orgId/tickets/:ticketId/progress", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const ticketId = requireTicketId(c.req.param("ticketId"));
+ member(c, projectId);
+ const body = await readJson(c);
+ const text = requireString(body, "text", { minLen: 1, maxLen: 4000 });
+ return c.json(
+ await deps.orgService.progressTicket(projectId, orgId, ticketId, text, actorOf(c, body)),
+ );
+ });
+
+ app.post("/:orgId/tickets/:ticketId/start", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const ticketId = requireTicketId(c.req.param("ticketId"));
+ member(c, projectId);
+ const body = await readJson(c).catch(() => ({}) as Record<string, unknown>);
+ const agentId = optionalString(body, "agentId", { minLen: 2, maxLen: 64 });
+ const message = optionalString(body, "message", { maxLen: 100_000 });
+ const workspace = optionalString(body, "workspace", { minLen: 1, maxLen: 4096 });
+ const res = await deps.orgService.startTicket(
+ projectId,
+ orgId,
+ ticketId,
+ {
+ ...(agentId !== undefined ? { agentId } : {}),
+ ...(message !== undefined ? { message } : {}),
+ ...(workspace !== undefined ? { workspace } : {}),
+ },
+ // Who asks decides whether it may: an employee starts sessions only on its own tickets.
+ // The body's `agentId` is the employee to run AS, not the caller, so it is not identity.
+ actorOf(c, body, { identityAgentId: false }),
+ );
+ return c.json(res, 202);
+ });
+
+ app.post("/:orgId/tickets/:ticketId/attach", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const ticketId = requireTicketId(c.req.param("ticketId"));
+ member(c, projectId);
+ const body = await readJson(c);
+ const sessionId = requireString(body, "sessionId", { minLen: 1, maxLen: 200 });
+ return c.json(
+ await deps.orgService.attachTicket(projectId, orgId, ticketId, sessionId, actorOf(c, body)),
+ );
+ });
+
+ // ---- channels ----
+
+ app.get("/:orgId/channels", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ member(c, projectId);
+ return c.json(await deps.orgService.channels(projectId, orgId, actorOfQuery(c)));
+ });
+
+ app.post("/:orgId/channels", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ member(c, projectId);
+ const body = await readJson(c);
+ const channelId = requireString(body, "channelId", { minLen: 2, maxLen: 64 });
+ if (!isChannelId(channelId)) throw badRequest("Invalid channel id.");
+ const name = optionalString(body, "name", { minLen: 1, maxLen: 100 });
+ const purpose = optionalString(body, "purpose", { maxLen: 2000 });
+ const item = await deps.orgService.createChannel(
+ projectId,
+ orgId,
+ {
+ channelId,
+ ...(name !== undefined ? { name } : {}),
+ ...(purpose !== undefined ? { purpose } : {}),
+ },
+ actorOf(c, body),
+ );
+ return c.json(item, 201);
+ });
+
+ app.get("/:orgId/channels/:channelId", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const channelId = requireChannelParam(c);
+ member(c, projectId);
+ return c.json(await deps.orgService.channel(projectId, orgId, channelId, actorOfQuery(c)));
+ });
+
+ app.patch("/:orgId/channels/:channelId", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const channelId = requireChannelParam(c);
+ member(c, projectId);
+ const body = await readJson(c);
+ const name = optionalString(body, "name", { minLen: 1, maxLen: 100 });
+ const purpose = optionalString(body, "purpose", { maxLen: 2000 });
+ const archived = optionalBoolean(body, "archived");
+ return c.json(
+ await deps.orgService.patchChannel(
+ projectId,
+ orgId,
+ channelId,
+ {
+ ...(name !== undefined ? { name } : {}),
+ ...(purpose !== undefined ? { purpose } : {}),
+ ...(archived !== undefined ? { archived } : {}),
+ },
+ actorOf(c, body),
+ ),
+ );
+ });
+
+ app.post("/:orgId/channels/:channelId/members", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const channelId = requireChannelParam(c);
+ member(c, projectId);
+ const body = await readJson(c);
+ const principal = requirePrincipal(
+ requireString(body, "principal", { minLen: 1, maxLen: 100 }),
+ );
+ return c.json(
+ await deps.orgService.addChannelMember(
+ projectId,
+ orgId,
+ channelId,
+ principal,
+ actorOf(c, body),
+ ),
+ 201,
+ );
+ });
+
+ app.delete("/:orgId/channels/:channelId/members/:principal", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const channelId = requireChannelParam(c);
+ member(c, projectId);
+ const principal = requirePrincipal(c.req.param("principal"));
+ await deps.orgService.removeChannelMember(
+ projectId,
+ orgId,
+ channelId,
+ principal,
+ actorOfQuery(c),
+ );
+ return c.body(null, 204);
+ });
+
+ // ---- channel messages ----
+
+ app.get("/:orgId/channels/:channelId/messages", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const channelId = requireChannelParam(c);
+ member(c, projectId);
+ const date = c.req.query("date");
+ if (date !== undefined && !/^\d{4}-\d{2}-\d{2}$/.test(date))
+ throw badRequest("date must be yyyy-mm-dd.");
+ return c.json(
+ await deps.orgService.channelMessages(projectId, orgId, actorOfQuery(c), channelId, {
+ ...(date !== undefined ? { date } : {}),
+ }),
+ );
+ });
+
+ app.post("/:orgId/channels/:channelId/messages", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const channelId = requireChannelParam(c);
+ member(c, projectId);
+ const body = await readJson(c);
+ const text = requireString(body, "text", { minLen: 1, maxLen: 20_000 });
+ const sessionId = callerSessionId(c, body);
+ let refs: { ticket?: string; session?: string; replyTo?: string } | undefined;
+ if (body.refs !== undefined && body.refs !== null) {
+ if (typeof body.refs !== "object") throw badRequest("refs must be an object.");
+ const r = body.refs as Record<string, unknown>;
+ const ticket = optionalString(r, "ticket", { minLen: 1, maxLen: 100, label: "refs.ticket" });
+ const session = optionalString(r, "session", {
+ minLen: 1,
+ maxLen: 200,
+ label: "refs.session",
+ });
+ const replyTo = optionalString(r, "replyTo", {
+ minLen: 1,
+ maxLen: 100,
+ label: "refs.replyTo",
+ });
+ refs = {
+ ...(ticket !== undefined ? { ticket } : {}),
+ ...(session !== undefined ? { session } : {}),
+ ...(replyTo !== undefined ? { replyTo } : {}),
+ };
+ }
+ const msg = await deps.orgService.sendChannelMessage(
+ projectId,
+ orgId,
+ c.var.user.userId,
+ channelId,
+ {
+ text,
+ ...(sessionId !== undefined ? { sessionId } : {}),
+ ...(refs !== undefined ? { refs } : {}),
+ },
+ );
+ return c.json(msg, 201);
+ });
+
+ app.post("/:orgId/channels/:channelId/read", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ const channelId = requireChannelParam(c);
+ member(c, projectId);
+ const body = await readJson(c);
+ const upTo = requireString(body, "upTo", { minLen: 1, maxLen: 100 });
+ await deps.orgService.markRead(projectId, orgId, c.var.user.userId, channelId, upTo);
+ return c.body(null, 204);
+ });
+
+ // ---- finance and sessions ----
+
+ app.get("/:orgId/finance", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ member(c, projectId);
+ const period = c.req.query("period");
+ if (period !== undefined && !/^\d{4}-(?:0[1-9]|1[0-2])$/.test(period))
+ throw badRequest("period must be yyyy-mm.");
+ return c.json(await deps.orgService.finance(projectId, orgId, period));
+ });
+
+ app.get("/:orgId/sessions", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const orgId = requireValidId(c, "orgId");
+ member(c, projectId);
+ return c.json(await deps.orgService.sessions(projectId, orgId));
+ });
+
+ return app;
+}
+
+/** `agent:<id>` or `user:<id>`; the service decides whether that principal exists here. */
+function requirePrincipal(raw: string | undefined): string {
+ const parsed = raw === undefined ? null : parsePrincipal(raw);
+ if (parsed === null || (parsed.kind !== "agent" && parsed.kind !== "user")) {
+ throw new HttpError(400, "invalid_principal", "principal must be agent:<id> or user:<id>.");
+ }
+ return raw!;
+}
+
+/** `model: { provider, modelId }` or `model: null` (clear); undefined when absent. */
+function parseModel(
+ body: Record<string, unknown>,
+): { provider: string; modelId: string } | null | undefined {
+ if (body.model === undefined) return undefined;
+ if (body.model === null) return null;
+ if (typeof body.model !== "object") throw badRequest("model must be an object or null.");
+ const m = body.model as Record<string, unknown>;
+ return {
+ provider: requireString(m, "provider", { minLen: 1, maxLen: 64, label: "model.provider" }),
+ modelId: requireString(m, "modelId", { minLen: 1, maxLen: 200, label: "model.modelId" }),
+ };
+}
+
+@Component({
+ contributes: {
+ "HttpModule.routes": [
+ {
+ id: "OrgRoutes.routes",
+ prefix: "/api/projects/:projectId/organizations",
+ auth: "user",
+ order: 145,
+ },
+ ],
+ },
+})
+export class OrgRoutes {
+ @Use() private readonly orgService!: OrgService;
+ @Use() private readonly projectService!: ProjectLifecycle;
+ @Use() private readonly settings!: Settings;
+ @Bind("OrgRoutes.routes") routes!: Hono<AppEnv>;
+ setup() {
+ this.routes = organizationRoutes({
+ orgService: this.orgService,
+ projectService: this.projectService,
+ serverSettingsRepo: this.settings,
+ });
+ }
+}
diff --git a/packages/server/src/mechanisms/agents.ts b/packages/server/src/mechanisms/agents.ts
index 068d14f3..05065830 100644
--- a/packages/server/src/mechanisms/agents.ts
+++ b/packages/server/src/mechanisms/agents.ts
@@ -129,4 +129,10 @@ export abstract class AgentLifecycle extends Interface<{
directory?: { path: string; names: readonly string[] },
archive?: Buffer<ArrayBufferLike>,
): Promise<AgentListItem>;
+ pluginVersion(
+ projectId: string,
+ agentId: string,
+ pluginName: string,
+ ): Promise<{ installed: string | null; library: string | null }>;
+ updatePlugin(projectId: string, agentId: string, pluginName: string): Promise<void>;
}>() {}
diff --git a/packages/server/src/mechanisms/observability.ts b/packages/server/src/mechanisms/observability.ts
index fa1d9383..fca4fbc7 100644
--- a/packages/server/src/mechanisms/observability.ts
+++ b/packages/server/src/mechanisms/observability.ts
@@ -2,6 +2,7 @@
* The observability mechanisms: what a node may require, declared apart from what implements it.
*/
import { Interface } from "@prismshadow/penguin-core/kernel";
+import type { Opaque } from "@prismshadow/penguin-core/kernel";
import type {
ErrorCodeCount,
ErrorFilter,
@@ -113,4 +114,16 @@ export abstract class UsageQueries extends Interface<{
queryErrors(projectId: string, q: UsageErrorsQuery): UsageErrorsPage;
clearErrors(projectId: string, q: UsageErrorsClearQuery): number;
modelTotals(projectId: string): UsageModelTotals;
+ costBySession(
+ projectId: string,
+ sessionIds: readonly string[],
+ fromTs: string,
+ toTs: string,
+ ): Promise<Opaque<"CostBySession", { bySession: Map<string, number>; unpriced: boolean }>>;
+ dailyCostForSessions(
+ projectId: string,
+ sessionIds: readonly string[],
+ fromTs: string,
+ toTs: string,
+ ): Promise<Array<{ date: string; cost: number }>>;
}>() {}
diff --git a/packages/server/src/mechanisms/organization.ts b/packages/server/src/mechanisms/organization.ts
new file mode 100644
index 00000000..3c47b144
--- /dev/null
+++ b/packages/server/src/mechanisms/organization.ts
@@ -0,0 +1,18 @@
+/**
+ * The organization mechanisms: what a node may require, declared apart from what
+ * implements it.
+ */
+import { Interface } from "@prismshadow/penguin-core/kernel";
+import type { Opaque } from "@prismshadow/penguin-core/kernel";
+import type { OrgCacheRepo } from "../db/repos/organizations.js";
+
+/**
+ * OrgCache: the mechanism OrgCacheRepo implements. The whole repo, except that
+ * `orgIdsOfProject` is named rather than inherited — a Map has no wire form, so the
+ * contract carries it as an opaque host object the way the kernel's other live values are.
+ */
+export abstract class OrgCache extends Interface<
+ Omit<OrgCacheRepo, "orgIdsOfProject"> & {
+ orgIdsOfProject(projectId: string): Opaque<"OrgIdsBySession", Map<string, string>>;
+ }
+>() {}
diff --git a/packages/server/src/mechanisms/projects.ts b/packages/server/src/mechanisms/projects.ts
index efebd2e6..ab8cc2e3 100644
--- a/packages/server/src/mechanisms/projects.ts
+++ b/packages/server/src/mechanisms/projects.ts
@@ -24,7 +24,7 @@ import type {
ProjectSummary,
} from "../api/types.js";
import type { UserRow } from "../db/repos/users.js";
-import type { RawTable } from "../services/project-config-service.js";
+import type { RawTable, UtilityCompletion } from "../services/project-config-service.js";
import type { ListEndpointModelsOptions, ModelRef, ProjectConfig } from "@prismshadow/penguin-core";
import type { TieredRates } from "../services/usage-service.js";
import type {
@@ -131,6 +131,7 @@ export abstract class ProjectConfigStore extends Interface<{
getModels(projectId: string): Promise<ModelsResponse>;
updateModels(projectId: string, req: ModelsUpdateRequest): Promise<ModelsResponse>;
setGroupApiKey(projectId: string, provider: string, apiKey: string): Promise<number>;
+ completeOnce(projectId: string, prompt: string): Promise<UtilityCompletion>;
}>() {}
/** ModelOAuth: the mechanism ModelOAuthService implements. */
diff --git a/packages/server/src/mechanisms/sessions.ts b/packages/server/src/mechanisms/sessions.ts
index dbf6f0bd..523dc0ed 100644
--- a/packages/server/src/mechanisms/sessions.ts
+++ b/packages/server/src/mechanisms/sessions.ts
@@ -15,6 +15,7 @@ export abstract class SessionIndex extends Interface<{
insert(row: SessionRow): void;
insertOrIgnore(row: SessionRow): void;
insertFork(sourceSessionId: string, row: SessionRow): SessionRow;
+ markOrgClient(sessionIds: readonly string[]): void;
markHasTrace(sessionId: string): void;
markDriven(sessionId: string, at: string): void;
touchLastActive(sessionId: string, at: string): void;
diff --git a/packages/server/src/mechanisms/settings.ts b/packages/server/src/mechanisms/settings.ts
index c69b6dbc..c5c13ebb 100644
--- a/packages/server/src/mechanisms/settings.ts
+++ b/packages/server/src/mechanisms/settings.ts
@@ -18,6 +18,8 @@ export abstract class Settings extends Interface<{
getAttachmentTotalMb(): number;
setAttachmentTotalMb(value: number): void;
getAttachmentLimitsMb(): { attachmentMaxMb: number; attachmentTotalMb: number };
+ getCompanyMode(): boolean;
+ setCompanyMode(value: boolean): void;
}>() {}
/** UiPrefsStore: the mechanism UiPrefsRepo implements. */
diff --git a/packages/server/src/organization/files.ts b/packages/server/src/organization/files.ts
new file mode 100644
index 00000000..63915f09
--- /dev/null
+++ b/packages/server/src/organization/files.ts
@@ -0,0 +1,1275 @@
+/**
+ * The organization files — parsing, validation and canonical serialization. Pure string
+ * work, no I/O: the store reads and writes, the service decides.
+ *
+ * Intent files (`org_config.toml`, `org_chart.yaml`, calendar events, tickets, the
+ * handbook, `channel.toml`) are edited by people and employees; the API is a validating
+ * writer over the same format, so a hand-edited file and an API-written one parse under one
+ * set of rules. Fact files (`desks.toml`, a ticket's `sessions` and `history` fields,
+ * message lines) are written by the server only. An invalid file is reported, never
+ * repaired in place.
+ */
+import path from "node:path";
+import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
+import {
+ Document as YamlDocument,
+ isMap,
+ isSeq,
+ parse as parseYaml,
+ stringify as stringifyYaml,
+} from "yaml";
+import type {
+ OrgApprovalMode,
+ OrgChannelMessage,
+ OrgChannelNoticeKind,
+ OrgLanguage,
+ OrgStatus,
+ OrgTicketHistoryAction,
+ OrgTicketHistoryEntry,
+ OrgTicketPriority,
+ OrgTicketStatus,
+} from "../api/types.js";
+import { parseScheduleFile } from "../runtime/schedule-file.js";
+import type { ScheduleDefinition } from "../runtime/schedule-file.js";
+import { SEMANTIC_ID_PATTERN } from "../services/ids.js";
+import { DEFAULT_CHANNEL_ID, ceoAgentId, isTicketColumn } from "./paths.js";
+import { parsePrincipal, splitPrincipalList } from "./principal.js";
+import { isValidTimeZone } from "./zoned.js";
+
+export type ParseResult<T> = { ok: true; value: T } | { ok: false; error: string };
+
+const fail = (error: string): { ok: false; error: string } => ({ ok: false, error });
+
+// ---------------------------------------------------------------------------
+// org_config.toml
+// ---------------------------------------------------------------------------
+
+export interface OrgConfig {
+ name: string;
+ mission: string;
+ status: OrgStatus;
+ timezone: string;
+ approvalMode: OrgApprovalMode;
+ mentionChainLimit: number;
+ budgetWarnRatio: number;
+ budgetPauseRatio: number;
+ createdBy: string;
+ /** The shared workspace root when it is not the organization's own `workspace/`: an absolute directory that exists. */
+ workspace?: string;
+ /** The model desks and ticket sessions run on when the employee entry names none; absent = the Project default. */
+ model?: { provider: string; modelId: string };
+ /** The working language everything the organization produces is written in; absent = detected from the mission ({@link orgLanguage}). */
+ language?: OrgLanguage;
+}
+
+/**
+ * The language of a piece of text as the organization uses it: one Han character anywhere
+ * makes it Chinese, everything else is English. Deliberately coarse — a mission is one or
+ * two sentences, and the question it answers is which of the two sets of templates the
+ * company writes in, not what locale it is in.
+ */
+export function detectLanguage(text: string): OrgLanguage {
+ return /\p{Script=Han}/u.test(text) ? "zh" : "en";
+}
+
+/**
+ * The organization's effective working language: the field when it is set, else the
+ * language of the mission. An organization written before the field existed therefore
+ * needs no migration — it reads as whatever its mission is written in.
+ */
+export function orgLanguage(config: OrgConfig): OrgLanguage {
+ return config.language ?? detectLanguage(config.mission);
+}
+
+/**
+ * The bounds `parseOrgConfig` holds the two numeric settings to. Exported because the write
+ * path has to refuse exactly what the loader would: a value past them is written happily and
+ * then fails to parse on the next load, which marks the organization invalid and stops every
+ * automatic trigger until somebody edits the file by hand.
+ */
+export const MENTION_CHAIN_LIMIT_MAX = 100;
+export const BUDGET_RATIO_MAX = 10;
+
+export const ORG_CONFIG_DEFAULTS = {
+ status: "active" as OrgStatus,
+ approvalMode: "allow-all" as OrgApprovalMode,
+ mentionChainLimit: 3,
+ budgetWarnRatio: 0.8,
+ budgetPauseRatio: 1.0,
+};
+
+/**
+ * The CEO's monthly budget in USD when organization creation names none. Budgets are
+ * compared on the cumulative line — the employee plus every subordinate — so the CEO's
+ * budget is the whole company's: a new organization is capped rather than unbounded, and
+ * the number is raised (or cleared) once the board knows what the mission costs.
+ */
+export const DEFAULT_CEO_BUDGET = 100;
+
+function tomlTable(raw: string): ParseResult<Record<string, unknown>> {
+ let parsed: unknown;
+ try {
+ parsed = parseToml(raw);
+ } catch (err) {
+ return fail(`Failed to parse TOML: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ if (parsed === null || typeof parsed !== "object") return fail("Content is not a TOML table");
+ return { ok: true, value: parsed as Record<string, unknown> };
+}
+
+export function parseOrgConfig(raw: string): ParseResult<OrgConfig> {
+ const t = tomlTable(raw);
+ if (!t.ok) return t;
+ const table = t.value;
+ const name = table["name"];
+ if (typeof name !== "string" || name.trim() === "")
+ return fail("name must be a non-empty string");
+ const mission = table["mission"];
+ if (typeof mission !== "string") return fail("mission must be a string");
+ const status = table["status"] ?? ORG_CONFIG_DEFAULTS.status;
+ if (status !== "active" && status !== "paused") return fail("status must be active or paused");
+ const timezone = table["timezone"] ?? "UTC";
+ if (typeof timezone !== "string" || !isValidTimeZone(timezone)) {
+ return fail("timezone must be a valid IANA timezone");
+ }
+ const approvalMode = table["approval_mode"] ?? ORG_CONFIG_DEFAULTS.approvalMode;
+ if (approvalMode !== "allow-all" && approvalMode !== "read-only" && approvalMode !== "deny-all") {
+ return fail("approval_mode must be allow-all, read-only or deny-all");
+ }
+ const limit = table["mention_chain_limit"] ?? ORG_CONFIG_DEFAULTS.mentionChainLimit;
+ if (
+ typeof limit !== "number" ||
+ !Number.isInteger(limit) ||
+ limit < 0 ||
+ limit > MENTION_CHAIN_LIMIT_MAX
+ ) {
+ return fail(`mention_chain_limit must be an integer between 0 and ${MENTION_CHAIN_LIMIT_MAX}`);
+ }
+ const warn = table["budget_warn_ratio"] ?? ORG_CONFIG_DEFAULTS.budgetWarnRatio;
+ const pause = table["budget_pause_ratio"] ?? ORG_CONFIG_DEFAULTS.budgetPauseRatio;
+ for (const [key, v] of [
+ ["budget_warn_ratio", warn],
+ ["budget_pause_ratio", pause],
+ ] as const) {
+ if (typeof v !== "number" || !(v > 0) || v > BUDGET_RATIO_MAX)
+ return fail(`${key} must be a number in (0, ${BUDGET_RATIO_MAX}]`);
+ }
+ const createdBy = table["created_by"];
+ if (typeof createdBy !== "string" || createdBy === "")
+ return fail("created_by must be a non-empty string");
+ const workspace = table["workspace"];
+ if (workspace !== undefined && (typeof workspace !== "string" || !path.isAbsolute(workspace))) {
+ return fail("workspace must be an absolute path");
+ }
+ const language = table["language"];
+ if (language !== undefined && language !== "zh" && language !== "en") {
+ return fail("language must be zh or en");
+ }
+ let model: { provider: string; modelId: string } | undefined;
+ if (table["model"] !== undefined) {
+ const m = table["model"];
+ if (m === null || typeof m !== "object") return fail("model must be a table");
+ const provider = (m as Record<string, unknown>)["provider"];
+ const modelId = (m as Record<string, unknown>)["model_id"];
+ if (
+ typeof provider !== "string" ||
+ provider === "" ||
+ typeof modelId !== "string" ||
+ modelId === ""
+ ) {
+ return fail("model needs both provider and model_id");
+ }
+ model = { provider, modelId };
+ }
+ return {
+ ok: true,
+ value: {
+ name: name.trim(),
+ mission: mission.trim(),
+ status,
+ timezone,
+ approvalMode,
+ mentionChainLimit: limit,
+ budgetWarnRatio: warn as number,
+ budgetPauseRatio: pause as number,
+ createdBy,
+ ...(typeof workspace === "string" ? { workspace } : {}),
+ ...(model !== undefined ? { model } : {}),
+ ...(language !== undefined ? { language } : {}),
+ },
+ };
+}
+
+export function serializeOrgConfig(cfg: OrgConfig): string {
+ const table = {
+ name: cfg.name,
+ mission: cfg.mission,
+ status: cfg.status,
+ timezone: cfg.timezone,
+ approval_mode: cfg.approvalMode,
+ mention_chain_limit: cfg.mentionChainLimit,
+ budget_warn_ratio: cfg.budgetWarnRatio,
+ budget_pause_ratio: cfg.budgetPauseRatio,
+ created_by: cfg.createdBy,
+ ...(cfg.language !== undefined ? { language: cfg.language } : {}),
+ ...(cfg.workspace !== undefined ? { workspace: cfg.workspace } : {}),
+ ...(cfg.model !== undefined
+ ? { model: { provider: cfg.model.provider, model_id: cfg.model.modelId } }
+ : {}),
+ };
+ return [
+ "# org_config.toml — organization settings (the id is the directory name and never changes).",
+ "# status: active | paused (paused stops every automatic trigger; people can still talk to any desk).",
+ "# approval_mode: allow-all | read-only | deny-all for desk and ticket sessions.",
+ "# language: zh | en — the working language of everything the organization writes (optional; detected from the mission when absent).",
+ "# workspace: an absolute directory used as the shared workspace instead of ./workspace (optional).",
+ "# [model]: provider + model_id for desks and ticket sessions when the employee names none (optional).",
+ stringifyToml(table),
+ "",
+ ].join("\n");
+}
+
+// ---------------------------------------------------------------------------
+// org_chart.yaml
+// ---------------------------------------------------------------------------
+
+export interface OrgEmployee {
+ agentId: string;
+ title: string;
+ /** null for the CEO, the root. */
+ reportsTo: string | null;
+ duties?: string;
+ /** A sub-directory of the shared workspace (`.` = all of it) or an absolute path. */
+ workspace: string;
+ budget?: number;
+ model?: { provider: string; modelId: string };
+}
+
+export interface OrgChart {
+ employees: OrgEmployee[];
+}
+
+function employeeFrom(item: unknown, index: number): ParseResult<OrgEmployee> {
+ if (item === null || typeof item !== "object")
+ return fail(`employees[${index}] is not a mapping`);
+ const e = item as Record<string, unknown>;
+ const agentId = e["agent_id"];
+ if (typeof agentId !== "string" || !SEMANTIC_ID_PATTERN.test(agentId)) {
+ return fail(`employees[${index}].agent_id is missing or not a valid Agent id`);
+ }
+ const title = e["title"];
+ if (typeof title !== "string" || title.trim() === "") {
+ return fail(`${agentId}: title must be a non-empty string`);
+ }
+ const reportsTo = e["reports_to"] ?? null;
+ if (reportsTo !== null && (typeof reportsTo !== "string" || reportsTo === "")) {
+ return fail(`${agentId}: reports_to must be an Agent id or null`);
+ }
+ const duties = e["duties"];
+ if (duties !== undefined && typeof duties !== "string")
+ return fail(`${agentId}: duties must be a string`);
+ const workspace = e["workspace"] ?? ".";
+ if (typeof workspace !== "string" || workspace.trim() === "") {
+ return fail(`${agentId}: workspace must be a non-empty string`);
+ }
+ const budget = e["budget"];
+ if (budget !== undefined && budget !== null && (typeof budget !== "number" || !(budget >= 0))) {
+ return fail(`${agentId}: budget must be a number >= 0`);
+ }
+ let model: { provider: string; modelId: string } | undefined;
+ if (e["model"] !== undefined && e["model"] !== null) {
+ const m = e["model"];
+ if (m === null || typeof m !== "object") return fail(`${agentId}: model must be a mapping`);
+ const provider = (m as Record<string, unknown>)["provider"];
+ const modelId = (m as Record<string, unknown>)["model_id"];
+ if (
+ typeof provider !== "string" ||
+ provider === "" ||
+ typeof modelId !== "string" ||
+ modelId === ""
+ ) {
+ return fail(`${agentId}: model needs both provider and model_id`);
+ }
+ model = { provider, modelId };
+ }
+ return {
+ ok: true,
+ value: {
+ agentId,
+ title: title.trim(),
+ reportsTo: reportsTo as string | null,
+ ...(typeof duties === "string" && duties.trim() !== "" ? { duties: duties.trim() } : {}),
+ workspace: workspace.trim(),
+ ...(typeof budget === "number" ? { budget } : {}),
+ ...(model !== undefined ? { model } : {}),
+ },
+ };
+}
+
+/**
+ * Parse and validate the employee tree: unique valid ids, exactly one root and it is the
+ * CEO (`<orgId>_ceo`), every `reports_to` names another employee, and no cycles — every
+ * employee walks up to the root.
+ */
+export function parseOrgChart(raw: string, orgId: string): ParseResult<OrgChart> {
+ let parsed: unknown;
+ try {
+ parsed = parseYaml(raw);
+ } catch (err) {
+ return fail(`Failed to parse YAML: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ if (parsed === null || typeof parsed !== "object") return fail("Content is not a YAML mapping");
+ const list = (parsed as Record<string, unknown>)["employees"];
+ if (!Array.isArray(list)) return fail("employees must be a list");
+ const employees: OrgEmployee[] = [];
+ const seen = new Set<string>();
+ for (const [i, item] of list.entries()) {
+ const r = employeeFrom(item, i);
+ if (!r.ok) return r;
+ if (seen.has(r.value.agentId)) return fail(`duplicate employee: ${r.value.agentId}`);
+ seen.add(r.value.agentId);
+ employees.push(r.value);
+ }
+ const roots = employees.filter((e) => e.reportsTo === null);
+ if (roots.length !== 1) return fail("exactly one employee must have reports_to: null (the CEO)");
+ if (roots[0]!.agentId !== ceoAgentId(orgId)) {
+ return fail(`the root employee must be the CEO ${ceoAgentId(orgId)}`);
+ }
+ for (const e of employees) {
+ if (e.reportsTo === null) continue;
+ if (e.reportsTo === e.agentId) return fail(`${e.agentId} reports to itself`);
+ if (!seen.has(e.reportsTo))
+ return fail(`${e.agentId} reports to unknown employee ${e.reportsTo}`);
+ }
+ const byId = new Map(employees.map((e) => [e.agentId, e]));
+ for (const e of employees) {
+ let cur: OrgEmployee | undefined = e;
+ for (let steps = 0; cur && cur.reportsTo !== null; steps++) {
+ if (steps > employees.length) return fail(`reporting line of ${e.agentId} forms a cycle`);
+ cur = byId.get(cur.reportsTo);
+ }
+ }
+ return { ok: true, value: { employees } };
+}
+
+export function serializeOrgChart(chart: OrgChart): string {
+ const doc = {
+ employees: chart.employees.map((e) => ({
+ agent_id: e.agentId,
+ title: e.title,
+ reports_to: e.reportsTo,
+ ...(e.duties !== undefined ? { duties: e.duties } : {}),
+ workspace: e.workspace,
+ ...(e.budget !== undefined ? { budget: e.budget } : {}),
+ ...(e.model !== undefined
+ ? { model: { provider: e.model.provider, model_id: e.model.modelId } }
+ : {}),
+ })),
+ };
+ return [
+ "# org_chart.yaml — the employee tree: one employee is one Agent (no Agent, no position),",
+ "# joined by reports_to into a tree rooted at the CEO. Budgets are monthly USD caps for an",
+ "# employee plus every subordinate; workspace is a sub-directory of the shared workspace",
+ "# (. = all of it) or an absolute path that already exists.",
+ stringifyYaml(doc, { lineWidth: 0 }).trimEnd(),
+ "",
+ ].join("\n");
+}
+
+/** Every employee below `agentId` (children, grandchildren, …), in tree order. */
+export function subordinatesOf(chart: OrgChart, agentId: string): string[] {
+ const out: string[] = [];
+ const walk = (id: string): void => {
+ for (const e of chart.employees) {
+ if (e.reportsTo === id) {
+ out.push(e.agentId);
+ walk(e.agentId);
+ }
+ }
+ };
+ walk(agentId);
+ return out;
+}
+
+/** The reporting line above `agentId`, nearest first, ending at the root. */
+export function ancestorsOf(chart: OrgChart, agentId: string): string[] {
+ const byId = new Map(chart.employees.map((e) => [e.agentId, e]));
+ const out: string[] = [];
+ let cur = byId.get(agentId);
+ while (cur && cur.reportsTo !== null && out.length <= chart.employees.length) {
+ out.push(cur.reportsTo);
+ cur = byId.get(cur.reportsTo);
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// desks.toml (fact file)
+// ---------------------------------------------------------------------------
+
+export interface DeskEntry {
+ sessionId: string;
+ /** The resolved absolute workspace the session was opened in (immutable per session). */
+ workspace: string;
+ openedAt: string;
+ /** Earlier desk sessions of this employee (renewals), oldest first: they still count toward the employee's cost. */
+ previous: string[];
+}
+
+export type Desks = Record<string, DeskEntry>;
+
+export function parseDesks(raw: string): ParseResult<Desks> {
+ const t = tomlTable(raw);
+ if (!t.ok) return t;
+ const desks: Desks = {};
+ for (const [agentId, value] of Object.entries(t.value)) {
+ if (value === null || typeof value !== "object") return fail(`${agentId} is not a table`);
+ const d = value as Record<string, unknown>;
+ if (typeof d["session_id"] !== "string" || typeof d["workspace"] !== "string") {
+ return fail(`${agentId}: session_id and workspace are required`);
+ }
+ const openedAt = d["opened_at"];
+ const previous = d["previous"];
+ if (
+ previous !== undefined &&
+ (!Array.isArray(previous) || previous.some((p) => typeof p !== "string"))
+ ) {
+ return fail(`${agentId}: previous must be a list of session ids`);
+ }
+ desks[agentId] = {
+ sessionId: d["session_id"],
+ workspace: d["workspace"],
+ openedAt:
+ openedAt instanceof Date
+ ? openedAt.toISOString()
+ : typeof openedAt === "string"
+ ? openedAt
+ : "",
+ previous: (previous as string[] | undefined) ?? [],
+ };
+ }
+ return { ok: true, value: desks };
+}
+
+export function serializeDesks(desks: Desks): string {
+ const table: Record<string, unknown> = {};
+ for (const [agentId, d] of Object.entries(desks)) {
+ table[agentId] = {
+ session_id: d.sessionId,
+ workspace: d.workspace,
+ opened_at: d.openedAt,
+ ...(d.previous.length > 0 ? { previous: d.previous } : {}),
+ };
+ }
+ return [
+ "# desks.toml — desk ledger (a fact file the server writes): employee -> current desk session.",
+ stringifyToml(table),
+ "",
+ ].join("\n");
+}
+
+// ---------------------------------------------------------------------------
+// calendar/<agent_id>/<name>.toml
+// ---------------------------------------------------------------------------
+
+export interface CalendarEvent extends ScheduleDefinition {
+ title?: string;
+}
+
+const CALENDAR_TARGET_KEYS = ["session_id", "workspace", "model_id", "provider"] as const;
+
+/** A schedule file without target fields: the target is always the employee's desk session. */
+export function parseCalendarEvent(name: string, raw: string): ParseResult<CalendarEvent> {
+ const t = tomlTable(raw);
+ if (!t.ok) return t;
+ for (const key of CALENDAR_TARGET_KEYS) {
+ if (t.value[key] !== undefined) {
+ return fail(
+ `${key} is not allowed: a calendar event always goes to the employee's desk session`,
+ );
+ }
+ }
+ const title = t.value["title"];
+ if (title !== undefined && typeof title !== "string") return fail("title must be a string");
+ const parsed = parseScheduleFile(name, raw);
+ if (!parsed.ok) return fail(parsed.error);
+ return {
+ ok: true,
+ value: {
+ ...parsed.def,
+ ...(typeof title === "string" && title.trim() !== "" ? { title: title.trim() } : {}),
+ },
+ };
+}
+
+export function serializeCalendarEvent(fields: {
+ title?: string;
+ prompt: string;
+ enabled: boolean;
+ startAt: string;
+ period?: string;
+ endAt?: string;
+}): string {
+ const table: Record<string, unknown> = {
+ ...(fields.title !== undefined ? { title: fields.title } : {}),
+ prompt: fields.prompt,
+ enabled: fields.enabled,
+ start_at: fields.startAt,
+ ...(fields.period !== undefined ? { period: fields.period } : {}),
+ ...(fields.endAt !== undefined ? { end_at: fields.endAt } : {}),
+ };
+ return `${stringifyToml(table)}\n`;
+}
+
+// ---------------------------------------------------------------------------
+// tickets/<yyyy-mm>/<column>/<yyyy-mm-dd>-<slug>.md
+// ---------------------------------------------------------------------------
+
+/** `<yyyy-mm-dd>-<slug>`; the slug is hyphen-joined lowercase English words, never a digit. */
+export const TICKET_ID_PATTERN = /^\d{4}-\d{2}-\d{2}-[a-z]+(?:-[a-z]+)*$/;
+
+/** At most this many words in a derived slug, and at most this many characters in each. */
+const SLUG_MAX_WORDS = 6;
+const SLUG_MAX_WORD_LENGTH = 20;
+
+/**
+ * The slug of a ticket id, derived from a title or from a model's proposal: ASCII letters
+ * only, lowercased, hyphen-joined. Digits are dropped — the id already starts with the date,
+ * and `-2` on the end of a slug reads as a version rather than as a name. Text that carries
+ * no Latin letters at all (a Chinese title) yields `""`, and one that yields a single word
+ * says as little as none: both are the case the caller asks the model to name.
+ */
+export function slugify(text: string): string {
+ return text
+ .normalize("NFKD")
+ .replace(/[̀-ͯ]/g, "")
+ .toLowerCase()
+ .replace(/[^a-z]+/g, " ")
+ .trim()
+ .split(/\s+/)
+ .filter((w) => w !== "")
+ .slice(0, SLUG_MAX_WORDS)
+ .map((w) => w.slice(0, SLUG_MAX_WORD_LENGTH))
+ .join("-");
+}
+
+const ALPHABET = "abcdefghijklmnopqrstuvwxyz";
+
+/**
+ * The letters that make a taken id unique: `2` → `b`, `3` → `c`, … `26` → `z`, `27` → `aa`.
+ * Letters rather than numbers because the slug pattern has no digits in it, and starting at
+ * `b` because the first candidate is the bare slug.
+ */
+export function slugSuffix(n: number): string {
+ let out = "";
+ for (let v = n; v > 0; v = Math.floor((v - 1) / ALPHABET.length)) {
+ out = `${ALPHABET[(v - 1) % ALPHABET.length]}${out}`;
+ }
+ return out;
+}
+
+export interface TicketDoc {
+ title: string;
+ status: OrgTicketStatus;
+ /** The ONE responsible principal (`agent:<id>` / `user:<id>`); every ticket has one. */
+ owner: string;
+ parent?: string;
+ notify: string[];
+ priority: OrgTicketPriority;
+ due?: string;
+ blocked?: string;
+ blockedBy?: string;
+ /** Contributing session ids, in the order they were attached (fact, server-written). */
+ sessions: string[];
+ /** The operation log, oldest first (fact, server-written). */
+ history: OrgTicketHistoryEntry[];
+ goal: string;
+ acceptanceCriteria: string;
+ /** Plain progress sentences, without their bullet; who wrote one and when is in the history. */
+ progress: string[];
+ result: string;
+ /** Frontmatter keys this parser does not know, kept verbatim across a round trip. */
+ extra: Record<string, unknown>;
+ /** Sections beyond the four fixed ones, kept verbatim. */
+ extraSections: Array<{ heading: string; body: string }>;
+}
+
+const SECTION_KEYS: Record<string, "goal" | "acceptanceCriteria" | "progress" | "result"> = {
+ goal: "goal",
+ "acceptance criteria": "acceptanceCriteria",
+ progress: "progress",
+ result: "result",
+};
+
+const KNOWN_FIELDS = new Set([
+ "title",
+ "status",
+ "owner",
+ "parent",
+ "notify",
+ "priority",
+ "due",
+ "blocked",
+ "blocked_by",
+ "sessions",
+ "history",
+]);
+
+const HISTORY_ACTIONS: readonly OrgTicketHistoryAction[] = [
+ "created",
+ "assigned",
+ "moved",
+ "blocked",
+ "unblocked",
+ "progress",
+ "session_started",
+ "session_attached",
+ "edited",
+];
+
+/** How much of a progress sentence the history entry that records it carries. */
+export const HISTORY_NOTE_MAX = 80;
+
+function isPersonPrincipal(raw: string): boolean {
+ const p = parsePrincipal(raw);
+ return p !== null && (p.kind === "agent" || p.kind === "user");
+}
+
+type Frontmatter =
+ { kind: "none" } | { kind: "unterminated" } | { kind: "ok"; yaml: string; body: string };
+
+/** The `---` fenced block at the top of the file, and everything after it. */
+function splitFrontmatter(text: string): Frontmatter {
+ const lines = text.split("\n");
+ let i = 0;
+ while (i < lines.length && lines[i]!.trim() === "") i++;
+ if (lines[i]?.trim() !== "---") return { kind: "none" };
+ const start = i + 1;
+ for (let j = start; j < lines.length; j++) {
+ if (lines[j]!.trim() === "---") {
+ return {
+ kind: "ok",
+ yaml: lines.slice(start, j).join("\n"),
+ body: lines.slice(j + 1).join("\n"),
+ };
+ }
+ }
+ return { kind: "unterminated" };
+}
+
+/**
+ * A ticket file: YAML frontmatter followed by the prose sections. The frontmatter carries
+ * the fields (the title among them — there is no H1), the prose carries `## Goal`,
+ * `## Acceptance criteria`, `## Progress` and `## Result`; unknown fields and unknown
+ * sections survive a round trip. A file in the format that predates the frontmatter is read
+ * by {@link parseLegacyTicket} and converted the next time it is written.
+ */
+export function parseTicket(raw: string): ParseResult<TicketDoc> {
+ const text = raw.replace(/\r\n/g, "\n");
+ const fm = splitFrontmatter(text);
+ if (fm.kind === "none") return parseLegacyTicket(text);
+ if (fm.kind === "unterminated") return fail("the frontmatter block is not closed by `---`");
+ let parsed: unknown;
+ try {
+ parsed = parseYaml(fm.yaml);
+ } catch (err) {
+ return fail(
+ `Failed to parse the frontmatter: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
+ return fail("the frontmatter is not a YAML mapping");
+ }
+ const front = parsed as Record<string, unknown>;
+ const fields = ticketFields(front);
+ if (!fields.ok) return fields;
+ const sections = ticketSections(fm.body);
+ if (!sections.ok) return sections;
+ return { ok: true, value: { ...fields.value, ...sections.value } };
+}
+
+type TicketFields = Omit<
+ TicketDoc,
+ "goal" | "acceptanceCriteria" | "progress" | "result" | "extraSections"
+>;
+
+/** The frontmatter's fields, validated; anything this parser does not know lands in `extra`. */
+function ticketFields(front: Record<string, unknown>): ParseResult<TicketFields> {
+ const str = (key: string): string => {
+ const v = front[key];
+ return typeof v === "string" ? v.trim() : "";
+ };
+ const title = str("title");
+ if (title === "") return fail("title must be a non-empty string");
+ const status = str("status");
+ if (!isTicketColumn(status)) {
+ return fail(`status must be one of the board columns, got \`${status}\``);
+ }
+ const owner = str("owner");
+ if (!isPersonPrincipal(owner)) return fail("owner must be agent:<id> or user:<id>");
+ const parent = str("parent");
+ if (parent !== "" && !TICKET_ID_PATTERN.test(parent)) return fail("parent must be a ticket id");
+ const notifyList = front["notify"];
+ if (notifyList !== undefined && notifyList !== null && !Array.isArray(notifyList)) {
+ return fail("notify must be a list of principals");
+ }
+ // No `notify`, or an empty one: tell the owner when it is an employee — its next sweep
+ // lists the change — and nobody when a person owns it, because one @-mention per closed
+ // ticket is a badge nobody asked for. A person lists itself to be told.
+ const notify =
+ Array.isArray(notifyList) && notifyList.length > 0
+ ? notifyList.map((n) => String(n).trim())
+ : defaultTicketNotify(owner);
+ for (const n of notify)
+ if (!isPersonPrincipal(n)) return fail(`notify entry is not a principal: ${n}`);
+ const priority = str("priority") === "" ? "P2" : str("priority");
+ if (priority !== "P0" && priority !== "P1" && priority !== "P2") {
+ return fail("priority must be P0, P1 or P2");
+ }
+ const due = str("due");
+ if (due !== "" && !/^\d{4}-\d{2}-\d{2}/.test(due)) return fail("due must start with yyyy-mm-dd");
+ const blocked = str("blocked");
+ const blockedBy = str("blocked_by");
+ if (blockedBy !== "" && !TICKET_ID_PATTERN.test(blockedBy) && !isPersonPrincipal(blockedBy)) {
+ return fail("blocked_by must be a ticket id or a principal");
+ }
+ const sessionList = front["sessions"];
+ if (sessionList !== undefined && sessionList !== null && !Array.isArray(sessionList)) {
+ return fail("sessions must be a list of session ids");
+ }
+ const sessions = Array.isArray(sessionList) ? sessionList.map((s) => String(s).trim()) : [];
+ const history = parseTicketHistory(front["history"]);
+ if (!history.ok) return history;
+ const extra: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(front)) if (!KNOWN_FIELDS.has(key)) extra[key] = value;
+ return {
+ ok: true,
+ value: {
+ title,
+ status,
+ owner,
+ ...(parent !== "" ? { parent } : {}),
+ notify,
+ priority,
+ ...(due !== "" ? { due } : {}),
+ ...(blocked !== "" ? { blocked } : {}),
+ ...(blockedBy !== "" ? { blockedBy } : {}),
+ sessions,
+ history: history.value,
+ extra,
+ },
+ };
+}
+
+/** The `Notify` list a ticket falls back to: its owner when an employee owns it, nobody otherwise. */
+export function defaultTicketNotify(owner: string): string[] {
+ return parsePrincipal(owner)?.kind === "agent" ? [owner] : [];
+}
+
+function parseTicketHistory(value: unknown): ParseResult<OrgTicketHistoryEntry[]> {
+ if (value === undefined || value === null) return { ok: true, value: [] };
+ if (!Array.isArray(value)) return fail("history must be a list of entries");
+ const out: OrgTicketHistoryEntry[] = [];
+ for (const [i, item] of value.entries()) {
+ if (item === null || typeof item !== "object" || Array.isArray(item)) {
+ return fail(`history[${i}] is not a mapping`);
+ }
+ const e = item as Record<string, unknown>;
+ const at = typeof e["at"] === "string" ? e["at"].trim() : "";
+ const by = typeof e["by"] === "string" ? e["by"].trim() : "";
+ const action = typeof e["action"] === "string" ? e["action"].trim() : "";
+ if (!(HISTORY_ACTIONS as readonly string[]).includes(action)) {
+ return fail(`history[${i}].action is not a known action: ${action}`);
+ }
+ const note = typeof e["note"] === "string" ? e["note"] : undefined;
+ out.push({
+ at,
+ by,
+ action: action as OrgTicketHistoryAction,
+ ...(note !== undefined && note !== "" ? { note } : {}),
+ });
+ }
+ return { ok: true, value: out };
+}
+
+type TicketProse = Pick<
+ TicketDoc,
+ "goal" | "acceptanceCriteria" | "progress" | "result" | "extraSections"
+>;
+
+/** The prose half: the four fixed sections, plus any others kept as written. */
+function ticketSections(body: string): ParseResult<TicketProse> {
+ const out: TicketProse = {
+ goal: "",
+ acceptanceCriteria: "",
+ progress: [],
+ result: "",
+ extraSections: [],
+ };
+ const sections: Array<{ heading: string; body: string[] }> = [];
+ let current: { heading: string; body: string[] } | null = null;
+ for (const line of body.split("\n")) {
+ const h = /^## (.+)$/.exec(line);
+ if (h) {
+ current = { heading: h[1]!.trim(), body: [] };
+ sections.push(current);
+ } else if (current) {
+ current.body.push(line);
+ } else if (line.trim() !== "") {
+ return fail(`text before the first section heading: ${line}`);
+ }
+ }
+ for (const s of sections) {
+ const key = SECTION_KEYS[s.heading.toLowerCase()];
+ const text = trimBlank(s.body).join("\n");
+ if (key === "progress") {
+ out.progress = trimBlank(s.body)
+ .filter((l) => l.trim() !== "")
+ .map((l) => l.trim().replace(/^[-*]\s+/, ""));
+ } else if (key !== undefined) {
+ out[key] = text;
+ } else {
+ out.extraSections.push({ heading: s.heading, body: text });
+ }
+ }
+ return { ok: true, value: out };
+}
+
+function trimBlank(lines: string[]): string[] {
+ let a = 0;
+ let b = lines.length;
+ while (a < b && lines[a]!.trim() === "") a++;
+ while (b > a && lines[b - 1]!.trim() === "") b--;
+ return lines.slice(a, b);
+}
+
+export function serializeTicket(doc: TicketDoc): string {
+ const front: Record<string, unknown> = {
+ title: doc.title,
+ status: doc.status,
+ owner: doc.owner,
+ ...(doc.parent !== undefined ? { parent: doc.parent } : {}),
+ notify: doc.notify,
+ priority: doc.priority,
+ ...(doc.due !== undefined ? { due: doc.due } : {}),
+ ...(doc.blocked !== undefined && doc.blocked !== "" ? { blocked: doc.blocked } : {}),
+ ...(doc.blockedBy !== undefined && doc.blockedBy !== "" ? { blocked_by: doc.blockedBy } : {}),
+ sessions: doc.sessions,
+ history: doc.history.map((h) => ({
+ at: h.at,
+ by: h.by,
+ action: h.action,
+ ...(h.note !== undefined && h.note !== "" ? { note: h.note } : {}),
+ })),
+ ...doc.extra,
+ };
+ const yamlDoc = new YamlDocument(front);
+ // One line per list and per history entry: a ticket file is read and hand-edited, and a
+ // twenty-line `sessions` block would bury the fields above it.
+ for (const key of ["notify", "sessions"]) {
+ const node = yamlDoc.get(key, true);
+ if (isSeq(node)) node.flow = true;
+ }
+ const history = yamlDoc.get("history", true);
+ if (isSeq(history)) for (const item of history.items) if (isMap(item)) item.flow = true;
+ const sections: string[] = [
+ `## Goal\n${doc.goal}`,
+ `## Acceptance criteria\n${doc.acceptanceCriteria}`,
+ `## Progress\n${doc.progress.map((p) => `- ${p}`).join("\n")}`,
+ `## Result\n${doc.result}`,
+ ...doc.extraSections.map((s) => `## ${s.heading}\n${s.body}`),
+ ];
+ const yaml = yamlDoc.toString({ lineWidth: 0, flowCollectionPadding: false });
+ return `---\n${yaml}---\n\n${sections.map((s) => s.trimEnd()).join("\n\n")}\n`;
+}
+
+/** One progress sentence as the history records it: the first {@link HISTORY_NOTE_MAX} characters, on one line. */
+export function historyNote(text: string): string {
+ return text
+ .replace(/\s*\n\s*/g, " ")
+ .trim()
+ .slice(0, HISTORY_NOTE_MAX);
+}
+
+// ---------------------------------------------------------------------------
+// Legacy ticket files
+// ---------------------------------------------------------------------------
+
+const LEGACY_HEADERS = new Set([
+ "status",
+ "initiator",
+ "owner",
+ "parent",
+ "notify",
+ "priority",
+ "due",
+ "blocked",
+ "blocked-by",
+ "sessions",
+]);
+
+/** A legacy progress line: `- <time> <principal> <text> [session:<id>]`. */
+function parseLegacyProgressLine(line: string): { time: string; by: string; text: string } | null {
+ const m = /^-\s+(\S+)\s+(\S+)\s+(.*)$/.exec(line.trim());
+ if (!m) return null;
+ let text = m[3]!.trim();
+ const s = /\s*session:(\S+)$/.exec(text);
+ if (s) text = text.slice(0, s.index).trim();
+ if (!isPersonPrincipal(m[2]!)) return null;
+ return { time: m[1]!, by: m[2]!, text };
+}
+
+/**
+ * A ticket written before the frontmatter format: `# Ticket: <title>` followed by
+ * `Key: value` header lines. `Initiator` becomes the `created` history entry and, when no
+ * `Owner` was set, the owner; each old progress line becomes a plain progress sentence plus
+ * one `progress` history entry carrying its time and principal. Nothing is repaired on disk
+ * here — the file converts to the new format the first time it is written.
+ *
+ * **Compatibility shim.** It can be deleted one release after the frontmatter format ships,
+ * by which time every ticket an organization still writes to has been converted; see
+ * `changelog/unreleased/2026-09-09-backward-compatibility.md`.
+ */
+export function parseLegacyTicket(text: string): ParseResult<TicketDoc> {
+ const lines = text.split("\n");
+ let i = 0;
+ while (i < lines.length && lines[i]!.trim() === "") i++;
+ const titleLine = /^# Ticket: (.+)$/.exec(lines[i] ?? "");
+ if (!titleLine)
+ return fail("the file must start with `---` (frontmatter) or `# Ticket: <title>`");
+ const title = titleLine[1]!.trim();
+ i++;
+ while (i < lines.length && lines[i]!.trim() === "") i++;
+ const headers = new Map<string, string>();
+ const extra: Record<string, unknown> = {};
+ for (; i < lines.length; i++) {
+ const line = lines[i]!;
+ if (line.trim() === "" || line.startsWith("## ")) break;
+ const kv = /^([A-Za-z][A-Za-z-]*):\s?(.*)$/.exec(line);
+ if (!kv) return fail(`header line is not \`Key: value\`: ${line}`);
+ const key = kv[1]!.toLowerCase();
+ if (LEGACY_HEADERS.has(key)) headers.set(key, kv[2]!.trim());
+ else extra[kv[1]!] = kv[2]!.trim();
+ }
+ const status = headers.get("status") ?? "";
+ if (!isTicketColumn(status))
+ return fail(`Status must be one of the board columns, got \`${status}\``);
+ const initiator = headers.get("initiator") ?? "";
+ if (!isPersonPrincipal(initiator)) return fail("Initiator must be agent:<id> or user:<id>");
+ // One owner now: an unassigned legacy ticket is owned by whoever filed it.
+ const ownerHeader = headers.get("owner") ?? "";
+ if (ownerHeader !== "" && !isPersonPrincipal(ownerHeader)) {
+ return fail("Owner must be agent:<id> or user:<id>");
+ }
+ const owner = ownerHeader !== "" ? ownerHeader : initiator;
+ const parent = headers.get("parent") ?? "";
+ if (parent !== "" && !TICKET_ID_PATTERN.test(parent) && !LEGACY_TICKET_ID_PATTERN.test(parent)) {
+ return fail("Parent must be a ticket id");
+ }
+ const notifyRaw = headers.get("notify");
+ const notify =
+ notifyRaw === undefined || notifyRaw === ""
+ ? defaultTicketNotify(owner)
+ : splitPrincipalList(notifyRaw);
+ for (const n of notify)
+ if (!isPersonPrincipal(n)) return fail(`Notify entry is not a principal: ${n}`);
+ const priority = headers.get("priority") ?? "P2";
+ if (priority !== "P0" && priority !== "P1" && priority !== "P2") {
+ return fail("Priority must be P0, P1 or P2");
+ }
+ const due = headers.get("due") ?? "";
+ if (due !== "" && !/^\d{4}-\d{2}-\d{2}/.test(due)) return fail("Due must start with yyyy-mm-dd");
+ const blocked = headers.get("blocked") ?? "";
+ const blockedBy = headers.get("blocked-by") ?? "";
+ if (
+ blockedBy !== "" &&
+ !TICKET_ID_PATTERN.test(blockedBy) &&
+ !LEGACY_TICKET_ID_PATTERN.test(blockedBy) &&
+ !isPersonPrincipal(blockedBy)
+ ) {
+ return fail("Blocked-by must be a ticket id or a principal");
+ }
+ const sessions = splitPrincipalList(headers.get("sessions") ?? "");
+ const prose = ticketSections(lines.slice(i).join("\n"));
+ if (!prose.ok) return prose;
+ // The old progress log carried the operator and the time inline; they move to the history,
+ // the sentence stays. A line nothing can be read out of is kept as a sentence and nothing else.
+ const history: OrgTicketHistoryEntry[] = [];
+ const progress: string[] = [];
+ for (const line of prose.value.progress) {
+ const entry = parseLegacyProgressLine(`- ${line}`);
+ if (entry === null) {
+ progress.push(line);
+ continue;
+ }
+ progress.push(entry.text);
+ history.push({
+ at: entry.time,
+ by: entry.by,
+ action: "progress",
+ note: historyNote(entry.text),
+ });
+ }
+ // Filing is what the `Initiator` header recorded; its time is the first thing that happened.
+ history.unshift({ at: history[0]?.at ?? "", by: initiator, action: "created" });
+ return {
+ ok: true,
+ value: {
+ title,
+ status,
+ owner,
+ ...(parent !== "" ? { parent } : {}),
+ notify,
+ priority,
+ ...(due !== "" ? { due } : {}),
+ ...(blocked !== "" ? { blocked } : {}),
+ ...(blockedBy !== "" ? { blockedBy } : {}),
+ sessions,
+ history,
+ ...prose.value,
+ progress,
+ extra,
+ },
+ };
+}
+
+/** Ticket ids written before the letters-only slug rule, as legacy files still reference them. */
+const LEGACY_TICKET_ID_PATTERN = /^\d{4}-\d{2}-\d{2}-[a-z0-9][a-z0-9-]{0,63}$/;
+
+// ---------------------------------------------------------------------------
+// channels/<channel_id>/channel.toml
+// ---------------------------------------------------------------------------
+
+/**
+ * A channel's intent file. `everyone` and `members` are the two shapes of membership
+ * and exactly one of them applies: the all-hands channel is `everyone = true` (every
+ * employee and every Project member, no list to keep), every other channel carries the
+ * explicit list its members edit through the API.
+ */
+export interface ChannelConfig {
+ name: string;
+ purpose: string;
+ /** `user:<id>` / `agent:<id>` / `system` (the all-hands channel, created with the organization). */
+ createdBy: string;
+ /** ISO 8601 UTC. */
+ createdAt: string;
+ /** An archived channel is read-only: no posts, no invitations, no membership changes. */
+ archived: boolean;
+ /** Explicit membership; absent on the all-hands channel. */
+ members?: string[];
+ /** True only on the all-hands channel: membership is implicit and there is no list. */
+ everyone?: boolean;
+}
+
+/**
+ * Parses a channel file. The channel id decides which membership shape is legal, so it is
+ * an argument rather than a field: `everyone` belongs to the all-hands channel and to no
+ * other, and every other channel must list its members.
+ */
+export function parseChannelConfig(channelId: string, raw: string): ParseResult<ChannelConfig> {
+ const t = tomlTable(raw);
+ if (!t.ok) return t;
+ const table = t.value;
+ const name = table["name"];
+ if (typeof name !== "string" || name.trim() === "")
+ return fail("name must be a non-empty string");
+ const purpose = table["purpose"] ?? "";
+ if (typeof purpose !== "string") return fail("purpose must be a string");
+ const createdBy = table["created_by"];
+ if (typeof createdBy !== "string" || (createdBy !== "system" && !isPersonPrincipal(createdBy))) {
+ return fail("created_by must be agent:<id>, user:<id> or system");
+ }
+ const createdAtRaw = table["created_at"];
+ const createdAt =
+ createdAtRaw instanceof Date
+ ? createdAtRaw.toISOString()
+ : typeof createdAtRaw === "string"
+ ? createdAtRaw
+ : null;
+ if (createdAt === null || Number.isNaN(Date.parse(createdAt)))
+ return fail("created_at must be an instant");
+ const archived = table["archived"] ?? false;
+ if (typeof archived !== "boolean") return fail("archived must be a boolean");
+ const everyone = table["everyone"] ?? false;
+ if (typeof everyone !== "boolean") return fail("everyone must be a boolean");
+ if (everyone !== (channelId === DEFAULT_CHANNEL_ID)) {
+ return fail(
+ everyone
+ ? `everyone belongs to the all-hands channel ${DEFAULT_CHANNEL_ID} and to no other`
+ : `the all-hands channel ${DEFAULT_CHANNEL_ID} must be everyone = true`,
+ );
+ }
+ const rawMembers = table["members"];
+ if (everyone) {
+ if (rawMembers !== undefined) return fail("an everyone channel keeps no members list");
+ return {
+ ok: true,
+ value: {
+ name: name.trim(),
+ purpose: purpose.trim(),
+ createdBy,
+ createdAt: new Date(createdAt).toISOString(),
+ archived,
+ everyone: true,
+ },
+ };
+ }
+ if (!Array.isArray(rawMembers)) return fail("members must be a list of principals");
+ const members: string[] = [];
+ for (const m of rawMembers) {
+ if (typeof m !== "string" || !isPersonPrincipal(m))
+ return fail(`members entry is not a principal: ${String(m)}`);
+ if (members.includes(m)) return fail(`duplicate member: ${m}`);
+ members.push(m);
+ }
+ return {
+ ok: true,
+ value: {
+ name: name.trim(),
+ purpose: purpose.trim(),
+ createdBy,
+ createdAt: new Date(createdAt).toISOString(),
+ archived,
+ members,
+ },
+ };
+}
+
+export function serializeChannelConfig(cfg: ChannelConfig): string {
+ const table = {
+ name: cfg.name,
+ purpose: cfg.purpose,
+ created_by: cfg.createdBy,
+ created_at: cfg.createdAt,
+ archived: cfg.archived,
+ ...(cfg.everyone === true ? { everyone: true } : { members: cfg.members ?? [] }),
+ };
+ return [
+ "# channel.toml — a channel (the id is the directory name under channels/).",
+ "# members: agent:<id> / user:<id>; only members read and post, and only a member's",
+ "# mention reaches a desk. everyone = true marks the all-hands channel instead: every",
+ "# employee and every Project member belongs to it and there is no list to keep.",
+ "# archived: read-only, folded away in the UI, until a person unarchives it.",
+ stringifyToml(table),
+ "",
+ ].join("\n");
+}
+
+// ---------------------------------------------------------------------------
+// channels/<channel_id>/<yyyy-mm-dd>.jsonl
+// ---------------------------------------------------------------------------
+
+export const CHANNEL_MESSAGE_ID_PATTERN = /^msg-\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}-[0-9a-f]{8}$/;
+
+export function parseChannelMessageLine(line: string): ParseResult<OrgChannelMessage> {
+ let v: unknown;
+ try {
+ v = JSON.parse(line);
+ } catch {
+ return fail("line is not JSON");
+ }
+ if (v === null || typeof v !== "object") return fail("line is not a JSON object");
+ const o = v as Record<string, unknown>;
+ if (typeof o["id"] !== "string" || !CHANNEL_MESSAGE_ID_PATTERN.test(o["id"]))
+ return fail("id is not a message id");
+ if (typeof o["time"] !== "string" || Number.isNaN(Date.parse(o["time"])))
+ return fail("time is not an instant");
+ if (typeof o["sender"] !== "string" || parsePrincipal(o["sender"]) === null)
+ return fail("sender is not a principal");
+ const hop = o["hop"];
+ if (typeof hop !== "number" || !Number.isInteger(hop) || hop < 0)
+ return fail("hop must be a non-negative integer");
+ if (typeof o["text"] !== "string") return fail("text must be a string");
+ const mentions = o["mentions"] ?? [];
+ if (
+ !Array.isArray(mentions) ||
+ mentions.some((m) => typeof m !== "string" || parsePrincipal(m) === null)
+ ) {
+ return fail("mentions must be a list of principals");
+ }
+ let refs: OrgChannelMessage["refs"];
+ if (o["refs"] !== undefined) {
+ const r = o["refs"];
+ if (r === null || typeof r !== "object") return fail("refs must be an object");
+ const rr = r as Record<string, unknown>;
+ refs = {
+ ...(typeof rr["ticket"] === "string" ? { ticket: rr["ticket"] } : {}),
+ ...(typeof rr["session"] === "string" ? { session: rr["session"] } : {}),
+ ...(typeof rr["reply_to"] === "string" ? { replyTo: rr["reply_to"] } : {}),
+ };
+ }
+ // The kind is taken as written rather than checked against the known list: a line a newer
+ // server wrote still parses here, and a client that does not know the kind shows `text`.
+ let notice: OrgChannelMessage["notice"];
+ if (o["notice"] !== undefined) {
+ const n = o["notice"];
+ if (n === null || typeof n !== "object") return fail("notice must be an object");
+ const nn = n as Record<string, unknown>;
+ if (typeof nn["kind"] !== "string" || nn["kind"] === "")
+ return fail("notice.kind must be a non-empty string");
+ const params = nn["params"] ?? {};
+ if (params === null || typeof params !== "object" || Array.isArray(params))
+ return fail("notice.params must be an object");
+ const entries = Object.entries(params as Record<string, unknown>);
+ if (entries.some(([, value]) => typeof value !== "string"))
+ return fail("notice.params values must be strings");
+ notice = {
+ kind: nn["kind"] as OrgChannelNoticeKind,
+ params: Object.fromEntries(entries) as Record<string, string>,
+ };
+ }
+ return {
+ ok: true,
+ value: {
+ id: o["id"],
+ time: o["time"],
+ sender: o["sender"],
+ hop,
+ text: o["text"],
+ mentions: mentions as string[],
+ ...(refs !== undefined && Object.keys(refs).length > 0 ? { refs } : {}),
+ ...(notice !== undefined ? { notice } : {}),
+ },
+ };
+}
+
+export function serializeChannelMessageLine(msg: OrgChannelMessage): string {
+ const refs =
+ msg.refs === undefined
+ ? undefined
+ : {
+ ...(msg.refs.ticket !== undefined ? { ticket: msg.refs.ticket } : {}),
+ ...(msg.refs.session !== undefined ? { session: msg.refs.session } : {}),
+ ...(msg.refs.replyTo !== undefined ? { reply_to: msg.refs.replyTo } : {}),
+ };
+ return JSON.stringify({
+ id: msg.id,
+ time: msg.time,
+ sender: msg.sender,
+ hop: msg.hop,
+ text: msg.text,
+ mentions: msg.mentions,
+ ...(refs !== undefined && Object.keys(refs).length > 0 ? { refs } : {}),
+ ...(msg.notice !== undefined ? { notice: msg.notice } : {}),
+ });
+}
+
+export interface MentionToken {
+ /** `agent` / `user` when the writer disambiguated, absent for the short form. */
+ prefix?: "agent" | "user";
+ /** The bare id, or `all`. */
+ id: string;
+}
+
+/** The `@` tokens in a message: `@id`, `@agent:id`, `@user:id`, `@all`; who they resolve to is the service's call. */
+export function extractMentionTokens(text: string): MentionToken[] {
+ const out: MentionToken[] = [];
+ const re = /(^|[^A-Za-z0-9_@])@(?:(agent|user):)?([A-Za-z0-9][A-Za-z0-9_.-]*)/g;
+ for (const m of text.matchAll(re)) {
+ const prefix = m[2] as "agent" | "user" | undefined;
+ const id = m[3]!.replace(/[.-]+$/, "");
+ if (id === "") continue;
+ out.push({ ...(prefix !== undefined ? { prefix } : {}), id });
+ }
+ return out;
+}
diff --git a/packages/server/src/organization/handbook.ts b/packages/server/src/organization/handbook.ts
new file mode 100644
index 00000000..3ad435ed
--- /dev/null
+++ b/packages/server/src/organization/handbook.ts
@@ -0,0 +1,272 @@
+/**
+ * The organization handbook index — `handbook/README.md`; the `handbook/` directory is the
+ * company's knowledge base and this file is the one every work run reads first (progressive
+ * loading: the trigger block points here, the index points at the files and documents).
+ * Generated once at creation from the template of the organization's working language — the
+ * two templates carry the same sections and tables, with paths, commands, ids and field
+ * names ASCII in both; the CEO and HR own the file afterwards and may rewrite any of it.
+ */
+import type { OrgLanguage } from "../api/types.js";
+
+export interface HandbookInput {
+ orgId: string;
+ name: string;
+ mission: string;
+ ceoAgentId: string;
+ createdBy: string;
+ /** The organization's working language: which of the two templates is rendered. */
+ language: OrgLanguage;
+}
+
+export function renderHandbook(input: HandbookInput): string {
+ return input.language === "zh" ? renderZh(input) : renderEn(input);
+}
+
+function renderEn(input: HandbookInput): string {
+ const dir = `<app_data_dir>/organizations/${input.orgId}`;
+ return `# ${input.name} — organization handbook
+
+Organization id: \`${input.orgId}\` · CEO: \`${input.ceoAgentId}\` · Board (creator): \`user:${input.createdBy}\`
+
+## Mission
+
+${input.mission}
+
+## Working language
+
+This organization works in English: channel messages, tickets (title, goal, acceptance
+criteria, progress, result), handbook documents, calendar prompts and employee briefs are
+written in it. Commands, file names, ids and field names stay ASCII.
+
+## How this organization runs
+
+- Every employee is an Agent. The reporting tree lives in \`org_chart.yaml\`; the CEO is the root.
+- Each employee has one standing **desk session**. Calendar events and channel mentions arrive
+ there as a message that starts with an \`[org_trigger]\` block; ticket changes are listed in the
+ next calendar sweep, never sent on their own. The desk session schedules work; it does not do
+ the ticket work itself.
+- Work is carried by **tickets** on the board. A ticket's owner opens a separate **ticket
+ session** for it from its desk (\`penguin org ticket start <id>\`), tracks it, checks the result
+ and writes progress back. Only the owner's desk — or a person — starts a ticket's sessions:
+ work moves to another employee by reassigning the ticket
+ (\`penguin org ticket assign <id> --owner agent:<employee>\`), and that desk picks it up in its
+ next sweep. The owner may add \`--agent-id <colleague>\` to enlist a colleague on its own
+ ticket. Several sessions and several employees may contribute to one ticket.
+- Talking happens in **channels**, each a directory under \`channels/\`. \`default_channel\` is the
+ all-hands channel every employee and every board member is in; anyone may open more for a stream or a
+ big ticket and invite the principals that work needs. Only \`@<employee>\` and \`@all\` deliver
+ a message to someone's desk, and only inside the channel's own membership; everything else is
+ just recorded.
+- The **calendar** is the only periodic driver: an event's prompt tells the employee what to
+ look at. HR keeps every employee on exactly one recurring event at its own hour — a rota,
+ not a broadcast: cadences differ by role (daily owners, 2–3 days for reviewers, weekly for
+ finance) and no two desks share a start minute.
+- **Budgets** are monthly caps per employee (own spend plus every subordinate). Reaching the
+ warning ratio posts a system message in the all-hands channel; reaching the pause ratio stops
+ that employee's calendar until the next month or a raised budget. People can always talk to a
+ desk directly.
+
+## Directory layout
+
+\`${dir}/\`
+
+| Path | What it is | Who writes it |
+| --- | --- | --- |
+| \`org_config.toml\` | name, mission, status, timezone, working language, approval mode, mention-chain and budget thresholds | people, CEO |
+| \`org_chart.yaml\` | employee tree: title, reports_to, duties, workspace, budget, model | CEO, HR (\`penguin org hire\` / \`employee set\`) |
+| \`handbook/\` | the knowledge base: this index (\`README.md\`) and the documents it lists | CEO, HR, employees (\`penguin org handbook …\` or file tools) |
+| \`desks.toml\` | employee → current desk session (fact file) | the server |
+| \`calendar/<agent_id>/<event>.toml\` | calendar events, one file each (same fields as scheduled tasks, no target) | employees (\`penguin org calendar …\`) |
+| \`tickets/<yyyy-mm>/<column>/<yyyy-mm-dd>-<slug>.md\` | tickets; the column directory is the status | anyone (\`penguin org ticket …\`) |
+| \`channels/<channel_id>/channel.toml\` | a channel: name, purpose, members (\`default_channel\` is everyone) | members (\`penguin org channel …\`) |
+| \`channels/<channel_id>/<yyyy-mm-dd>.jsonl\` | a channel's messages, one per line | the server (\`penguin org channel send\`) |
+| \`workspace/\` (or the \`workspace\` path in \`org_config.toml\`) | the shared workspace; its root holds the shared inputs and is nobody's desk — the CEO works in \`ceo/\`, a hire lands in a sub-directory named after its Agent id unless another one is assigned, and a relative sub-directory is created by the server as it is assigned (an absolute path must already exist) | employees |
+
+Paths in prompts use \`<app_data_dir>\` placeholders; resolve them from the Environment section
+of your system prompt. Never write absolute paths into files other people read.
+
+## Principals
+
+People and employees are named \`user:<user_id>\` and \`agent:<agent_id>\` in every structured
+field (ticket headers, message senders and mentions). \`all\` in a mention means every member of
+that channel — in the all-hands channel, every employee; \`system\` is the scheduler. In message
+text \`@<id>\` is shorthand: employees resolve first, then Project members; write
+\`@agent:<id>\` or \`@user:<id>\` when both exist.
+
+## Ticket protocol
+
+- A ticket file is YAML frontmatter (\`title\`, \`status\`, \`owner\`, \`notify\`, \`priority\`, \`due\`,
+ \`blocked\`, \`sessions\`, \`history\`) followed by \`## Goal\`, \`## Acceptance criteria\`,
+ \`## Progress\` and \`## Result\`. Its id is \`<yyyy-mm-dd>-<slug>\`, the slug lowercase English
+ words joined by hyphens.
+- Columns: \`proposed\` → \`in_progress\` → \`review\` (optional) → \`done\`, or \`rejected\` (give a reason).
+- **One owner.** \`owner\` is the single principal responsible for the ticket — whoever filed it
+ unless the filing named someone else — and \`history\` records who filed it and everything since.
+- Anyone may propose. The CEO, the owner's manager or a person accepts (→ in_progress) or rejects.
+- The owner moves a finished ticket to \`review\`; the CEO or a person moves it to \`done\`.
+ P2 tickets may go straight to \`done\` when the acceptance criteria are plainly met.
+- Before a ticket session ends it writes progress (\`penguin org ticket progress <id> -m …\`) and
+ moves the ticket if the work is complete. \`## Progress\` is plain sentences: what was done and
+ where. No ids, no timestamps, no names — the server records who wrote each line and when.
+- Stuck (waiting for a decision, another ticket, a missing key): \`penguin org ticket block <id>
+ --reason … --by …\` and stop working on it. Blocked tickets are skipped by the sweep until unblocked.
+- Name every input you rely on and every deliverable you produce by its full path (absolute, or
+ \`<app_data_dir>/…\`) in \`## Goal\`, \`## Acceptance criteria\`, your progress lines and \`## Result\`;
+ a colleague must be able to open it without asking.
+- Closing a ticket notifies its \`notify\` list, and its owner when an employee owns it; a person
+ who wants to hear about it lists themselves in \`notify\`. Ticket changes are never posted in a
+ channel: the board is read from the board.
+
+## Decisions belong to the board
+
+The CEO proposes; the board (the creator, \`user:${input.createdBy}\`) decides. Before hiring
+(which roles, budgets, models), before setting or raising a budget, before rejecting someone
+else's ticket or closing a P0 / P1 ticket without review, before anything that reaches outside
+the organization (publishing, accounts, money) and before changing this handbook or the
+organization's structure, the CEO posts one clear proposal in the all-hands channel mentioning
+the board and stops until the answer comes back. Employees raise such matters to their manager;
+the CEO takes them to the board. Routine work inside an accepted plan needs no confirmation.
+
+## Channel etiquette
+
+- Mention someone only for a decision, a blocker, or a completion report. Never \`@all\` for chatter.
+- Answer in the channel the trigger names (its \`channel:\` line):
+ \`penguin org channel send --channel <id> -m …\`. During your calendar sweep read the channels
+ you are in: \`penguin org channel ls\`, then \`penguin org channel tail --channel <id>\`.
+- Open a channel when a thread would drown the all-hands channel — one per stream or per big
+ ticket (\`penguin org channel create <id>\`), invite exactly the principals the work needs
+ (\`penguin org channel invite <id> <principal>\`), and say so once in the all-hands channel.
+- You read and post only in channels you are a member of, and an employee joins one only when a
+ member invites it. What the board must decide goes to the all-hands channel, where they read.
+- A message that mentions someone who is not in the channel is refused: invite them first.
+- Mention chains stop after a few hops on purpose; a person or the calendar restarts the thread.
+
+## Roles
+
+- **CEO** (\`company-ceo\` skill): turns the mission into tickets, hires, partitions the shared
+ workspace, opens one channel per stream and invites its owners, reviews tickets, reports to
+ the board in the all-hands channel.
+- **HR** (\`company-hr\` skill): keeps every employee scheduled, hires and offboards, evaluates
+ and improves employees, keeps this handbook current.
+- **Finance** (\`company-finance\` skill): sets budgets, audits spend daily, explains alerts and
+ proposes savings.
+- **Everyone** (\`company-employee\` skill): reads this handbook first, sweeps the board, opens
+ and tracks ticket sessions, writes results back, blocks instead of idling, reports in its channels.
+
+## Knowledge base
+
+This directory (\`handbook/\`) is the company's knowledge base and this file is its index —
+the one file every run reads first. Keep durable knowledge here, one Markdown file per
+subject: decisions the board took (\`decisions/<yyyy-mm-dd>-<slug>.md\`), conventions,
+how-tos, product and market facts, anything the next run must not have to rediscover.
+List every document below with one line saying when it matters, so a run reads a document
+only when its line says so. \`penguin org handbook list | show <path> | write <path>\`
+reads and writes documents; the index cannot be deleted.
+
+## Documents
+
+_None yet._
+
+## Command reference
+
+See the \`company-employee\` skill for the full \`penguin org\` command surface. Inside a desk or
+ticket session \`--org-id\`, \`--project-id\`, \`--agent-id\` and the current session are already
+known from the environment.
+`;
+}
+
+function renderZh(input: HandbookInput): string {
+ const dir = `<app_data_dir>/organizations/${input.orgId}`;
+ return `# ${input.name} — 组织手册
+
+组织 id:\`${input.orgId}\` · CEO:\`${input.ceoAgentId}\` · 董事会(创建者):\`user:${input.createdBy}\`
+
+## 使命
+
+${input.mission}
+
+## 工作语言
+
+本组织的工作语言是中文:频道消息、工单(标题、目标、验收标准、进展、结果)、手册文档、日程提示词与员工简介都用中文书写。命令、文件名、id 与字段名一律保持 ASCII。
+
+## 这家组织如何运转
+
+- 每名员工都是一个 Agent。汇报树写在 \`org_chart.yaml\` 里,根是 CEO。
+- 每名员工有且只有一个常设的**工位会话**。日程项与频道里的提及以一条开头为 \`[org_trigger]\` 块的消息送到这里;工单的变化从不单独送来,而是列在下一次日历巡检的正文里。工位会话负责调度,不亲自做工单上的活。
+- 工作由看板上的**工单**承载。工单的负责人从自己的工位为它另开一个**工单会话**(\`penguin org ticket start <id>\`),跟踪它、检查结果、回写进展。只有负责人的工位或人可以为一张工单发起会话:要把活交给别的员工,就改派负责人(\`penguin org ticket assign <id> --owner agent:<员工>\`),那名员工的工位会在下一次巡检时接手。负责人可以加 \`--agent-id <同事>\` 把同事拉进自己名下的工单。一张工单可以由多个会话、多名员工共同贡献。
+- 交流发生在**频道**里,每个频道是 \`channels/\` 下的一个目录。\`default_channel\` 是全员频道,每名员工与每位董事会成员都在其中;任何人都可以为一条工作线或一张大工单另开频道,并邀请这项工作需要的主体。只有 \`@<员工>\` 与 \`@all\` 会把消息送到某人的工位,且只在该频道的成员范围内生效;其余内容只是记录在案。
+- **日历**是唯一的周期性驱动:一条日程项的提示词告诉员工该去看什么。HR 保证每名员工恰有一条各自时点的周期日程——这是轮值表,不是广播:节奏因角色而异(负责人每天、审核者两三天、财务每周),且没有两个工位共用同一个起始分钟。
+- **预算**是每名员工的月度上限(自身支出加上全部下属)。达到告警比例会在全员频道发一条系统消息;达到暂停比例则停掉该员工的日历,直到下个月或预算调高为止。人随时可以直接找工位说话。
+
+## 目录结构
+
+\`${dir}/\`
+
+| 路径 | 是什么 | 谁来写 |
+| --- | --- | --- |
+| \`org_config.toml\` | 名称、使命、状态、时区、工作语言、审批模式、@ 连锁上限与预算阈值 | 人、CEO |
+| \`org_chart.yaml\` | 员工树:头衔、reports_to、职责、workspace、预算、Model | CEO、HR(\`penguin org hire\` / \`employee set\`) |
+| \`handbook/\` | 知识库:这份索引(\`README.md\`)与它列出的文档 | CEO、HR、员工(\`penguin org handbook …\` 或文件工具) |
+| \`desks.toml\` | 员工 → 当前工位会话(事实文件) | 服务端 |
+| \`calendar/<agent_id>/<event>.toml\` | 日程项,一项一个文件(字段同定时任务,没有目标字段) | 员工(\`penguin org calendar …\`) |
+| \`tickets/<yyyy-mm>/<column>/<yyyy-mm-dd>-<slug>.md\` | 工单;所在列目录即状态 | 任何人(\`penguin org ticket …\`) |
+| \`channels/<channel_id>/channel.toml\` | 一个频道:名称、用途、成员(\`default_channel\` 是全员) | 成员(\`penguin org channel …\`) |
+| \`channels/<channel_id>/<yyyy-mm-dd>.jsonl\` | 频道消息,一行一条 | 服务端(\`penguin org channel send\`) |
+| \`workspace/\`(或 \`org_config.toml\` 里的 \`workspace\` 路径) | 公共工作区;根目录放共享输入,不是任何人的工位——CEO 在 \`ceo/\` 里工作,新员工不另行指定就落在以其 Agent id 命名的子目录里;相对子目录在分配时由服务端创建,绝对路径必须已存在 | 员工 |
+
+提示词里的路径一律用 \`<app_data_dir>\` 占位符,按系统提示词的 Environment 一节解析。绝不要把绝对路径写进别人会读的文件里。
+
+## 身份记号
+
+人和员工在所有结构化字段(工单头部、消息发送者与提及)里都记作 \`user:<user_id>\` 与 \`agent:<agent_id>\`。提及里的 \`all\` 指该频道的全体成员——在全员频道即全体员工;\`system\` 是调度器。消息正文里的 \`@<id>\` 是简写:先解析为员工,再解析为 Project 成员;两者都存在时写 \`@agent:<id>\` 或 \`@user:<id>\`。
+
+## 工单协议
+
+- 工单文件由 YAML frontmatter(\`title\`、\`status\`、\`owner\`、\`notify\`、\`priority\`、\`due\`、
+ \`blocked\`、\`sessions\`、\`history\`)加 \`## Goal\`、\`## Acceptance criteria\`、\`## Progress\`、
+ \`## Result\` 四节组成。id 形如 \`<yyyy-mm-dd>-<slug>\`,slug 是用连字符连接的小写英文单词。
+- 列:\`proposed\` → \`in_progress\` → \`review\`(可选)→ \`done\`,或 \`rejected\`(须给出理由)。
+- **负责人只有一个。** \`owner\` 是这张工单唯一的责任人——除非创建时指名他人,否则就是创建者本人;
+ 谁创建的以及此后发生的一切都记在 \`history\` 里。
+- 任何人都可以提出。由 CEO、负责人的上级或某个人接受(→ in_progress)或拒绝。
+- 负责人把完成的工单移到 \`review\`;由 CEO 或某个人移到 \`done\`。验收标准明显已满足的 P2 工单可以直接进 \`done\`。
+- 工单会话结束前要写进展(\`penguin org ticket progress <id> -m …\`),工作完成则移列。\`## Progress\`
+ 只写大白话句子:做了什么、东西在哪。不写 id、不写时间、不写人名——谁写的、什么时候写的由服务端记录。
+- 卡住了(等人拍板、等另一张工单、缺一把 key):\`penguin org ticket block <id> --reason … --by …\`,然后停手。被阻塞的工单在解除之前会被巡检跳过。
+- \`## Goal\`、\`## Acceptance criteria\`、进展行与 \`## Result\` 里的每个参考物与交付物都写**完整路径**(绝对路径或 \`<app_data_dir>/…\`),同事不用问就能打开。
+- 关闭一张工单会通知它的 \`notify\` 名单,负责人是员工时也通知负责人;想收到通知的人把自己列进 \`notify\`。
+ 工单的变化从不发到频道里:看板上的事,到看板上看。
+
+## 决策属于董事会
+
+CEO 提案,董事会(创建者 \`user:${input.createdBy}\`)拍板。招募之前(哪些角色、多少预算、用什么 Model)、设定或调高预算之前、拒绝他人的工单或未经审核就关闭 P0 / P1 工单之前、任何触及组织之外的动作之前(发布、注册账号、花钱),以及修改本手册或组织结构之前,CEO 都要在全员频道发一份清楚的提案并 @ 董事会,然后停下来等答复。员工把这类事项上报给自己的上级,由 CEO 带到董事会。已批准计划之内的日常工作不需要再确认。
+
+## 频道礼仪
+
+- 只在需要拍板、出现阻塞或汇报完成时提及别人。绝不为闲谈 \`@all\`。
+- 在触发块指明的频道里作答(它的 \`channel:\` 行):\`penguin org channel send --channel <id> -m …\`。日历巡检时读一遍自己所在的频道:\`penguin org channel ls\`,再 \`penguin org channel tail --channel <id>\`。
+- 一条线索会淹没全员频道时就另开频道——一条工作线或一张大工单一个(\`penguin org channel create <id>\`),只邀请这项工作需要的主体(\`penguin org channel invite <id> <principal>\`),并在全员频道里说明一次。
+- 你只在自己是成员的频道里读和发;员工只有被成员邀请才会加入一个频道。需要董事会拍板的事情要发到全员频道——他们在那里读。
+- 提及了不在该频道的人,整条消息会被拒收:先邀请对方。
+- @ 连锁在若干跳之后会有意停止;由人或日历重新发起线索。
+
+## 角色
+
+- **CEO**(\`company-ceo\` Skill):把使命拆成工单、招募、划分公共工作区、为每条工作线开一个频道并邀请其负责人、审核工单、在全员频道向董事会汇报。
+- **HR**(\`company-hr\` Skill):保证每名员工都有日程、负责招募与离职、评估并改进员工、维护本手册。
+- **财务**(\`company-finance\` Skill):设定预算、每天审计支出、解释告警并提出节流方案。
+- **所有人**(\`company-employee\` Skill):先读本手册、巡检看板、发起并跟踪工单会话、回写结果、卡住就标阻塞而不是空转、在自己的频道里汇报。
+
+## 知识库
+
+这个目录(\`handbook/\`)是公司的知识库,本文件是它的索引——每轮触发最先读的那一个文件。把可以长期沿用的知识放在这里,一个主题一个 Markdown 文件:董事会做出的决定(\`decisions/<yyyy-mm-dd>-<slug>.md\`)、约定、操作指南、产品与市场事实,以及任何不该让下一轮再重新摸索一遍的东西。每份文档都要在下面列出并用一行说明它何时相关,好让一轮运行只在那一行说了相关时才去读它。\`penguin org handbook list | show <path> | write <path>\` 用来读写文档;索引本身不可删除。
+
+## 文档
+
+_暂无。_
+
+## 命令参考
+
+完整的 \`penguin org\` 命令面见 \`company-employee\` Skill。在工位会话或工单会话内,\`--org-id\`、\`--project-id\`、\`--agent-id\` 与当前会话都已由环境给出。
+`;
+}
diff --git a/packages/server/src/organization/paths.ts b/packages/server/src/organization/paths.ts
new file mode 100644
index 00000000..e869916d
--- /dev/null
+++ b/packages/server/src/organization/paths.ts
@@ -0,0 +1,155 @@
+/**
+ * Where an organization lives on disk. Every path is under the Project directory —
+ * `<root>/<projectId>/organizations/<orgId>/` — so the model's `<app_data_dir>` placeholder
+ * (its Environment's App Data Dir is the Project directory) resolves to the same place the
+ * server reads. Files are the truth for company mode; nothing here touches SQLite.
+ */
+import path from "node:path";
+import { projectDir } from "@prismshadow/penguin-core";
+import type { OrgTicketStatus } from "../api/types.js";
+
+/** The kanban columns in board order; each is a directory under `tickets/<yyyy-mm>/`. */
+export const ORG_TICKET_COLUMNS: readonly OrgTicketStatus[] = [
+ "proposed",
+ "in_progress",
+ "review",
+ "done",
+ "rejected",
+];
+
+export function isTicketColumn(value: string): value is OrgTicketStatus {
+ return (ORG_TICKET_COLUMNS as readonly string[]).includes(value);
+}
+
+export function organizationsDir(root: string, projectId: string): string {
+ return path.join(projectDir(root, projectId), "organizations");
+}
+
+export function orgDir(root: string, projectId: string, orgId: string): string {
+ return path.join(organizationsDir(root, projectId), orgId);
+}
+
+export function orgConfigPath(dir: string): string {
+ return path.join(dir, "org_config.toml");
+}
+
+export function orgChartPath(dir: string): string {
+ return path.join(dir, "org_chart.yaml");
+}
+
+export function desksPath(dir: string): string {
+ return path.join(dir, "desks.toml");
+}
+
+/** `handbook/`: the organization handbook, the company's knowledge base. */
+export function handbookDir(dir: string): string {
+ return path.join(dir, "handbook");
+}
+
+/** `handbook/README.md`: the index every work run reads first. */
+export function handbookPath(dir: string): string {
+ return path.join(handbookDir(dir), "README.md");
+}
+
+/**
+ * A path inside the handbook, relative to `handbook/`: plain segments (no hidden files, no
+ * `.`/`..`, at most eight levels), so a request can never name a file outside the directory.
+ */
+export const HANDBOOK_FILE_PATTERN =
+ /^(?:[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/){0,7}[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
+
+export function isHandbookFilePath(rel: string): boolean {
+ return HANDBOOK_FILE_PATTERN.test(rel);
+}
+
+export function handbookFilePath(dir: string, rel: string): string {
+ if (!isHandbookFilePath(rel)) throw new Error(`invalid handbook path: ${rel}`);
+ return path.join(handbookDir(dir), ...rel.split("/"));
+}
+
+/**
+ * Calendar event names: the file's stem. The store only lists names matching this, so the
+ * writers validate against the same rule — otherwise a write lands a file no pass ever sees.
+ */
+export const CALENDAR_EVENT_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
+
+export function isCalendarEventName(name: string): boolean {
+ return CALENDAR_EVENT_NAME_PATTERN.test(name);
+}
+
+export function calendarDir(dir: string, agentId?: string): string {
+ return agentId === undefined ? path.join(dir, "calendar") : path.join(dir, "calendar", agentId);
+}
+
+export function calendarEventPath(dir: string, agentId: string, name: string): string {
+ return path.join(calendarDir(dir, agentId), `${name}.toml`);
+}
+
+export function ticketsDir(dir: string): string {
+ return path.join(dir, "tickets");
+}
+
+/** `tickets/<yyyy-mm>/<column>/<ticketId>.md`; the month comes from the id's date prefix. */
+export function ticketPath(dir: string, ticketId: string, column: OrgTicketStatus): string {
+ return path.join(ticketsDir(dir), ticketMonth(ticketId), column, `${ticketId}.md`);
+}
+
+/** The `yyyy-mm` a ticket id belongs to (its first seven characters). */
+export function ticketMonth(ticketId: string): string {
+ return ticketId.slice(0, 7);
+}
+
+/**
+ * Channel ids follow the semantic-id rule organization and Agent ids use, because the id is
+ * the directory name under `channels/`. `default_channel` is reserved for the all-hands
+ * channel every employee and every Project member belongs to implicitly.
+ */
+export const CHANNEL_ID_PATTERN = /^[a-z][a-z0-9_]{1,63}$/;
+
+export const DEFAULT_CHANNEL_ID = "default_channel";
+
+export function isChannelId(value: string): boolean {
+ return CHANNEL_ID_PATTERN.test(value);
+}
+
+/** `channels/`: one directory per channel. */
+export function channelsDir(dir: string): string {
+ return path.join(dir, "channels");
+}
+
+export function channelDir(dir: string, channelId: string): string {
+ return path.join(channelsDir(dir), channelId);
+}
+
+/** `channels/<channel_id>/channel.toml`: the channel's name, purpose and membership. */
+export function channelConfigPath(dir: string, channelId: string): string {
+ return path.join(channelDir(dir, channelId), "channel.toml");
+}
+
+/** `channels/<channel_id>/<yyyy-mm-dd>.jsonl`: one day's messages, one JSON line each. */
+export function channelDayPath(dir: string, channelId: string, date: string): string {
+ return path.join(channelDir(dir, channelId), `${date}.jsonl`);
+}
+
+export function workspaceDir(dir: string): string {
+ return path.join(dir, "workspace");
+}
+
+/**
+ * The canonical form of an employee's workspace spec, so `./hr`, `hr/` and `hr` are one
+ * partition in the chart rather than three spellings of it: a leading `./` and trailing
+ * slashes go, repeated slashes collapse, and `.` (the whole shared workspace) stays `.`.
+ * An absolute path keeps its shape — it is a user's directory, not ours to rewrite.
+ */
+export function normalizeWorkspaceSpec(spec: string): string {
+ let out = spec.trim().replace(/\/{2,}/g, "/");
+ if (path.isAbsolute(out)) return out.length > 1 ? out.replace(/\/+$/, "") : out;
+ while (out.startsWith("./")) out = out.slice(2);
+ out = out.replace(/\/+$/, "");
+ return out === "" ? "." : out;
+}
+
+/** The CEO's Agent id is fixed by the organization id, so creation can check it is free before writing anything. */
+export function ceoAgentId(orgId: string): string {
+ return `${orgId}_ceo`;
+}
diff --git a/packages/server/src/organization/principal.ts b/packages/server/src/organization/principal.ts
new file mode 100644
index 00000000..6c796a17
--- /dev/null
+++ b/packages/server/src/organization/principal.ts
@@ -0,0 +1,66 @@
+/**
+ * Principal notation — how organization files name a person or an employee:
+ * `agent:<agent_id>` / `user:<user_id>`, plus `all` (every employee) and `system` (the
+ * scheduler as a message sender). Agent ids and user ids are separate namespaces, which is
+ * exactly why the prefix exists: the same id could name both.
+ */
+
+export type Principal =
+ | { kind: "agent"; id: string }
+ | { kind: "user"; id: string }
+ | { kind: "all" }
+ | { kind: "system" };
+
+const ID = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
+
+export function parsePrincipal(raw: string): Principal | null {
+ const value = raw.trim();
+ if (value === "all") return { kind: "all" };
+ if (value === "system") return { kind: "system" };
+ const m = /^(agent|user):(.+)$/.exec(value);
+ if (!m || !ID.test(m[2]!)) return null;
+ return m[1] === "agent" ? { kind: "agent", id: m[2]! } : { kind: "user", id: m[2]! };
+}
+
+export function formatPrincipal(p: Principal): string {
+ switch (p.kind) {
+ case "agent":
+ return `agent:${p.id}`;
+ case "user":
+ return `user:${p.id}`;
+ case "all":
+ return "all";
+ case "system":
+ return "system";
+ }
+}
+
+export function agentPrincipal(agentId: string): string {
+ return `agent:${agentId}`;
+}
+
+export function userPrincipal(userId: string): string {
+ return `user:${userId}`;
+}
+
+/** The agent id behind an `agent:` principal string, or null for anything else. */
+export function principalAgentId(raw: string): string | null {
+ const p = parsePrincipal(raw);
+ return p?.kind === "agent" ? p.id : null;
+}
+
+/** The user id behind a `user:` principal string, or null for anything else. */
+export function principalUserId(raw: string): string | null {
+ const p = parsePrincipal(raw);
+ return p?.kind === "user" ? p.id : null;
+}
+
+/** Splits a `Notify`-style list: comma separated, blanks dropped, order kept, duplicates removed. */
+export function splitPrincipalList(raw: string): string[] {
+ const out: string[] = [];
+ for (const part of raw.split(",")) {
+ const v = part.trim();
+ if (v !== "" && !out.includes(v)) out.push(v);
+ }
+ return out;
+}
diff --git a/packages/server/src/organization/semantic-id.ts b/packages/server/src/organization/semantic-id.ts
new file mode 100644
index 00000000..cc1b3822
--- /dev/null
+++ b/packages/server/src/organization/semantic-id.ts
@@ -0,0 +1,112 @@
+/**
+ * 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/organization/store.ts b/packages/server/src/organization/store.ts
new file mode 100644
index 00000000..2fed0f1d
--- /dev/null
+++ b/packages/server/src/organization/store.ts
@@ -0,0 +1,576 @@
+/**
+ * File I/O for organization directories: the one place that knows how the files are laid
+ * out on disk. Reads return the raw text next to the parse result so callers can hash,
+ * echo or report it; writes are whole-file replacements. No SQLite here — the caches are
+ * the service's business.
+ */
+import fs from "node:fs/promises";
+import path from "node:path";
+import type { OrgChannelMessage, OrgTicketStatus } from "../api/types.js";
+import type {
+ CalendarEvent,
+ ChannelConfig,
+ Desks,
+ OrgChart,
+ OrgConfig,
+ ParseResult,
+ TicketDoc,
+} from "./files.js";
+import {
+ parseCalendarEvent,
+ parseChannelConfig,
+ parseChannelMessageLine,
+ parseDesks,
+ parseOrgChart,
+ parseOrgConfig,
+ parseTicket,
+ serializeChannelConfig,
+ serializeDesks,
+ serializeOrgChart,
+ serializeOrgConfig,
+ serializeTicket,
+} from "./files.js";
+import {
+ DEFAULT_CHANNEL_ID,
+ ORG_TICKET_COLUMNS,
+ calendarDir,
+ calendarEventPath,
+ channelConfigPath,
+ channelDayPath,
+ channelDir,
+ channelsDir,
+ desksPath,
+ handbookDir,
+ handbookFilePath,
+ handbookPath,
+ isCalendarEventName,
+ isChannelId,
+ orgChartPath,
+ orgConfigPath,
+ orgDir,
+ organizationsDir,
+ ticketPath,
+ ticketsDir,
+ workspaceDir,
+} from "./paths.js";
+
+/** Directory names that are Agent ids (organizations, calendar owners). */
+const ID = /^[a-z][a-z0-9_]{1,63}$/;
+const DATE = /^\d{4}-\d{2}-\d{2}$/;
+const MONTH = /^\d{4}-\d{2}$/;
+
+export interface OrgFile<T> {
+ raw: string;
+ parsed: ParseResult<T>;
+}
+
+/** One file of the handbook, `path` relative to `handbook/` with `/` separators. */
+export interface HandbookFile {
+ path: string;
+ size: number;
+ mtimeMs: number;
+}
+
+export interface CalendarFile {
+ agentId: string;
+ name: string;
+ raw: string;
+ parsed: ParseResult<CalendarEvent>;
+ mtimeMs: number;
+}
+
+/** One `channels/<channel_id>/channel.toml`, parsed; the id is the directory name. */
+export interface ChannelFile {
+ channelId: string;
+ raw: string;
+ parsed: ParseResult<ChannelConfig>;
+ mtimeMs: number;
+}
+
+export interface TicketFile {
+ /** Path relative to the organization directory. */
+ relPath: string;
+ ticketId: string;
+ /** The column directory the file sits in. */
+ column: OrgTicketStatus;
+ raw: string;
+ parsed: ParseResult<TicketDoc>;
+ mtimeMs: number;
+}
+
+async function readText(p: string): Promise<string | null> {
+ try {
+ return await fs.readFile(p, "utf8");
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
+ throw err;
+ }
+}
+
+async function writeText(p: string, text: string): Promise<void> {
+ await fs.mkdir(path.dirname(p), { recursive: true });
+ await fs.writeFile(p, text, "utf8");
+}
+
+export class OrgStore {
+ constructor(readonly root: string) {}
+
+ dir(projectId: string, orgId: string): string {
+ return orgDir(this.root, projectId, orgId);
+ }
+
+ /** Organization ids under a Project: the directories that carry an `org_config.toml`. */
+ async listOrgIds(projectId: string): Promise<string[]> {
+ let items: import("node:fs").Dirent[];
+ try {
+ items = await fs.readdir(organizationsDir(this.root, projectId), { withFileTypes: true });
+ } catch {
+ return [];
+ }
+ const out: string[] = [];
+ for (const d of items) {
+ if (!d.isDirectory() || !ID.test(d.name)) continue;
+ if (
+ (await readText(
+ orgConfigPath(path.join(organizationsDir(this.root, projectId), d.name)),
+ )) !== null
+ ) {
+ out.push(d.name);
+ }
+ }
+ return out.sort();
+ }
+
+ async exists(projectId: string, orgId: string): Promise<boolean> {
+ return (await readText(orgConfigPath(this.dir(projectId, orgId)))) !== null;
+ }
+
+ /**
+ * Creates the directory skeleton and the one file that is not a caller's to choose: the
+ * all-hands channel, which exists for as long as the organization does.
+ */
+ async createLayout(dir: string, createdAt = new Date().toISOString()): Promise<void> {
+ await fs.mkdir(path.dirname(dir), { recursive: true });
+ // Not recursive: an existing directory is a taken id, never something to reuse.
+ await fs.mkdir(dir, { recursive: false });
+ for (const sub of [
+ handbookDir(dir),
+ calendarDir(dir),
+ ticketsDir(dir),
+ channelsDir(dir),
+ workspaceDir(dir),
+ ]) {
+ await fs.mkdir(sub, { recursive: true });
+ }
+ // The purpose is left empty on purpose: seeded English prose would show verbatim in
+ // every locale. The channel view renders its own localized line for the all-hands
+ // channel when the purpose is unset, and a person may still write one.
+ await this.writeChannel(dir, DEFAULT_CHANNEL_ID, {
+ name: "All hands",
+ purpose: "",
+ createdBy: "system",
+ createdAt,
+ archived: false,
+ everyone: true,
+ });
+ }
+
+ async remove(dir: string): Promise<void> {
+ await fs.rm(dir, { recursive: true, force: true });
+ }
+
+ // ---- org_config.toml / org_chart.yaml / desks.toml / handbook/ ----
+
+ async readConfig(dir: string): Promise<OrgFile<OrgConfig> | null> {
+ const raw = await readText(orgConfigPath(dir));
+ return raw === null ? null : { raw, parsed: parseOrgConfig(raw) };
+ }
+
+ async writeConfig(dir: string, cfg: OrgConfig): Promise<void> {
+ await writeText(orgConfigPath(dir), serializeOrgConfig(cfg));
+ }
+
+ async readChart(dir: string, orgId: string): Promise<OrgFile<OrgChart> | null> {
+ const raw = await readText(orgChartPath(dir));
+ return raw === null ? null : { raw, parsed: parseOrgChart(raw, orgId) };
+ }
+
+ async writeChart(dir: string, chart: OrgChart): Promise<void> {
+ await writeText(orgChartPath(dir), serializeOrgChart(chart));
+ }
+
+ /** A missing ledger is an empty ledger. */
+ async readDesks(dir: string): Promise<OrgFile<Desks>> {
+ const raw = await readText(desksPath(dir));
+ return raw === null
+ ? { raw: "", parsed: { ok: true, value: {} } }
+ : { raw, parsed: parseDesks(raw) };
+ }
+
+ async writeDesks(dir: string, desks: Desks): Promise<void> {
+ await writeText(desksPath(dir), serializeDesks(desks));
+ }
+
+ async readHandbook(dir: string): Promise<string> {
+ return (await readText(handbookPath(dir))) ?? "";
+ }
+
+ async writeHandbook(dir: string, content: string): Promise<void> {
+ await writeText(handbookPath(dir), content);
+ }
+
+ /** Every file under `handbook/` (hidden entries skipped), the index first, then by path. */
+ async listHandbookFiles(dir: string): Promise<HandbookFile[]> {
+ const base = handbookDir(dir);
+ const out: HandbookFile[] = [];
+ const walk = async (rel: string[]): Promise<void> => {
+ let entries: import("node:fs").Dirent[];
+ try {
+ entries = await fs.readdir(path.join(base, ...rel), { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const e of entries) {
+ if (e.name.startsWith(".")) continue;
+ const next = [...rel, e.name];
+ if (e.isDirectory()) {
+ await walk(next);
+ } else if (e.isFile()) {
+ const st = await fs.stat(path.join(base, ...next));
+ out.push({ path: next.join("/"), size: st.size, mtimeMs: st.mtimeMs });
+ }
+ }
+ };
+ await walk([]);
+ out.sort((a, b) =>
+ a.path === "README.md" ? -1 : b.path === "README.md" ? 1 : a.path.localeCompare(b.path),
+ );
+ return out;
+ }
+
+ async readHandbookFile(dir: string, rel: string): Promise<string | null> {
+ return readText(handbookFilePath(dir, rel));
+ }
+
+ async writeHandbookFile(dir: string, rel: string, content: string): Promise<void> {
+ await writeText(handbookFilePath(dir, rel), content);
+ }
+
+ /** Removes the file and any directory it leaves empty, up to (not including) `handbook/`. */
+ async deleteHandbookFile(dir: string, rel: string): Promise<void> {
+ const file = handbookFilePath(dir, rel);
+ await fs.rm(file, { force: true });
+ const base = handbookDir(dir);
+ let parent = path.dirname(file);
+ while (parent !== base && parent.startsWith(base)) {
+ try {
+ await fs.rmdir(parent);
+ } catch {
+ break;
+ }
+ parent = path.dirname(parent);
+ }
+ }
+
+ // ---- calendar ----
+
+ async listCalendar(dir: string): Promise<CalendarFile[]> {
+ const out: CalendarFile[] = [];
+ let agents: import("node:fs").Dirent[];
+ try {
+ agents = await fs.readdir(calendarDir(dir), { withFileTypes: true });
+ } catch {
+ return out;
+ }
+ for (const a of agents) {
+ if (!a.isDirectory() || !ID.test(a.name)) continue;
+ const files = await fs.readdir(calendarDir(dir, a.name), { withFileTypes: true });
+ for (const f of files) {
+ if (!f.isFile() || !f.name.endsWith(".toml")) continue;
+ const name = f.name.slice(0, -".toml".length);
+ if (!isCalendarEventName(name)) continue;
+ const p = calendarEventPath(dir, a.name, name);
+ const [raw, stat] = await Promise.all([fs.readFile(p, "utf8"), fs.stat(p)]);
+ out.push({
+ agentId: a.name,
+ name,
+ raw,
+ parsed: parseCalendarEvent(name, raw),
+ mtimeMs: stat.mtimeMs,
+ });
+ }
+ }
+ return out.sort((x, y) => x.agentId.localeCompare(y.agentId) || x.name.localeCompare(y.name));
+ }
+
+ async readCalendarEvent(
+ dir: string,
+ agentId: string,
+ name: string,
+ ): Promise<CalendarFile | null> {
+ const p = calendarEventPath(dir, agentId, name);
+ const raw = await readText(p);
+ if (raw === null) return null;
+ const stat = await fs.stat(p);
+ return { agentId, name, raw, parsed: parseCalendarEvent(name, raw), mtimeMs: stat.mtimeMs };
+ }
+
+ async writeCalendarEvent(dir: string, agentId: string, name: string, raw: string): Promise<void> {
+ await writeText(calendarEventPath(dir, agentId, name), raw);
+ }
+
+ async deleteCalendarEvent(dir: string, agentId: string, name: string): Promise<boolean> {
+ try {
+ await fs.unlink(calendarEventPath(dir, agentId, name));
+ return true;
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return false;
+ throw err;
+ }
+ }
+
+ // ---- tickets ----
+
+ /**
+ * Every ticket file across months and columns. A file whose name is not a ticket id, or
+ * that sits in a directory that is not a column, is skipped — it is not a ticket.
+ */
+ async listTickets(dir: string): Promise<TicketFile[]> {
+ const out: TicketFile[] = [];
+ let months: import("node:fs").Dirent[];
+ try {
+ months = await fs.readdir(ticketsDir(dir), { withFileTypes: true });
+ } catch {
+ return out;
+ }
+ for (const m of months) {
+ if (!m.isDirectory() || !MONTH.test(m.name)) continue;
+ for (const column of ORG_TICKET_COLUMNS) {
+ const colDir = path.join(ticketsDir(dir), m.name, column);
+ let files: import("node:fs").Dirent[];
+ try {
+ files = await fs.readdir(colDir, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const f of files) {
+ if (!f.isFile() || !f.name.endsWith(".md")) continue;
+ const ticketId = f.name.slice(0, -".md".length);
+ const p = path.join(colDir, f.name);
+ const [raw, stat] = await Promise.all([fs.readFile(p, "utf8"), fs.stat(p)]);
+ out.push({
+ relPath: path.relative(dir, p),
+ ticketId,
+ column,
+ raw,
+ parsed: parseTicket(raw),
+ mtimeMs: stat.mtimeMs,
+ });
+ }
+ }
+ }
+ return out.sort((a, b) => a.ticketId.localeCompare(b.ticketId));
+ }
+
+ /** Locates a ticket by id: its month is in the id, its column is whichever directory holds it. */
+ async findTicket(dir: string, ticketId: string): Promise<TicketFile | null> {
+ for (const column of ORG_TICKET_COLUMNS) {
+ const p = ticketPath(dir, ticketId, column);
+ const raw = await readText(p);
+ if (raw === null) continue;
+ const stat = await fs.stat(p);
+ return {
+ relPath: path.relative(dir, p),
+ ticketId,
+ column,
+ raw,
+ parsed: parseTicket(raw),
+ mtimeMs: stat.mtimeMs,
+ };
+ }
+ return null;
+ }
+
+ async writeTicket(
+ dir: string,
+ ticketId: string,
+ column: OrgTicketStatus,
+ doc: TicketDoc,
+ ): Promise<void> {
+ await writeText(ticketPath(dir, ticketId, column), serializeTicket(doc));
+ }
+
+ /** Rewrites the file in its new column and removes the old one (the header was updated by the caller). */
+ async moveTicket(
+ dir: string,
+ ticketId: string,
+ from: OrgTicketStatus,
+ to: OrgTicketStatus,
+ doc: TicketDoc,
+ ): Promise<void> {
+ await this.writeTicket(dir, ticketId, to, doc);
+ if (from !== to) await fs.unlink(ticketPath(dir, ticketId, from)).catch(() => {});
+ }
+
+ // ---- channels ----
+
+ /**
+ * Every channel directory that carries a `channel.toml`, by id. A plain file under
+ * `channels/` is not a channel and is skipped rather than reported, and neither is a
+ * directory without that file — a stray entry must not make the whole listing an error.
+ */
+ async listChannels(dir: string): Promise<ChannelFile[]> {
+ let entries: import("node:fs").Dirent[];
+ try {
+ entries = await fs.readdir(channelsDir(dir), { withFileTypes: true });
+ } catch {
+ return [];
+ }
+ const out: ChannelFile[] = [];
+ for (const e of entries) {
+ if (!e.isDirectory() || !isChannelId(e.name)) continue;
+ const file = await this.readChannel(dir, e.name);
+ if (file !== null) out.push(file);
+ }
+ return out.sort((a, b) => a.channelId.localeCompare(b.channelId));
+ }
+
+ /** Null when the directory carries no `channel.toml`: it is not a channel. */
+ async readChannel(dir: string, channelId: string): Promise<ChannelFile | null> {
+ const p = channelConfigPath(dir, channelId);
+ const raw = await readText(p);
+ if (raw === null) return null;
+ const stat = await fs.stat(p);
+ return { channelId, raw, parsed: parseChannelConfig(channelId, raw), mtimeMs: stat.mtimeMs };
+ }
+
+ async writeChannel(dir: string, channelId: string, cfg: ChannelConfig): Promise<void> {
+ await writeText(channelConfigPath(dir, channelId), serializeChannelConfig(cfg));
+ }
+
+ // ---- channel messages ----
+
+ async listMessageDays(dir: string, channelId: string): Promise<string[]> {
+ let files: import("node:fs").Dirent[];
+ try {
+ files = await fs.readdir(channelDir(dir, channelId), { withFileTypes: true });
+ } catch {
+ return [];
+ }
+ return files
+ .filter(
+ (f) =>
+ f.isFile() && f.name.endsWith(".jsonl") && DATE.test(f.name.slice(0, -".jsonl".length)),
+ )
+ .map((f) => f.name.slice(0, -".jsonl".length))
+ .sort()
+ .reverse();
+ }
+
+ async appendMessageLine(
+ dir: string,
+ channelId: string,
+ date: string,
+ line: string,
+ ): Promise<void> {
+ const p = channelDayPath(dir, channelId, date);
+ await fs.mkdir(path.dirname(p), { recursive: true });
+ await fs.appendFile(p, `${line}\n`, "utf8");
+ }
+
+ /** Every parsable message of a day, in file order; malformed lines are reported alongside. */
+ async readMessageDay(
+ dir: string,
+ channelId: string,
+ date: string,
+ ): Promise<{ messages: OrgChannelMessage[]; invalid: number }> {
+ const raw = await readText(channelDayPath(dir, channelId, date));
+ if (raw === null) return { messages: [], invalid: 0 };
+ const messages: OrgChannelMessage[] = [];
+ let invalid = 0;
+ for (const line of raw.split("\n")) {
+ if (line.trim() === "") continue;
+ const r = parseChannelMessageLine(line);
+ if (r.ok) messages.push(r.value);
+ else invalid++;
+ }
+ return { messages, invalid };
+ }
+
+ /**
+ * Tail scan: the complete lines after a byte offset, and the offset they end at. A file
+ * shorter than the offset (rewritten by hand) is re-read from the start.
+ */
+ async readMessagesFrom(
+ dir: string,
+ channelId: string,
+ date: string,
+ offset: number,
+ ): Promise<{ lines: string[]; nextOffset: number }> {
+ const p = channelDayPath(dir, channelId, date);
+ let buf: Buffer;
+ try {
+ buf = await fs.readFile(p);
+ } catch {
+ return { lines: [], nextOffset: 0 };
+ }
+ const start = offset > buf.length ? 0 : offset;
+ const lastNl = buf.lastIndexOf(0x0a);
+ if (lastNl < start) return { lines: [], nextOffset: start };
+ const text = buf.subarray(start, lastNl + 1).toString("utf8");
+ return {
+ lines: text.split("\n").filter((l) => l.trim() !== ""),
+ nextOffset: lastNl + 1,
+ };
+ }
+
+ // ---- workspace ----
+
+ /**
+ * Where an employee's workspace spec points, without touching the disk: relative → under
+ * the shared workspace, absolute → itself. Null only when a relative spec climbs out of
+ * the shared workspace with `..` — that is a spec no organization may hold, whether or not
+ * the directory happens to exist.
+ */
+ workspaceTarget(shared: string, spec: string): string | null {
+ if (path.isAbsolute(spec)) return spec;
+ const target = path.resolve(shared, spec);
+ const rel = path.relative(shared, target);
+ return rel.startsWith("..") || path.isAbsolute(rel) ? null : target;
+ }
+
+ /**
+ * Resolves an employee's workspace as the chart writes it, read-only: null when the spec
+ * escapes the shared workspace or the directory does not exist. Callers that are about to
+ * put an employee to work use {@link ensureWorkspace} instead.
+ */
+ async resolveWorkspace(shared: string, spec: string): Promise<string | null> {
+ const target = this.workspaceTarget(shared, spec);
+ if (target === null) return null;
+ try {
+ const stat = await fs.stat(target);
+ return stat.isDirectory() ? target : null;
+ } catch {
+ return null;
+ }
+ }
+
+ /**
+ * The workspace to open a session in, created when it is the organization's to create: a
+ * relative spec names a partition of the shared workspace, so the server makes it rather
+ * than refusing an employee for a directory nobody thought to create; an absolute spec
+ * names an arbitrary user directory and must already exist. Null when a relative spec
+ * escapes the shared workspace, or when an absolute one is missing or not a directory.
+ */
+ async ensureWorkspace(shared: string, spec: string): Promise<string | null> {
+ const target = this.workspaceTarget(shared, spec);
+ if (target === null) return null;
+ if (path.isAbsolute(spec)) return this.resolveWorkspace(shared, spec);
+ try {
+ await fs.mkdir(target, { recursive: true });
+ } catch {
+ return null;
+ }
+ return target;
+ }
+}
diff --git a/packages/server/src/organization/zoned.ts b/packages/server/src/organization/zoned.ts
new file mode 100644
index 00000000..d76658a5
--- /dev/null
+++ b/packages/server/src/organization/zoned.ts
@@ -0,0 +1,135 @@
+/**
+ * Timezone arithmetic for organizations: budget periods are natural months and channel files
+ * are split by day **in the organization's timezone**, while every stored instant stays
+ * UTC. Intl is the only clock-zone source Node ships with, so the conversions go through
+ * `formatToParts` rather than a bundled zone table.
+ */
+
+export interface ZonedParts {
+ year: number;
+ month: number;
+ day: number;
+ hour: number;
+ minute: number;
+ second: number;
+}
+
+const formatters = new Map<string, Intl.DateTimeFormat>();
+
+function formatterFor(timeZone: string): Intl.DateTimeFormat {
+ let f = formatters.get(timeZone);
+ if (!f) {
+ f = new Intl.DateTimeFormat("en-CA", {
+ timeZone,
+ hourCycle: "h23",
+ year: "numeric",
+ month: "2-digit",
+ day: "2-digit",
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ });
+ formatters.set(timeZone, f);
+ }
+ return f;
+}
+
+export function isValidTimeZone(timeZone: string): boolean {
+ try {
+ formatterFor(timeZone);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** The wall-clock parts of an instant in a zone. */
+export function zonedParts(timeZone: string, ms: number): ZonedParts {
+ const parts = formatterFor(timeZone).formatToParts(new Date(ms));
+ const get = (type: Intl.DateTimeFormatPartTypes): number =>
+ Number(parts.find((p) => p.type === type)?.value ?? "0");
+ return {
+ year: get("year"),
+ month: get("month"),
+ day: get("day"),
+ // Some engines print "24" for midnight under h23; normalize.
+ hour: get("hour") % 24,
+ minute: get("minute"),
+ second: get("second"),
+ };
+}
+
+const pad = (n: number, w = 2): string => String(n).padStart(w, "0");
+
+/** `yyyy-mm-dd` of an instant in a zone. */
+export function zonedDate(timeZone: string, ms: number): string {
+ const p = zonedParts(timeZone, ms);
+ return `${pad(p.year, 4)}-${pad(p.month)}-${pad(p.day)}`;
+}
+
+/** The zone's UTC offset in minutes at an instant (positive east of UTC). */
+export function zonedOffsetMinutes(timeZone: string, ms: number): number {
+ const p = zonedParts(timeZone, ms);
+ const asUtc = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second);
+ return Math.round((asUtc - Math.floor(ms / 1000) * 1000) / 60_000);
+}
+
+/** The instant of a zone's local wall-clock time (a second pass corrects for a DST edge). */
+export function zonedLocalToUtc(
+ timeZone: string,
+ year: number,
+ month: number,
+ day: number,
+ hour = 0,
+ minute = 0,
+): number {
+ const guess = Date.UTC(year, month - 1, day, hour, minute);
+ const first = guess - zonedOffsetMinutes(timeZone, guess) * 60_000;
+ return guess - zonedOffsetMinutes(timeZone, first) * 60_000;
+}
+
+export interface ZonedMonthRange {
+ /** `yyyy-mm`. */
+ period: string;
+ /** First instant of the month (inclusive), epoch ms. */
+ fromMs: number;
+ /** First instant of the next month (exclusive), epoch ms. */
+ toMs: number;
+}
+
+/** The natural month containing `ms` in a zone; `period` names it, the bounds are UTC instants. */
+export function zonedMonthRange(timeZone: string, ms: number): ZonedMonthRange {
+ const p = zonedParts(timeZone, ms);
+ const nextYear = p.month === 12 ? p.year + 1 : p.year;
+ const nextMonth = p.month === 12 ? 1 : p.month + 1;
+ return {
+ period: `${pad(p.year, 4)}-${pad(p.month)}`,
+ fromMs: zonedLocalToUtc(timeZone, p.year, p.month, 1),
+ toMs: zonedLocalToUtc(timeZone, nextYear, nextMonth, 1),
+ };
+}
+
+/** The range for an explicit `yyyy-mm` period; null when the period is malformed. */
+export function zonedPeriodRange(timeZone: string, period: string): ZonedMonthRange | null {
+ const m = /^(\d{4})-(\d{2})$/.exec(period);
+ if (!m) return null;
+ const year = Number(m[1]);
+ const month = Number(m[2]);
+ if (month < 1 || month > 12) return null;
+ const nextYear = month === 12 ? year + 1 : year;
+ const nextMonth = month === 12 ? 1 : month + 1;
+ return {
+ period,
+ fromMs: zonedLocalToUtc(timeZone, year, month, 1),
+ toMs: zonedLocalToUtc(timeZone, nextYear, nextMonth, 1),
+ };
+}
+
+/** The day `[from, to)` range of a `yyyy-mm-dd` in a zone. */
+export function zonedDayRange(timeZone: string, date: string): { fromMs: number; toMs: number } {
+ const [y, m, d] = date.split("-").map(Number) as [number, number, number];
+ return {
+ fromMs: zonedLocalToUtc(timeZone, y, m, d),
+ toMs: zonedLocalToUtc(timeZone, y, m, d + 1),
+ };
+}
diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.ts
index 77bb8d84..fc99eef5 100644
--- a/packages/server/src/platform.ts
+++ b/packages/server/src/platform.ts
@@ -71,6 +71,7 @@ import { UsageRepo } from "./db/repos/usage.js";
import { SchedulesRepo } from "./db/repos/schedules.js";
import { TraceIndexRepo } from "./db/repos/trace-index.js";
import { MessagingBindingsRepo } from "./db/repos/messaging-bindings.js";
+import { OrgCacheRepo } from "./db/repos/organizations.js";
import { ErrorsRepo } from "./db/repos/errors.js";
import { SessionSources } from "./runtime/session-sources.js";
import { ErrorRecorder } from "./runtime/error-recorder.js";
@@ -96,6 +97,9 @@ import { ProjectsRoutes } from "./http/routes/dirs.js";
import { SandboxModule } from "./sandbox/service.js";
import { SchedulerRoutes } from "./http/routes/schedules.js";
import { Machines, MachinesModule } from "./machines/service.js";
+import { OrganizationModule, OrgScheduler, OrgService } from "./runtime/organization/service.js";
+import { OrgRoutes } from "./http/routes/organizations.js";
+import { OrgRuns, OrgSessions } from "./runtime/organization/deps.js";
import { ProjectAdminRoutes } from "./http/routes/projects.js";
import { AdminRoutes } from "./http/routes/admin.js";
import { MeRoutes } from "./http/routes/me.js";
@@ -130,6 +134,7 @@ import { AgentConfig, AgentLifecycle, Benchmarks, Memory, Snapshots } from "./me
import { WorkspaceFiles } from "./mechanisms/workspace.js";
import { Settings, UiPrefsStore } from "./mechanisms/settings.js";
import { MessagingBindings } from "./mechanisms/messaging.js";
+import { OrgCache } from "./mechanisms/organization.js";
import { PreviewModule, PreviewTokens } from "./http/routes/preview.js";
import { Http, HttpModule } from "./http/app.js";
import { WebModule, WebShell } from "./http/routes/contributions.js";
@@ -152,6 +157,7 @@ import { WebModule, WebShell } from "./http/routes/contributions.js";
@Component()
export class Startup {
@Use() private readonly scheduler!: Scheduling;
+ @Use() private readonly orgScheduler!: OrgScheduler;
@Use() private readonly sessionService!: SessionServiceIface;
@Use() private readonly machines!: Machines;
@Use() private readonly errors!: Errors;
@@ -159,6 +165,9 @@ export class Startup {
async setup() {
// Schedule scheduler: startup reconciliation (missed, don't backfill) + periodic scan.
await this.scheduler.start();
+ // Company mode's scheduler: same lifetime and the same startup rule (reconcile once,
+ // no backfill), only active while this App is.
+ await this.orgScheduler.start();
// Startup adoption sweep: fold Trace-only Sessions into the index. Fire-and-forget —
// a broken trace shard must not block the boot.
void this.sessionService.adoptUnmanagedTraceSessions().catch((err: unknown) => {
@@ -281,6 +290,8 @@ export class ProjectsModule {}
ScheduleTaskRunner,
ScheduleSessionCreator,
MessagingTaskRunner,
+ OrgRuns,
+ OrgSessions,
ProjectRuns,
],
})
@@ -339,6 +350,17 @@ export class WorkspaceModule {}
})
export class MessagingHubModule {}
+/**
+ * Company mode: the organization runtime, its routes and the caches they project into.
+ * The caches are the group's own store — only the four members the session runtime and
+ * Project deletion reach for leave the group, as OrgCache.
+ */
+@Module({
+ children: [OrgCacheRepo, OrganizationModule, OrgRoutes],
+ exports: [OrgCache, OrgService, OrgScheduler],
+})
+export class CompanyModule {}
+
@Module({
children: [
GlobalFetch,
@@ -371,6 +393,7 @@ export class ApiModule {}
AgentsModule,
WorkspaceModule,
MessagingHubModule,
+ CompanyModule,
ApiModule,
SandboxModule,
TerminalModule,
diff --git a/packages/server/src/runtime/error-recorder.ts b/packages/server/src/runtime/error-recorder.ts
index 7e834180..2d74342a 100644
--- a/packages/server/src/runtime/error-recorder.ts
+++ b/packages/server/src/runtime/error-recorder.ts
@@ -60,6 +60,7 @@ import type { ErrorLog, Errors } from "../mechanisms/observability.js";
/** Capture-site source (maps one-to-one to error_records.source). */
export type ErrorSource =
| "http"
+ | "organization"
| "session"
| "llm"
| "environment"
diff --git a/packages/server/src/runtime/organization/budget.ts b/packages/server/src/runtime/organization/budget.ts
new file mode 100644
index 00000000..4d7d1d04
--- /dev/null
+++ b/packages/server/src/runtime/organization/budget.ts
@@ -0,0 +1,170 @@
+/**
+ * Spend attribution for an organization: every cost figure is derived from usage records
+ * joined to the sessions the organization's files claim — desk sessions from the ledger,
+ * contributing sessions from the tickets' `Sessions` headers. Nothing is stored; the
+ * budget marks in SQLite only remember which alerts already fired.
+ */
+import type { TicketDoc } from "../../organization/files.js";
+import { subordinatesOf } from "../../organization/files.js";
+import { zonedMonthRange, zonedPeriodRange } from "../../organization/zoned.js";
+import type { ZonedMonthRange } from "../../organization/zoned.js";
+import type { OrgDeps } from "./deps.js";
+import type { LoadedOrg } from "./model.js";
+
+export interface OrgSpend {
+ period: string;
+ range: ZonedMonthRange;
+ /** Cost per session over the period. */
+ bySession: Map<string, number>;
+ /** Cost of an employee's own sessions (desk + contributing), each session once. */
+ own: Map<string, number>;
+ /** Own plus every subordinate's own, recursively. */
+ cumulative: Map<string, number>;
+ /** A ticket's share of its contributing sessions (a session on n tickets counts 1/n). */
+ ticket: Map<string, number>;
+ /** A ticket's share plus its descendants' along `Parent`. */
+ ticketRolledUp: Map<string, number>;
+ /** Some usage ran on an unpriced model. */
+ unpriced: boolean;
+ /** The organization's session ids the figures were computed over. */
+ sessionIds: string[];
+}
+
+export interface TicketForSpend {
+ ticketId: string;
+ doc: TicketDoc;
+}
+
+/** Which sessions the organization owns and which employee each belongs to (desk sessions by ledger, ticket sessions by the session row). */
+export function orgSessionOwners(
+ deps: OrgDeps,
+ org: LoadedOrg,
+ tickets: readonly TicketForSpend[],
+): Map<string, string> {
+ const owners = new Map<string, string>();
+ for (const [agentId, desk] of Object.entries(org.desks)) {
+ owners.set(desk.sessionId, agentId);
+ for (const prev of desk.previous) owners.set(prev, agentId);
+ }
+ for (const t of tickets) {
+ for (const sessionId of t.doc.sessions) {
+ if (owners.has(sessionId)) continue;
+ const row = deps.sessions.findById(sessionId);
+ if (row && row.projectId === org.projectId) owners.set(sessionId, row.agentId);
+ }
+ }
+ return owners;
+}
+
+export async function computeSpend(
+ deps: OrgDeps,
+ org: LoadedOrg,
+ tickets: readonly TicketForSpend[],
+ period?: string,
+): Promise<OrgSpend> {
+ const now = deps.now?.() ?? Date.now();
+ // An explicit period that is not a month is a caller's bug — the routes refuse one with a
+ // 400 — and answering it with the current month's figures would be a wrong answer told
+ // quietly. Only the absent period falls back to the month in progress.
+ const explicit = period !== undefined ? zonedPeriodRange(org.config.timezone, period) : null;
+ if (period !== undefined && explicit === null)
+ throw new Error(`period must be yyyy-mm: ${period}`);
+ const range = explicit ?? zonedMonthRange(org.config.timezone, now);
+ const owners = orgSessionOwners(deps, org, tickets);
+ const sessionIds = [...owners.keys()];
+ const { bySession, unpriced } = await deps.usage.costBySession(
+ org.projectId,
+ sessionIds,
+ new Date(range.fromMs).toISOString(),
+ new Date(range.toMs - 1).toISOString(),
+ );
+ const own = new Map<string, number>();
+ for (const e of org.chart.employees) own.set(e.agentId, 0);
+ for (const [sessionId, agentId] of owners) {
+ const cost = bySession.get(sessionId) ?? 0;
+ own.set(agentId, (own.get(agentId) ?? 0) + cost);
+ }
+ const cumulative = new Map<string, number>();
+ for (const e of org.chart.employees) {
+ let sum = own.get(e.agentId) ?? 0;
+ for (const sub of subordinatesOf(org.chart, e.agentId)) sum += own.get(sub) ?? 0;
+ cumulative.set(e.agentId, sum);
+ }
+ // A session attached to n tickets is split n ways so parents and the organization never double count it.
+ const ticketsPerSession = new Map<string, number>();
+ for (const t of tickets) {
+ for (const s of new Set(t.doc.sessions))
+ ticketsPerSession.set(s, (ticketsPerSession.get(s) ?? 0) + 1);
+ }
+ const ticket = new Map<string, number>();
+ for (const t of tickets) {
+ let sum = 0;
+ for (const s of new Set(t.doc.sessions))
+ sum += (bySession.get(s) ?? 0) / (ticketsPerSession.get(s) ?? 1);
+ ticket.set(t.ticketId, sum);
+ }
+ const children = new Map<string, string[]>();
+ for (const t of tickets) {
+ if (t.doc.parent !== undefined)
+ children.set(t.doc.parent, [...(children.get(t.doc.parent) ?? []), t.ticketId]);
+ }
+ const ticketRolledUp = new Map<string, number>();
+ const rollUp = (id: string, depth: number): number => {
+ const cached = ticketRolledUp.get(id);
+ if (cached !== undefined) return cached;
+ let sum = ticket.get(id) ?? 0;
+ if (depth < 64) for (const c of children.get(id) ?? []) sum += rollUp(c, depth + 1);
+ ticketRolledUp.set(id, sum);
+ return sum;
+ };
+ for (const t of tickets) rollUp(t.ticketId, 0);
+ return {
+ period: range.period,
+ range,
+ bySession,
+ own,
+ cumulative,
+ ticket,
+ ticketRolledUp,
+ unpriced,
+ sessionIds,
+ };
+}
+
+const money = (n: number): string => n.toFixed(2);
+
+/**
+ * Spend as a fraction of a budget. Zero is a real budget — everything is already over it —
+ * so it reads as 1 rather than as no ratio at all: an employee capped at zero is warned and
+ * paused on the first pass, and a row that reports that with no meter beside it explains
+ * nothing. Unbounded is `budget === undefined`, and has no ratio to report.
+ */
+export function budgetRatio(cost: number, budget: number): number {
+ return budget > 0 ? cost / budget : 1;
+}
+
+/** The `budget:` line of a trigger block: `12.40 / 30.00 USD (41%)`, or the spend alone when unbounded. */
+export function budgetLine(org: LoadedOrg, spend: OrgSpend, agentId: string): string {
+ const cost = spend.cumulative.get(agentId) ?? 0;
+ const budget = org.byId.get(agentId)?.budget;
+ if (budget === undefined) return `${money(cost)} USD / unbounded`;
+ return `${money(cost)} / ${money(budget)} USD (${Math.round(budgetRatio(cost, budget) * 100)}%)`;
+}
+
+/** Employees whose own budget mark, or any ancestor's, is paused for the period. */
+export function pausedEmployees(deps: OrgDeps, org: LoadedOrg, period: string): Set<string> {
+ const pausedSelf = new Set(
+ deps.cache
+ .listBudgetStates(org.projectId, org.orgId, period)
+ .filter((s) => s.pausedAt !== null)
+ .map((s) => s.agentId),
+ );
+ const out = new Set<string>();
+ for (const e of org.chart.employees) {
+ if (pausedSelf.has(e.agentId)) {
+ out.add(e.agentId);
+ for (const sub of subordinatesOf(org.chart, e.agentId)) out.add(sub);
+ }
+ }
+ return out;
+}
diff --git a/packages/server/src/runtime/organization/deps.ts b/packages/server/src/runtime/organization/deps.ts
new file mode 100644
index 00000000..7ca52b23
--- /dev/null
+++ b/packages/server/src/runtime/organization/deps.ts
@@ -0,0 +1,153 @@
+/**
+ * What the organization runtime needs from the rest of the server, as narrow interfaces:
+ * the session manager (run state and task start), session creation, the Agent lifecycle,
+ * usage pricing, the file store and the caches. app.ts binds the real services; tests bind
+ * doubles — the same shape the schedule scheduler uses.
+ */
+import type { OmniMessage } from "@prismshadow/penguin-core";
+import { Interface } from "@prismshadow/penguin-core/kernel";
+import type { ApprovalMode, ServerEvent, SessionStatus } from "../../api/types.js";
+import type { OrgCache } from "../../mechanisms/organization.js";
+import type { Members, ProjectConfigStore, Projects } from "../../mechanisms/projects.js";
+import type { SessionIndex } from "../../mechanisms/sessions.js";
+import type { OrgStore } from "../../organization/store.js";
+import type { UtilityCompletion } from "../../services/project-config-service.js";
+import type { ErrorSink } from "../error-recorder.js";
+
+/** The session manager as the runtime sees it: is a session busy, and start a Task on it. */
+export interface OrgTaskRunner {
+ statusOf(sessionId: string): SessionStatus;
+ startTask(
+ sessionId: string,
+ input: OmniMessage[],
+ opts?: { queueIfBusy?: boolean },
+ ): Promise<{ sessionId: string; queued?: boolean }>;
+}
+
+/**
+ * What company mode needs of the session runtime: the task seam above, plus the runtime
+ * eviction a plugin update performs (the same one the plugins route does). Declared here,
+ * at the consumer, and satisfied by the wider session manager.
+ */
+export interface OrgRunsShape extends OrgTaskRunner {
+ invalidateAgentRuntimes(projectId: string, agentId: string): void;
+}
+
+/** Session creation (desk and ticket sessions are ordinary sessions of the employee's Agent). */
+export interface OrgSessionCreator {
+ createSession(args: {
+ projectId: string;
+ agentId: string;
+ workspace?: string;
+ modelId?: string;
+ provider?: string;
+ approvalMode?: ApprovalMode;
+ /**
+ * Always "org" here — the runtime opens no other kind of session, and the marker is
+ * what keeps a desk or ticket session out of development mode's list once the
+ * organization is gone. Required rather than optional so a new call site cannot
+ * forget it.
+ */
+ client: "org";
+ }): Promise<{ sessionId: string; workspace: string }>;
+}
+
+/**
+ * The library plugins an employee is hired with, and the ones every reconcile pass keeps at
+ * the library's version. It lives here rather than beside the hiring code because both the
+ * hire and the pass reach it through the `agents` gateway below, and a module of interfaces
+ * can be imported from anywhere in the runtime without a cycle.
+ */
+export const DEFAULT_EMPLOYEE_PLUGINS = ["agent-company", "agent-development"] as const;
+
+/**
+ * The plugins a hire is created with: the pair above, then whatever the caller asked for on
+ * top, in the order given and without repeats. The extra names add rather than replace —
+ * an employee hired without `agent-company` has no `company-employee` skill to follow, which
+ * is exactly what the brief written at hire time tells it to do, and the pass that keeps
+ * plugins current deliberately installs nothing an employee does not already carry, so
+ * nothing would ever repair it.
+ */
+export function employeePlugins(extra: readonly string[] | undefined): string[] {
+ const out: string[] = [...DEFAULT_EMPLOYEE_PLUGINS];
+ for (const name of extra ?? []) if (!out.includes(name)) out.push(name);
+ return out;
+}
+
+/** The Agent lifecycle pieces hiring, creation and keeping an employee's plugins current need. */
+export interface OrgAgentGateway {
+ exists(projectId: string, agentId: string): Promise<boolean>;
+ create(
+ projectId: string,
+ agentId: string,
+ name: string | undefined,
+ description: string | undefined,
+ plugins: readonly string[],
+ ): Promise<void>;
+ /** The Agent's display name (system_config.yaml), falling back to the id. */
+ displayName(projectId: string, agentId: string): Promise<string>;
+ /** Replaces the Agent's AGENTS.md (the employee brief written at hire time). */
+ writeAgentsMd(projectId: string, agentId: string, content: string): Promise<void>;
+ /**
+ * Where one library plugin stands on this Agent: the version it carries (null when it
+ * carries none of the plugin) against the version the library offers (null when the library
+ * has no such plugin). What the reconcile pass compares to decide whether an employee's
+ * company plugins have fallen behind.
+ */
+ pluginVersion(
+ projectId: string,
+ agentId: string,
+ plugin: string,
+ ): Promise<{ installed: string | null; library: string | null }>;
+ /** Reinstalls one library plugin over the Agent's copy — the whole-plugin update the Agents page performs. */
+ updatePlugin(projectId: string, agentId: string, plugin: string): Promise<void>;
+}
+
+/** Cost attribution by session (UsageService.costBySession / dailyCostForSessions). */
+export interface OrgUsageGateway {
+ costBySession(
+ projectId: string,
+ sessionIds: readonly string[],
+ fromTs: string,
+ toTs: string,
+ ): Promise<{ bySession: Map<string, number>; unpriced: boolean }>;
+ dailyCostForSessions(
+ projectId: string,
+ sessionIds: readonly string[],
+ fromTs: string,
+ toTs: string,
+ ): Promise<Array<{ date: string; cost: number }>>;
+}
+
+export interface OrgDeps {
+ root: string;
+ store: OrgStore;
+ cache: OrgCache;
+ projects: Projects;
+ members: Members;
+ sessions: SessionIndex;
+ runner: OrgTaskRunner;
+ sessionCreator: OrgSessionCreator;
+ agents: OrgAgentGateway;
+ projectConfig: ProjectConfigStore;
+ /**
+ * One short completion on the Project's default model, for the utility asks that are not a
+ * Session's work — today the semantic id a display name is translated into. A failure comes
+ * back as `{ ok: false }` with the reason rather than as a bare "no answer", so the caller
+ * can both record it and tell the user which way the ask fell through; every caller still
+ * carries an answer that works without the model. Optional so a test binds a double or nothing.
+ */
+ completeOnce?: (projectId: string, prompt: string) => Promise<UtilityCompletion>;
+ usage: OrgUsageGateway;
+ errors: ErrorSink;
+ /** Company-mode notifications go to the Project's owner and members (app.ts binds the user channels). */
+ notifyProject: (projectId: string, event: ServerEvent) => void;
+ /** The admin master switch, read per pass so a change applies without a restart. */
+ companyModeEnabled: () => boolean;
+ now?: () => number;
+ log?: (line: string) => void;
+}
+
+/** What company mode needs of the session runtime — declared at the consumer (Go style). */
+export abstract class OrgRuns extends Interface<OrgRunsShape>() {}
+export abstract class OrgSessions extends Interface<OrgSessionCreator>() {}
diff --git a/packages/server/src/runtime/organization/digest.ts b/packages/server/src/runtime/organization/digest.ts
new file mode 100644
index 00000000..18f60d61
--- /dev/null
+++ b/packages/server/src/runtime/organization/digest.ts
@@ -0,0 +1,89 @@
+/**
+ * The "Since your last sweep" section of a calendar event's body. Ticket changes never wake
+ * a desk: an owner assigned, a ticket blocked, a blocker closed, done, rejected — each is
+ * queued for the employee and listed here when its next calendar event fires, which is where
+ * it decides what to do about each. Pure: the rows as they were queued and the tickets as
+ * they stand now go in, one Markdown section comes out.
+ */
+import type { OrgTicketChange } from "../../api/types.js";
+import type { OrgDeskNoticeRow } from "../../db/repos/organizations.js";
+import type { TicketDoc } from "../../organization/files.js";
+
+/** A ticket as the digest reads it: the listing the reconcile pass already holds. */
+export interface DigestTicket {
+ ticketId: string;
+ doc: TicketDoc;
+}
+
+/** What each change is called, before the ticket's own reason or blocker is added. */
+const CHANGE_LABEL: Record<OrgTicketChange, string> = {
+ assigned: "assigned to you",
+ blocked: "blocked",
+ blocker_closed: "blocker closed",
+ done: "done",
+ rejected: "rejected",
+};
+
+/** The title of a ticket whose file is gone by the time the sweep fires. */
+const REMOVED_TITLE = "ticket removed";
+
+const MAX_REASON = 120;
+
+/** The first line of a reason, short enough to sit inside a list item. */
+function shortReason(text: string | undefined): string | null {
+ const line = (text ?? "")
+ .split("\n")
+ .map((l) => l.trim())
+ .find((l) => l !== "");
+ if (line === undefined) return null;
+ return line.length > MAX_REASON ? `${line.slice(0, MAX_REASON - 1)}…` : line;
+}
+
+/** The change, plus what the ticket itself says about it: the reason, the blocker, the next step. */
+function changeText(row: OrgDeskNoticeRow, doc: TicketDoc | null): string {
+ const label = CHANGE_LABEL[row.change];
+ if (doc === null) return label;
+ const blockedBy = doc.blockedBy !== undefined && doc.blockedBy !== "" ? doc.blockedBy : null;
+ switch (row.change) {
+ case "blocked": {
+ const reason = shortReason(doc.blocked);
+ const by = blockedBy === null ? "" : ` (by ${blockedBy})`;
+ return `${label}${reason === null ? "" : ` — "${reason}"`}${by}`;
+ }
+ case "blocker_closed": {
+ const which = blockedBy === null ? "" : ` (${blockedBy})`;
+ return `${label}${which} — verify, then \`penguin org ticket unblock ${row.ticketId}\``;
+ }
+ case "rejected": {
+ // A rejection's reason is appended to the ticket's `## Result` by the move that made it.
+ const reason = shortReason(doc.result);
+ return reason === null ? label : `${label} — "${reason}"`;
+ }
+ default:
+ return label;
+ }
+}
+
+/**
+ * The queued changes as the section a calendar event's body ends with, or `""` when nothing
+ * is queued. One line per row in queue order, each naming the ticket, its current title and
+ * what happened to it.
+ */
+export function deskDigest(
+ rows: readonly OrgDeskNoticeRow[],
+ tickets: readonly DigestTicket[],
+): string {
+ if (rows.length === 0) return "";
+ const byId = new Map(tickets.map((t) => [t.ticketId, t.doc]));
+ const lines = rows.map((row) => {
+ const doc = byId.get(row.ticketId) ?? null;
+ const title = doc === null ? REMOVED_TITLE : doc.title;
+ return `- ${row.ticketId} (${title}): ${changeText(row, doc)}`;
+ });
+ return [
+ "## Since your last sweep",
+ ...lines,
+ "",
+ 'Decide on each: start a ticket session (`penguin org ticket start <id> -m "…"`), verify and unblock, or leave it — do not do the work at your desk.',
+ ].join("\n");
+}
diff --git a/packages/server/src/runtime/organization/locks.ts b/packages/server/src/runtime/organization/locks.ts
new file mode 100644
index 00000000..1b60ad92
--- /dev/null
+++ b/packages/server/src/runtime/organization/locks.ts
@@ -0,0 +1,26 @@
+/**
+ * One writer per organization at a time. The scheduler's pass and a route's write both
+ * read files, decide, and write files and caches; interleaving them could deliver a channel
+ * mention twice or lose a ledger update. A promise chain per key serializes them.
+ */
+export class KeyedLocks {
+ private readonly tails = new Map<string, Promise<unknown>>();
+
+ async run<T>(key: string, fn: () => Promise<T>): Promise<T> {
+ const prev = this.tails.get(key) ?? Promise.resolve();
+ const next = prev.then(fn, fn);
+ // The tail is the settled form of `next`: a rejection must not break the chain for the
+ // next waiter. Keep that exact promise so the cleanup below can recognise its own tail.
+ const tail = next.catch(() => undefined);
+ this.tails.set(key, tail);
+ try {
+ return await next;
+ } finally {
+ if (this.tails.get(key) === tail) this.tails.delete(key);
+ }
+ }
+}
+
+export function orgLockKey(projectId: string, orgId: string): string {
+ return `${projectId}\0${orgId}`;
+}
diff --git a/packages/server/src/runtime/organization/model.ts b/packages/server/src/runtime/organization/model.ts
new file mode 100644
index 00000000..2a590076
--- /dev/null
+++ b/packages/server/src/runtime/organization/model.ts
@@ -0,0 +1,99 @@
+/**
+ * An organization as one pass sees it: the three root files read and validated together.
+ * A broken config or chart does not hide the organization — it is listed with `invalid`
+ * set and every automatic trigger is held until the file is fixed (the same rule as an
+ * invalid schedule file: report, skip, recover on edit).
+ */
+import type { Desks, OrgChart, OrgConfig, OrgEmployee } from "../../organization/files.js";
+import { ORG_CONFIG_DEFAULTS, ancestorsOf } from "../../organization/files.js";
+import { ceoAgentId, workspaceDir } from "../../organization/paths.js";
+import type { OrgDeps } from "./deps.js";
+
+export interface LoadedOrg {
+ projectId: string;
+ orgId: string;
+ dir: string;
+ config: OrgConfig;
+ chart: OrgChart;
+ desks: Desks;
+ byId: Map<string, OrgEmployee>;
+ /** Set when a root file fails validation; the organization is then read-only for the scheduler. */
+ invalid?: string;
+}
+
+/** Reads config, chart and ledger; null when the directory is not an organization. */
+export async function loadOrg(
+ deps: OrgDeps,
+ projectId: string,
+ orgId: string,
+): Promise<LoadedOrg | null> {
+ const dir = deps.store.dir(projectId, orgId);
+ const configFile = await deps.store.readConfig(dir);
+ if (configFile === null) return null;
+ const problems: string[] = [];
+ let config: OrgConfig;
+ if (configFile.parsed.ok) {
+ config = configFile.parsed.value;
+ } else {
+ problems.push(`org_config.toml: ${configFile.parsed.error}`);
+ config = {
+ name: orgId,
+ mission: "",
+ status: "paused",
+ timezone: "UTC",
+ approvalMode: ORG_CONFIG_DEFAULTS.approvalMode,
+ mentionChainLimit: ORG_CONFIG_DEFAULTS.mentionChainLimit,
+ budgetWarnRatio: ORG_CONFIG_DEFAULTS.budgetWarnRatio,
+ budgetPauseRatio: ORG_CONFIG_DEFAULTS.budgetPauseRatio,
+ createdBy: "",
+ };
+ }
+ const chartFile = await deps.store.readChart(dir, orgId);
+ let chart: OrgChart;
+ if (chartFile === null) {
+ problems.push("org_chart.yaml is missing");
+ chart = { employees: [] };
+ } else if (chartFile.parsed.ok) {
+ chart = chartFile.parsed.value;
+ } else {
+ problems.push(`org_chart.yaml: ${chartFile.parsed.error}`);
+ chart = { employees: [] };
+ }
+ const desksFile = await deps.store.readDesks(dir);
+ let desks: Desks = {};
+ if (desksFile.parsed.ok) desks = desksFile.parsed.value;
+ else problems.push(`desks.toml: ${desksFile.parsed.error}`);
+ return {
+ projectId,
+ orgId,
+ dir,
+ config,
+ chart,
+ desks,
+ byId: new Map(chart.employees.map((e) => [e.agentId, e])),
+ ...(problems.length > 0 ? { invalid: problems.join("; ") } : {}),
+ };
+}
+
+/** The `employee:` line of a trigger block: id, title and reporting line for orientation. */
+export function employeeLine(org: LoadedOrg, agentId: string): string {
+ const e = org.byId.get(agentId);
+ if (!e) return agentId;
+ return e.reportsTo === null
+ ? `${agentId} (${e.title})`
+ : `${agentId} (${e.title}, reports to ${e.reportsTo})`;
+}
+
+/** The employee and everyone above it, for "any ancestor paused" checks. */
+export function lineOf(org: LoadedOrg, agentId: string): string[] {
+ return [agentId, ...ancestorsOf(org.chart, agentId)];
+}
+
+export function isCeo(org: LoadedOrg, agentId: string): boolean {
+ return agentId === ceoAgentId(org.orgId);
+}
+
+/** The shared workspace root: the directory named in the config, else the organization's own `workspace/`. */
+export function sharedWorkspace(org: LoadedOrg): string {
+ return org.config.workspace ?? workspaceDir(org.dir);
+}
diff --git a/packages/server/src/runtime/organization/notices.ts b/packages/server/src/runtime/organization/notices.ts
new file mode 100644
index 00000000..cbcf1cc6
--- /dev/null
+++ b/packages/server/src/runtime/organization/notices.ts
@@ -0,0 +1,112 @@
+/**
+ * The `system` lines an organization writes, built once as a sentence and a structure
+ * together. `text` is the English line the file keeps and the CLI falls back to; `notice`
+ * is the same fact as a kind plus string parameters, so a client renders it in the reader's
+ * language and with display names. Building both here is what stops the two from drifting:
+ * a kind that changes its parameters changes its sentence in the same function.
+ *
+ * A channel holds what people and employees say to each other, plus the two facts that change
+ * who is in the room — an employee joining or leaving, a channel's membership and archive
+ * state — and the budget alerts. Ticket changes write no line here: the board is read from
+ * the board, and a board that narrates itself buries the conversation.
+ */
+import type { OrgChannelMessage, OrgChannelNotice } from "../../api/types.js";
+
+/** One system line: the English sentence and its structured twin. */
+export interface SystemLine {
+ text: string;
+ notice: OrgChannelNotice;
+}
+
+/** A line as the message body the channel writer takes; a `system` line mentions nobody unless the caller says so. */
+export function systemMessage(line: SystemLine): Omit<OrgChannelMessage, "id" | "time"> {
+ return { sender: "system", hop: 0, text: line.text, mentions: [], notice: line.notice };
+}
+
+export function employeeJoined(agent: string, title: string, reportsTo: string): SystemLine {
+ return {
+ text: `${agent} joined as ${title}, reporting to ${reportsTo}.`,
+ notice: { kind: "employee_joined", params: { agent, title, reportsTo } },
+ };
+}
+
+export function employeeLeft(agent: string, reportsTo: string): SystemLine {
+ return {
+ text: `${agent} left the organization; reports now go to ${reportsTo}.`,
+ notice: { kind: "employee_left", params: { agent, reportsTo } },
+ };
+}
+
+export function channelCreated(by: string): SystemLine {
+ return {
+ text: `${by} created the channel.`,
+ notice: { kind: "channel_created", params: { by } },
+ };
+}
+
+export function channelArchiveChanged(by: string, archived: boolean): SystemLine {
+ return {
+ text: `${by} ${archived ? "archived" : "unarchived"} the channel.`,
+ notice: { kind: archived ? "channel_archived" : "channel_unarchived", params: { by } },
+ };
+}
+
+/** A member added: by itself (a person joining) or by another member. */
+export function channelMemberAdded(by: string, principal: string): SystemLine {
+ if (by === principal) {
+ return {
+ text: `${principal} joined the channel.`,
+ notice: { kind: "channel_joined", params: { principal } },
+ };
+ }
+ return {
+ text: `${by} invited ${principal} to the channel.`,
+ notice: { kind: "channel_invited", params: { by, principal } },
+ };
+}
+
+/** A member removed: itself (leaving) or by someone else. */
+export function channelMemberRemoved(by: string, principal: string): SystemLine {
+ if (by === principal) {
+ return {
+ text: `${principal} left the channel.`,
+ notice: { kind: "channel_left", params: { principal } },
+ };
+ }
+ return {
+ text: `${by} removed ${principal} from the channel.`,
+ notice: { kind: "channel_removed", params: { by, principal } },
+ };
+}
+
+export interface BudgetFacts {
+ agent: string;
+ period: string;
+ percent: number;
+ cost: number;
+ budget: number;
+}
+
+const money = (n: number): string => n.toFixed(2);
+
+const budgetParams = (f: BudgetFacts): Record<string, string> => ({
+ agent: f.agent,
+ period: f.period,
+ percent: String(f.percent),
+ cost: money(f.cost),
+ budget: money(f.budget),
+});
+
+export function budgetWarned(f: BudgetFacts): SystemLine {
+ return {
+ text: `Budget warning: ${f.agent} has used ${f.percent}% of its ${f.period} budget (${money(f.cost)} / ${money(f.budget)} USD).`,
+ notice: { kind: "budget_warned", params: budgetParams(f) },
+ };
+}
+
+export function budgetPaused(f: BudgetFacts): SystemLine {
+ return {
+ text: `Budget pause: ${f.agent} reached ${f.percent}% of its ${f.period} budget (${money(f.cost)} / ${money(f.budget)} USD). Its calendar and its subordinates' are paused until the next month or a raised budget; mentions and direct conversations still work.`,
+ notice: { kind: "budget_paused", params: budgetParams(f) },
+ };
+}
diff --git a/packages/server/src/runtime/organization/reconcile.ts b/packages/server/src/runtime/organization/reconcile.ts
new file mode 100644
index 00000000..4cff61fa
--- /dev/null
+++ b/packages/server/src/runtime/organization/reconcile.ts
@@ -0,0 +1,743 @@
+/**
+ * One reconcile pass over an organization — the same pass whether the scheduler's timer
+ * or a route's write asks for it. Files in, decisions out: caches are projected from the
+ * ledger and the tickets, missing desks are opened and desks renewed where the chart moved
+ * them, due calendar events fire (carrying the ticket changes queued since the employee's
+ * last sweep), ticket changes are recorded and queued, new channel mentions are delivered,
+ * budgets are checked, and every employee's company plugins are brought up to the library's
+ * version.
+ * Missed work is never backfilled: a slot that passed while the server was down, the
+ * organization paused or the switch off is consumed and skipped, like a schedule.
+ */
+import { createHash } from "node:crypto";
+import { comparePluginVersions } from "@prismshadow/penguin-core";
+import type { OrgCalendarOutcome, OrgChannelMessage, OrgTicketChange } from "../../api/types.js";
+import type { ChannelConfig, TicketDoc } from "../../organization/files.js";
+import { parseChannelMessageLine, serializeChannelMessageLine } from "../../organization/files.js";
+import { agentPrincipal, parsePrincipal, principalAgentId } from "../../organization/principal.js";
+import { DEFAULT_CHANNEL_ID } from "../../organization/paths.js";
+import { zonedDate } from "../../organization/zoned.js";
+import { latestSlotAt, slotInWindow } from "../schedule-file.js";
+import { budgetLine, computeSpend, pausedEmployees } from "./budget.js";
+import type { OrgSpend, TicketForSpend } from "./budget.js";
+import { DEFAULT_EMPLOYEE_PLUGINS } from "./deps.js";
+import type { OrgDeps } from "./deps.js";
+import { deskDigest } from "./digest.js";
+import { loadOrg, sharedWorkspace } from "./model.js";
+import type { LoadedOrg } from "./model.js";
+import { budgetPaused, budgetWarned, systemMessage } from "./notices.js";
+import type { SystemLine } from "./notices.js";
+import { dispatchToDesk, ensureDesk, syncDeskCache } from "./triggers.js";
+
+export interface LoadedTicket extends TicketForSpend {
+ column: TicketDoc["status"];
+ relPath: string;
+}
+
+export interface TicketListing {
+ tickets: LoadedTicket[];
+ /** Files that could not be parsed, or ids that appear in two columns. */
+ invalid: Array<{ path: string; error: string }>;
+}
+
+const nowOf = (deps: OrgDeps): number => deps.now?.() ?? Date.now();
+
+function recordError(
+ deps: OrgDeps,
+ org: LoadedOrg,
+ code: string,
+ message: string,
+ agentId?: string,
+): void {
+ deps.errors.record({
+ source: "organization",
+ err: new Error(message),
+ code,
+ ctx: { projectId: org.projectId, ...(agentId !== undefined ? { agentId } : {}) },
+ });
+}
+
+/** Every ticket file, parsed; an unparsable file or a duplicated id is reported and left out. */
+export async function listTickets(deps: OrgDeps, org: LoadedOrg): Promise<TicketListing> {
+ const files = await deps.store.listTickets(org.dir);
+ const seen = new Map<string, number>();
+ for (const f of files) seen.set(f.ticketId, (seen.get(f.ticketId) ?? 0) + 1);
+ const tickets: LoadedTicket[] = [];
+ const invalid: Array<{ path: string; error: string }> = [];
+ for (const f of files) {
+ if ((seen.get(f.ticketId) ?? 0) > 1) {
+ invalid.push({
+ path: f.relPath,
+ error: `ticket id ${f.ticketId} appears in more than one column`,
+ });
+ continue;
+ }
+ if (!f.parsed.ok) {
+ invalid.push({ path: f.relPath, error: f.parsed.error });
+ continue;
+ }
+ if (f.parsed.value.status !== f.column) {
+ invalid.push({
+ path: f.relPath,
+ error: `Status is ${f.parsed.value.status} but the file sits in ${f.column}`,
+ });
+ continue;
+ }
+ tickets.push({
+ ticketId: f.ticketId,
+ column: f.column,
+ relPath: f.relPath,
+ doc: f.parsed.value,
+ });
+ }
+ for (const bad of invalid) {
+ recordError(deps, org, "org_ticket_invalid", `Invalid ticket ${bad.path}: ${bad.error}`);
+ }
+ return { tickets, invalid };
+}
+
+/**
+ * Projects the ledger and the tickets' `Sessions` headers into the two session caches, and
+ * stamps `client = "org"` on every session row those files name. The caches are rebuilt from
+ * the files on every pass and vanish with the organization; the stamp is written once per row
+ * and stays, which is what keeps a desk or ticket session out of development mode's list
+ * after the organization is deleted or company mode is switched off. It also backfills the
+ * sessions of organizations that already existed before the marker did — one pass marks them
+ * all. Sessions of organizations deleted before then are never seen again and stay unmarked.
+ */
+export function syncCaches(deps: OrgDeps, org: LoadedOrg, tickets: readonly LoadedTicket[]): void {
+ syncDeskCache(deps, org);
+ // The stamp is durable, unlike the caches beside it, so a hand-edited ledger naming a
+ // session of another Project must not mark it as this organization's.
+ const owned: string[] = [];
+ const own = (sessionId: string): void => {
+ if (deps.sessions.findById(sessionId)?.projectId === org.projectId) owned.push(sessionId);
+ };
+ for (const desk of Object.values(org.desks)) {
+ own(desk.sessionId);
+ for (const prev of desk.previous) own(prev);
+ }
+ const rows: Array<{ ticketId: string; sessionId: string; agentId: string }> = [];
+ for (const t of tickets) {
+ for (const sessionId of t.doc.sessions) {
+ const row = deps.sessions.findById(sessionId);
+ if (row && row.projectId === org.projectId) {
+ rows.push({ ticketId: t.ticketId, sessionId, agentId: row.agentId });
+ owned.push(sessionId);
+ }
+ }
+ }
+ deps.cache.syncTicketSessions(org.projectId, org.orgId, rows);
+ deps.sessions.markOrgClient(owned);
+}
+
+/**
+ * An employee's company plugins, brought up to the library's version.
+ *
+ * An Agent's plugins are written once, at creation, and nothing rewrites them afterwards —
+ * the Agents page offers a manual per-Agent update, which nobody is there to click in an
+ * organization that runs unattended for weeks. So every pass compares each employee's
+ * installed {@link DEFAULT_EMPLOYEE_PLUGINS} against the library's version and reinstalls
+ * the ones that have fallen behind (the same whole-plugin update the Agents page performs),
+ * which is how a skill added to `agent-company` after a hire reaches the employees already
+ * at work.
+ *
+ * Cheap when nothing moved: the versions match and no file is written. An employee that does
+ * not carry a plugin at all is left alone — the set an Agent was hired with is the CEO's
+ * choice, not something a pass grows. A failed update is recorded and never stops the pass:
+ * the next one tries again.
+ */
+async function reconcileEmployeePlugins(deps: OrgDeps, org: LoadedOrg): Promise<void> {
+ for (const employee of org.chart.employees) {
+ for (const plugin of DEFAULT_EMPLOYEE_PLUGINS) {
+ try {
+ const { installed, library } = await deps.agents.pluginVersion(
+ org.projectId,
+ employee.agentId,
+ plugin,
+ );
+ if (installed === null || library === null) continue;
+ if (comparePluginVersions(library, installed) <= 0) continue;
+ await deps.agents.updatePlugin(org.projectId, employee.agentId, plugin);
+ deps.log?.(
+ `org: updated plugin ${plugin} on ${employee.agentId} (${installed} -> ${library})`,
+ );
+ } catch (err) {
+ recordError(
+ deps,
+ org,
+ "org_plugin_update_failed",
+ `Could not update plugin ${plugin} on ${employee.agentId}: ${err instanceof Error ? err.message : String(err)}`,
+ employee.agentId,
+ );
+ }
+ }
+ }
+}
+
+/**
+ * Every employee of the chart has a desk session, and one that went missing comes back.
+ *
+ * A hire opens the desk itself, so this step is what covers everything hiring does not: an
+ * employee added to `org_chart.yaml` by hand, one hired before desks were opened at hire
+ * time, and a desk whose session row is gone — deleted by hand, or with the employee's Agent.
+ * Until it runs, every surface that addresses a desk by Session id points at a Session the
+ * server cannot find: the sidebar's desk row still draws its menu, and binding it to a
+ * messaging bot answers "Session does not exist".
+ *
+ * Opening a desk starts no run, so a paused organization and a switched-off master switch
+ * provision desks exactly like an active one. Idempotent: an employee whose desk is there is
+ * skipped without a write. A failure is recorded per employee and never stops the pass — the
+ * next one tries again.
+ */
+async function provisionMissingDesks(deps: OrgDeps, org: LoadedOrg): Promise<void> {
+ for (const employee of org.chart.employees) {
+ const desk = org.desks[employee.agentId];
+ if (desk !== undefined && deps.sessions.findById(desk.sessionId) !== null) continue;
+ const r = await ensureDesk(deps, org, employee.agentId);
+ if (!r.ok) {
+ recordError(deps, org, "org_desk_unavailable", r.error, employee.agentId);
+ continue;
+ }
+ if (r.desk.created) {
+ deps.log?.(`org: opened a desk session for ${employee.agentId} (${r.desk.sessionId})`);
+ }
+ }
+}
+
+/** The CEO moved an employee's workspace: a desk whose session sits elsewhere is renewed. */
+async function renewMovedDesks(deps: OrgDeps, org: LoadedOrg): Promise<void> {
+ for (const [agentId, desk] of Object.entries(org.desks)) {
+ const employee = org.byId.get(agentId);
+ if (!employee) continue;
+ const resolved = await deps.store.resolveWorkspace(sharedWorkspace(org), employee.workspace);
+ if (resolved === null || resolved === desk.workspace) continue;
+ const r = await ensureDesk(deps, org, agentId);
+ if (!r.ok) recordError(deps, org, "org_desk_unavailable", r.error, agentId);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Calendar
+// ---------------------------------------------------------------------------
+
+async function reconcileCalendar(
+ deps: OrgDeps,
+ org: LoadedOrg,
+ tickets: readonly LoadedTicket[],
+ spend: OrgSpend,
+ paused: Set<string>,
+ triggers: boolean,
+): Promise<void> {
+ const files = await deps.store.listCalendar(org.dir);
+ const present: Array<{ agentId: string; name: string }> = [];
+ const nowMs = nowOf(deps);
+ for (const file of files) {
+ present.push({ agentId: file.agentId, name: file.name });
+ if (!file.parsed.ok) {
+ recordError(
+ deps,
+ org,
+ "org_calendar_invalid",
+ `Invalid calendar event ${file.agentId}/${file.name}.toml: ${file.parsed.error}`,
+ file.agentId,
+ );
+ continue;
+ }
+ if (!org.byId.has(file.agentId)) {
+ recordError(
+ deps,
+ org,
+ "org_calendar_invalid",
+ `Calendar event ${file.agentId}/${file.name}.toml belongs to no employee`,
+ file.agentId,
+ );
+ continue;
+ }
+ const def = file.parsed.value;
+ const key = {
+ projectId: org.projectId,
+ orgId: org.orgId,
+ agentId: file.agentId,
+ name: file.name,
+ };
+ const { row, fresh } = deps.cache.registerCalendar({
+ ...key,
+ startAtMs: def.startAtMs,
+ defHash: createHash("sha1").update(file.raw).digest("hex"),
+ });
+ let state = row;
+ if (fresh) {
+ // No backfill: a due time already in the past at registration is consumed, not fired.
+ const slot = latestSlotAt(def, nowMs);
+ if (slot !== null) {
+ if (def.periodMs === undefined)
+ deps.cache.markCalendarMissed(key.projectId, key.orgId, key.agentId, key.name);
+ else deps.cache.markCalendarSlot(key.projectId, key.orgId, key.agentId, key.name, slot);
+ state = deps.cache.findCalendar(key.projectId, key.orgId, key.agentId, key.name) ?? row;
+ }
+ }
+ if (!def.enabled || state.invalidReason !== null) continue;
+ if (def.periodMs === undefined && (state.firedOnce || state.missed)) continue;
+ const slot = latestSlotAt(def, nowMs);
+ if (slot === null || !slotInWindow(def, slot)) continue;
+ if (state.lastSlotMs !== null && slot <= state.lastSlotMs) continue;
+ // Consume the slot first: whatever happens next, it is never retried (the twin of no-backfill).
+ deps.cache.markCalendarSlot(key.projectId, key.orgId, key.agentId, key.name, slot);
+ const mark = (outcome: OrgCalendarOutcome): void =>
+ deps.cache.markCalendarOutcome(key.projectId, key.orgId, key.agentId, key.name, outcome);
+ if (!triggers || org.config.status === "paused" || paused.has(file.agentId)) {
+ mark("paused");
+ continue;
+ }
+ const firedAt = new Date(nowMs).toISOString();
+ // The sweep is where ticket changes are delivered: taken here, at the last moment before
+ // the run that carries them, so a slot held for a paused employee keeps its queue.
+ const notices = deps.cache.takeDeskNotices(org.projectId, org.orgId, file.agentId);
+ const digest = deskDigest(notices, tickets);
+ const outcome = await dispatchToDesk(
+ deps,
+ org,
+ file.agentId,
+ { kind: "event", event: file.name, firedAt },
+ digest === "" ? def.prompt : `${def.prompt}\n\n${digest}`,
+ { hop: 0, budget: budgetLine(org, spend, file.agentId) },
+ );
+ if (outcome === "skipped") {
+ // The run never started (no desk, or the Task could not be queued): the changes go
+ // back on the queue in their order, so the slot that does fire still carries them.
+ for (const row of notices) deps.cache.queueDeskNotice(row);
+ mark("error");
+ continue;
+ }
+ deps.cache.markCalendarFired(
+ key.projectId,
+ key.orgId,
+ key.agentId,
+ key.name,
+ firedAt,
+ def.periodMs === undefined,
+ );
+ mark(outcome === "queued" ? "queued" : "fired");
+ }
+ deps.cache.deleteMissingCalendar(org.projectId, org.orgId, present);
+}
+
+// ---------------------------------------------------------------------------
+// Tickets
+// ---------------------------------------------------------------------------
+
+/**
+ * One ticket change, queued for the employees it concerns. A change never starts a work run
+ * and it never writes into a channel: the employees' half is a row per (employee, ticket,
+ * change) that the employee's next calendar sweep carries under "Since your last sweep" —
+ * queued whether or not the organization is paused, since delivery waits for that sweep
+ * anyway. The people's half is the `org_ticket` event and the overview's inbox, both read
+ * from the board itself; a channel is for what people and employees say to each other, and a
+ * board that narrates itself into the all-hands channel buries that.
+ */
+function notifyTicket(
+ deps: OrgDeps,
+ org: LoadedOrg,
+ t: LoadedTicket,
+ change: OrgTicketChange,
+ agentIds: Iterable<string>,
+): void {
+ const at = new Date(nowOf(deps)).toISOString();
+ for (const agentId of new Set(agentIds)) {
+ if (!org.byId.has(agentId)) continue;
+ deps.cache.queueDeskNotice({
+ projectId: org.projectId,
+ orgId: org.orgId,
+ agentId,
+ ticketId: t.ticketId,
+ change,
+ at,
+ });
+ }
+}
+
+async function reconcileTickets(
+ deps: OrgDeps,
+ org: LoadedOrg,
+ tickets: readonly LoadedTicket[],
+): Promise<void> {
+ for (const t of tickets) {
+ const cur = {
+ projectId: org.projectId,
+ orgId: org.orgId,
+ ticketId: t.ticketId,
+ status: t.doc.status,
+ owner: t.doc.owner,
+ blocked: t.doc.blocked ?? "",
+ blockedBy: t.doc.blockedBy ?? "",
+ };
+ const prev = deps.cache.findTicketState(org.projectId, org.orgId, t.ticketId);
+ if (!prev) {
+ // First sight: remember the ticket as it is, notify nothing (the same no-backfill rule as a calendar slot).
+ deps.cache.upsertTicketState(cur);
+ continue;
+ }
+ if (
+ prev.status === cur.status &&
+ prev.owner === cur.owner &&
+ prev.blocked === cur.blocked &&
+ prev.blockedBy === cur.blockedBy
+ ) {
+ continue;
+ }
+ deps.cache.upsertTicketState(cur);
+ const events: string[] = [];
+ if (prev.status !== cur.status) events.push(`status:${cur.status}`);
+ if (prev.owner !== cur.owner) events.push("owner");
+ if (prev.blocked !== cur.blocked) events.push(cur.blocked === "" ? "unblocked" : "blocked");
+ for (const change of events) {
+ deps.notifyProject(org.projectId, {
+ type: "org_ticket",
+ projectId: org.projectId,
+ orgId: org.orgId,
+ ticketId: t.ticketId,
+ change,
+ });
+ }
+ const ownerAgent = cur.owner === "" ? null : principalAgentId(cur.owner);
+ if (prev.owner !== cur.owner && ownerAgent !== null) {
+ notifyTicket(deps, org, t, "assigned", [ownerAgent]);
+ }
+ if (prev.blocked === "" && cur.blocked !== "") {
+ const agents: string[] = [];
+ const by = parsePrincipal(cur.blockedBy);
+ if (by?.kind === "agent") agents.push(by.id);
+ const manager = ownerAgent !== null ? (org.byId.get(ownerAgent)?.reportsTo ?? null) : null;
+ if (manager !== null) agents.push(manager);
+ notifyTicket(deps, org, t, "blocked", agents);
+ }
+ if (prev.status !== cur.status && (cur.status === "done" || cur.status === "rejected")) {
+ // An employee owner hears about its own ticket in its next sweep; a person reads the
+ // closure on the board and in the overview's inbox.
+ const agents: string[] = [];
+ for (const p of new Set([...t.doc.notify, t.doc.owner])) {
+ const parsed = parsePrincipal(p);
+ if (parsed?.kind === "agent") agents.push(parsed.id);
+ }
+ notifyTicket(deps, org, t, cur.status, agents);
+ // Tickets waiting on this one: their owners are told in their own next sweep, which is
+ // where they decide whether to verify and unblock.
+ for (const waiting of tickets) {
+ if (waiting.doc.blockedBy !== t.ticketId) continue;
+ const waitingOwner = principalAgentId(waiting.doc.owner);
+ if (waitingOwner !== null) {
+ notifyTicket(deps, org, waiting, "blocker_closed", [waitingOwner]);
+ }
+ }
+ }
+ }
+ deps.cache.deleteMissingTicketState(
+ org.projectId,
+ org.orgId,
+ tickets.map((t) => t.ticketId),
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Channels
+// ---------------------------------------------------------------------------
+
+const pad = (n: number): string => String(n).padStart(2, "0");
+
+let lastIdMs = 0;
+let idSeq = 0;
+
+/**
+ * `msg-<UTC time to the second>-<8 hex>`: the suffix packs the millisecond and a per-process
+ * sequence, so ids written by this server sort in write order even within one second — the
+ * read cursor and the unread count compare ids as strings.
+ */
+export function newMessageId(nowMs: number): string {
+ if (nowMs === lastIdMs) idSeq++;
+ else {
+ lastIdMs = nowMs;
+ idSeq = 0;
+ }
+ const d = new Date(nowMs);
+ const suffix = (((nowMs % 1000) << 12) | (idSeq & 0xfff)).toString(16).padStart(8, "0");
+ return `msg-${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}-${pad(d.getUTCHours())}-${pad(d.getUTCMinutes())}-${pad(d.getUTCSeconds())}-${suffix}`;
+}
+
+/** Appends a message to a channel's file for today (organization timezone) and returns it; delivery happens in the scan. */
+export async function appendChannelMessage(
+ deps: OrgDeps,
+ org: LoadedOrg,
+ channelId: string,
+ msg: Omit<OrgChannelMessage, "id" | "time">,
+): Promise<OrgChannelMessage> {
+ const nowMs = nowOf(deps);
+ const full: OrgChannelMessage = {
+ id: newMessageId(nowMs),
+ time: new Date(nowMs).toISOString(),
+ ...msg,
+ };
+ await deps.store.appendMessageLine(
+ org.dir,
+ channelId,
+ zonedDate(org.config.timezone, nowMs),
+ serializeChannelMessageLine(full),
+ );
+ return full;
+}
+
+/**
+ * A `system` line. Organization-wide notices (budgets, ticket notices addressed to people,
+ * hires and departures) go to the all-hands channel; a membership notice goes to the
+ * channel it concerns. The line arrives as its builder made it — the English sentence and
+ * the structured notice beside it — so a client can render it in the reader's language.
+ */
+export async function appendSystemMessage(
+ deps: OrgDeps,
+ org: LoadedOrg,
+ channelId: string,
+ line: SystemLine,
+ mentions: string[],
+ refs?: OrgChannelMessage["refs"],
+): Promise<OrgChannelMessage> {
+ return appendChannelMessage(deps, org, channelId, {
+ ...systemMessage(line),
+ mentions,
+ ...(refs !== undefined ? { refs } : {}),
+ });
+}
+
+/** The body of a mention trigger: the message, then up to 20 earlier messages of that channel's day as context. */
+function mentionBody(all: readonly OrgChannelMessage[], msg: OrgChannelMessage): string {
+ const idx = all.findIndex((m) => m.id === msg.id);
+ const earlier = (idx > 0 ? all.slice(Math.max(0, idx - 20), idx) : []).map(
+ (m) => `> ${m.time} ${m.sender}: ${m.text.replace(/\n/g, "\n> ")}`,
+ );
+ const head = `Message ${msg.id} from ${msg.sender}${msg.refs?.ticket !== undefined ? ` (ticket ${msg.refs.ticket})` : ""}:\n${msg.text}`;
+ return earlier.length === 0 ? head : `${head}\n\nEarlier today:\n${earlier.join("\n")}`;
+}
+
+/**
+ * The employees a channel delivers to: every employee for the all-hands channel, the
+ * `agent:` members for any other. An `agent:` member who has since left the organization is
+ * not one — the chart decides who exists.
+ */
+function channelAgents(org: LoadedOrg, channel: ChannelConfig): Set<string> {
+ if (channel.everyone === true) return new Set(org.chart.employees.map((e) => e.agentId));
+ const out = new Set<string>();
+ for (const m of channel.members ?? []) {
+ const id = principalAgentId(m);
+ if (id !== null && org.byId.has(id)) out.add(id);
+ }
+ return out;
+}
+
+/**
+ * Tail-scans each channel's recent day files, publishes every new message and delivers its
+ * mentions inside that channel's membership. Archived channels take no posts, so there is
+ * nothing new to find in them; an invalid `channel.toml` is reported and the channel skipped.
+ */
+export async function scanChannels(
+ deps: OrgDeps,
+ org: LoadedOrg,
+ spend: OrgSpend,
+ triggers: boolean,
+): Promise<void> {
+ for (const file of await deps.store.listChannels(org.dir)) {
+ if (!file.parsed.ok) {
+ recordError(
+ deps,
+ org,
+ "org_channel_invalid",
+ `Invalid channel ${file.channelId}/channel.toml: ${file.parsed.error}`,
+ );
+ continue;
+ }
+ const channel = file.parsed.value;
+ if (channel.archived) continue;
+ const members = channelAgents(org, channel);
+ const channelId = file.channelId;
+ const days = (await deps.store.listMessageDays(org.dir, channelId)).slice(0, 3);
+ for (const date of days.reverse()) {
+ const offset = deps.cache.channelOffset(org.projectId, org.orgId, channelId, date);
+ const { lines, nextOffset } = await deps.store.readMessagesFrom(
+ org.dir,
+ channelId,
+ date,
+ offset,
+ );
+ if (lines.length === 0) {
+ if (nextOffset !== offset)
+ deps.cache.setChannelOffset(org.projectId, org.orgId, channelId, date, nextOffset);
+ continue;
+ }
+ const all = (await deps.store.readMessageDay(org.dir, channelId, date)).messages;
+ for (const line of lines) {
+ const parsed = parseChannelMessageLine(line);
+ if (!parsed.ok) {
+ recordError(
+ deps,
+ org,
+ "org_channel_message_invalid",
+ `Invalid message line in ${channelId}/${date}.jsonl: ${parsed.error}`,
+ );
+ continue;
+ }
+ const msg = parsed.value;
+ deps.notifyProject(org.projectId, {
+ type: "org_channel",
+ projectId: org.projectId,
+ orgId: org.orgId,
+ channelId,
+ message: msg,
+ });
+ if (!triggers || org.config.status === "paused" || msg.sender === "system") continue;
+ if (msg.hop >= org.config.mentionChainLimit) continue;
+ const senderAgent = principalAgentId(msg.sender);
+ const targets = new Set<string>();
+ for (const m of msg.mentions) {
+ const p = parsePrincipal(m);
+ // A mention only reaches a member: the send path refuses the rest, and a
+ // hand-written line naming an outsider must not deliver either.
+ if (p?.kind === "agent") {
+ if (members.has(p.id)) targets.add(p.id);
+ } else if (p?.kind === "all") {
+ for (const id of members) targets.add(id);
+ }
+ }
+ if (senderAgent !== null) targets.delete(senderAgent);
+ for (const agentId of targets) {
+ if (!org.byId.has(agentId)) continue;
+ await dispatchToDesk(
+ deps,
+ org,
+ agentId,
+ {
+ kind: "mention",
+ message: `${msg.id} from ${msg.sender}`,
+ channel: channelId,
+ },
+ mentionBody(all, msg),
+ { hop: msg.hop, budget: budgetLine(org, spend, agentId) },
+ );
+ }
+ }
+ deps.cache.setChannelOffset(org.projectId, org.orgId, channelId, date, nextOffset);
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Budgets
+// ---------------------------------------------------------------------------
+
+async function reconcileBudgets(deps: OrgDeps, org: LoadedOrg, spend: OrgSpend): Promise<void> {
+ const nowIso = new Date(nowOf(deps)).toISOString();
+ for (const e of org.chart.employees) {
+ if (e.budget === undefined) continue;
+ const cost = spend.cumulative.get(e.agentId) ?? 0;
+ // A zero budget is spent the moment it is written — everything is already over it — so it
+ // reads 100% whatever the cost, the figure `budgetLine` already puts in the trigger block.
+ const ratio = e.budget > 0 ? cost / e.budget : 1;
+ const state = deps.cache.budgetState(org.projectId, org.orgId, e.agentId, spend.period);
+ const notify = (state: "warned" | "paused" | "resumed"): void =>
+ deps.notifyProject(org.projectId, {
+ type: "org_budget",
+ projectId: org.projectId,
+ orgId: org.orgId,
+ agentId: e.agentId,
+ state,
+ ratio,
+ });
+ const pct = Math.round(ratio * 100);
+ if (ratio >= org.config.budgetPauseRatio) {
+ if (state?.pausedAt === undefined || state.pausedAt === null) {
+ deps.cache.markBudget(org.projectId, org.orgId, e.agentId, spend.period, {
+ pausedAt: nowIso,
+ });
+ await appendSystemMessage(
+ deps,
+ org,
+ DEFAULT_CHANNEL_ID,
+ budgetPaused({
+ agent: agentPrincipal(e.agentId),
+ period: spend.period,
+ percent: pct,
+ cost,
+ budget: e.budget,
+ }),
+ [],
+ );
+ notify("paused");
+ }
+ } else if (state?.pausedAt !== undefined && state.pausedAt !== null) {
+ deps.cache.markBudget(org.projectId, org.orgId, e.agentId, spend.period, { pausedAt: null });
+ notify("resumed");
+ }
+ if (
+ ratio >= org.config.budgetWarnRatio &&
+ (state?.warnedAt === undefined || state.warnedAt === null)
+ ) {
+ deps.cache.markBudget(org.projectId, org.orgId, e.agentId, spend.period, {
+ warnedAt: nowIso,
+ });
+ await appendSystemMessage(
+ deps,
+ org,
+ DEFAULT_CHANNEL_ID,
+ budgetWarned({
+ agent: agentPrincipal(e.agentId),
+ period: spend.period,
+ percent: pct,
+ cost,
+ budget: e.budget,
+ }),
+ [],
+ );
+ notify("warned");
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// The pass
+// ---------------------------------------------------------------------------
+
+export interface ReconcileResult {
+ org: LoadedOrg;
+ tickets: LoadedTicket[];
+ spend: OrgSpend;
+}
+
+/**
+ * Reconciles one organization. `triggers: false` keeps the pass to caches, desks and
+ * budgets (the master switch is off, or a route only needs the projections refreshed).
+ */
+export async function reconcileOrg(
+ deps: OrgDeps,
+ projectId: string,
+ orgId: string,
+ opts: { triggers?: boolean } = {},
+): Promise<ReconcileResult | null> {
+ const org = await loadOrg(deps, projectId, orgId);
+ if (org === null) return null;
+ const triggers = opts.triggers ?? true;
+ if (org.invalid !== undefined) {
+ recordError(deps, org, "org_invalid", `Organization ${orgId} is invalid: ${org.invalid}`);
+ const { tickets } = await listTickets(deps, org);
+ const spend = await computeSpend(deps, org, tickets);
+ return { org, tickets, spend };
+ }
+ const { tickets } = await listTickets(deps, org);
+ syncCaches(deps, org, tickets);
+ await reconcileEmployeePlugins(deps, org);
+ await provisionMissingDesks(deps, org);
+ await renewMovedDesks(deps, org);
+ const spend = await computeSpend(deps, org, tickets);
+ await reconcileBudgets(deps, org, spend);
+ const paused = pausedEmployees(deps, org, spend.period);
+ await reconcileCalendar(deps, org, tickets, spend, paused, triggers);
+ await reconcileTickets(deps, org, tickets);
+ await scanChannels(deps, org, spend, triggers);
+ return { org, tickets, spend };
+}
diff --git a/packages/server/src/runtime/organization/rota.ts b/packages/server/src/runtime/organization/rota.ts
new file mode 100644
index 00000000..f5235f30
--- /dev/null
+++ b/packages/server/src/runtime/organization/rota.ts
@@ -0,0 +1,81 @@
+/**
+ * Rota advice for a calendar write. A calendar is a rota, not a broadcast: desks that fire
+ * on the same minute compete for the same budget minute and the same tickets, and a second
+ * sweep on one employee doubles its cost for nothing. The write itself always succeeds —
+ * these are advisory lines the CLI prints and the skills tell employees to act on, so a
+ * scheduling mistake is visible at the moment it is made instead of at the month's bill.
+ *
+ * Pure: the caller passes the organization's whole calendar listing, the event it just
+ * wrote, the clock and the organization's timezone.
+ */
+import { zonedParts } from "../../organization/zoned.js";
+
+/** The fields a rota check reads; `OrgCalendarItem` satisfies it. */
+export interface RotaEvent {
+ agentId: string;
+ name: string;
+ enabled: boolean;
+ /** ISO 8601 instant, as stored. */
+ startAt: string;
+ /** Absent for a one-shot event. */
+ period?: string;
+}
+
+/** How close to the write "started at now" counts as: the CLI resolves `--start-at now` to the current instant. */
+const NOW_WINDOW_MS = 90_000;
+
+/** `HH:MM` of an instant in the organization's timezone, or null when `startAt` is not an instant. */
+function startMinute(timezone: string, startAt: string): string | null {
+ const ms = Date.parse(startAt);
+ if (Number.isNaN(ms)) return null;
+ const p = zonedParts(timezone, ms);
+ return `${String(p.hour).padStart(2, "0")}:${String(p.minute).padStart(2, "0")}`;
+}
+
+const isRecurring = (e: RotaEvent): boolean => e.period !== undefined && e.period !== "";
+
+const isSame = (a: RotaEvent, b: RotaEvent): boolean =>
+ a.agentId === b.agentId && a.name === b.name;
+
+/**
+ * The advisory lines for `written`, in the order a scheduler should fix them: whose minute
+ * it collides with, whether that employee already sweeps on this cadence, and whether it was
+ * started at "now" (which pins every event scheduled that way to one minute). Empty when the
+ * rota is clean — a disabled event is nobody's rota.
+ */
+export function rotaWarnings(
+ events: readonly RotaEvent[],
+ written: RotaEvent,
+ nowMs: number,
+ timezone: string,
+): string[] {
+ if (!written.enabled) return [];
+ const out: string[] = [];
+ const minute = startMinute(timezone, written.startAt);
+ if (minute !== null) {
+ for (const e of events) {
+ if (isSame(e, written) || e.agentId === written.agentId) continue;
+ if (!e.enabled || !isRecurring(e)) continue;
+ if (startMinute(timezone, e.startAt) !== minute) continue;
+ out.push(
+ `\`${e.agentId}/${e.name}\` also fires at ${minute}; give every employee its own minute.`,
+ );
+ }
+ }
+ if (isRecurring(written)) {
+ for (const e of events) {
+ if (isSame(e, written) || e.agentId !== written.agentId) continue;
+ if (!e.enabled || e.period !== written.period) continue;
+ out.push(
+ `\`${written.agentId}\` already has a recurring event \`${e.name}\` with period ${written.period}; one sweep per employee.`,
+ );
+ }
+ const ms = Date.parse(written.startAt);
+ if (!Number.isNaN(ms) && Math.abs(ms - nowMs) <= NOW_WINDOW_MS) {
+ out.push(
+ "A recurring event started at 'now' shares its minute with every other event started the same way; pick the role's hour.",
+ );
+ }
+ }
+ return out;
+}
diff --git a/packages/server/src/runtime/organization/scheduler.ts b/packages/server/src/runtime/organization/scheduler.ts
new file mode 100644
index 00000000..ca69c62e
--- /dev/null
+++ b/packages/server/src/runtime/organization/scheduler.ts
@@ -0,0 +1,87 @@
+/**
+ * The organization scheduler: a Web server runtime component, alive only while the
+ * server runs, shaped like the schedule scheduler — one reconcile pass at start (no
+ * backfill), then a periodic tick over every organization of every Project. A route
+ * write asks for an immediate pass of just its organization, so API changes take effect
+ * now while hand edits wait for the next tick. The admin switch is read every tick: off
+ * means the pass still refreshes caches but fires nothing.
+ */
+import type { OrgDeps } from "./deps.js";
+import { KeyedLocks, orgLockKey } from "./locks.js";
+import { reconcileOrg } from "./reconcile.js";
+import type { ReconcileResult } from "./reconcile.js";
+
+/** Same cadence as schedules: the calendar's minimum period is 5m, so 30s is plenty. */
+const TICK_INTERVAL_MS = 30_000;
+
+export class OrganizationScheduler {
+ private timer: ReturnType<typeof setInterval> | null = null;
+ private ticking = false;
+ private readonly intervalMs: number;
+ readonly locks = new KeyedLocks();
+
+ constructor(
+ private readonly deps: OrgDeps,
+ opts: { intervalMs?: number } = {},
+ ) {
+ this.intervalMs = opts.intervalMs ?? TICK_INTERVAL_MS;
+ }
+
+ async start(): Promise<void> {
+ await this.tickOnce();
+ this.timer = setInterval(() => {
+ void this.tickOnce();
+ }, this.intervalMs);
+ this.timer.unref?.();
+ }
+
+ stop(): void {
+ if (this.timer) clearInterval(this.timer);
+ this.timer = null;
+ }
+
+ /** One pass over every organization (deterministic entry for tests; concurrent calls run only one). */
+ async tickOnce(): Promise<void> {
+ if (this.ticking) return;
+ this.ticking = true;
+ try {
+ const triggers = this.deps.companyModeEnabled();
+ for (const project of this.deps.projects.listAll()) {
+ for (const orgId of await this.deps.store.listOrgIds(project.projectId)) {
+ try {
+ await this.reconcile(project.projectId, orgId, { triggers });
+ } catch (err) {
+ this.deps.errors.record({
+ source: "organization",
+ err,
+ code: "org_tick_failed",
+ ctx: { projectId: project.projectId },
+ });
+ }
+ }
+ }
+ } catch (err) {
+ this.deps.errors.record({ source: "organization", err, code: "org_tick_failed" });
+ } finally {
+ this.ticking = false;
+ }
+ }
+
+ /** Immediate-effect entry after a route write: one organization, serialized with the tick. */
+ reconcile(
+ projectId: string,
+ orgId: string,
+ opts: { triggers?: boolean } = {},
+ ): Promise<ReconcileResult | null> {
+ return this.locks.run(orgLockKey(projectId, orgId), () =>
+ reconcileOrg(this.deps, projectId, orgId, {
+ triggers: opts.triggers ?? this.deps.companyModeEnabled(),
+ }),
+ );
+ }
+
+ /** Runs a write under the organization's lock so it never interleaves with a pass. */
+ withLock<T>(projectId: string, orgId: string, fn: () => Promise<T>): Promise<T> {
+ return this.locks.run(orgLockKey(projectId, orgId), fn);
+ }
+}
diff --git a/packages/server/src/runtime/organization/service.ts b/packages/server/src/runtime/organization/service.ts
new file mode 100644
index 00000000..c721a403
--- /dev/null
+++ b/packages/server/src/runtime/organization/service.ts
@@ -0,0 +1,2841 @@
+import fs from "node:fs/promises";
+import path from "node:path";
+/**
+ * The organization service: what the routes (and through them the CLI and the Web App)
+ * call. Every write is a validated edit of an organization file under the organization's
+ * lock, followed by an immediate reconcile pass so the change takes effect now; every
+ * read is a projection of the files plus the live session state and the period's spend.
+ */
+import type {
+ OrgCalendarItem,
+ OrgCalendarResponse,
+ OrgCalendarUpsertRequest,
+ OrgCalendarWriteResponse,
+ SemanticIdSuggestReason,
+ SemanticIdSuggestRequest,
+ SemanticIdSuggestResponse,
+ OrgChannelCreateRequest,
+ OrgChannelDetail,
+ OrgChannelItem,
+ OrgChannelMember,
+ OrgChannelPatchRequest,
+ OrgChannelsResponse,
+ OrgChannelMessage,
+ OrgChannelMessageSendRequest,
+ OrgChannelMessagesResponse,
+ OrgChartResponse,
+ OrgDeskResponse,
+ OrgEmployeeItem,
+ OrgEmployeePatchRequest,
+ OrgFinanceResponse,
+ OrgHireRequest,
+ OrgInbox,
+ OrgSessionsResponse,
+ OrgTicketCreateRequest,
+ OrgTicketDetail,
+ OrgTicketHistoryAction,
+ OrgTicketItem,
+ OrgTicketSessionItem,
+ OrgTicketStatus,
+ OrgTicketUpdateRequest,
+ OrgTicketsResponse,
+ OrganizationCreateRequest,
+ OrganizationDetail,
+ OrganizationPatchRequest,
+ OrganizationSettings,
+ OrganizationSummary,
+ OrgLanguage,
+ ScheduleStatus,
+ OrgHandbookFileResponse,
+ OrgHandbookFilesResponse,
+} from "../../api/types.js";
+import { TICKET_SLUG_PATTERN } from "../../api/types.js";
+import { Interface, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";
+import type { ClassCtx } from "@prismshadow/penguin-core/kernel";
+import { HttpError } from "../../http/errors.js";
+import { userChannelKey } from "../../http/routes/events.js";
+import type { Channels, Clock, Config, Log } from "../../hmr/capabilities.js";
+import type { ChannelHub } from "../channel.js";
+import type { OrgCache } from "../../mechanisms/organization.js";
+import type { AgentConfig, AgentLifecycle } from "../../mechanisms/agents.js";
+import type {
+ AgentIndex,
+ Members,
+ ProjectConfigStore,
+ Projects,
+} from "../../mechanisms/projects.js";
+import type { SessionIndex } from "../../mechanisms/sessions.js";
+import type { Settings } from "../../mechanisms/settings.js";
+import type { Errors, UsageQueries } from "../../mechanisms/observability.js";
+import { OrgStore } from "../../organization/store.js";
+import { badRequest } from "../../http/validate.js";
+import type { ChannelConfig, OrgConfig, OrgEmployee, TicketDoc } from "../../organization/files.js";
+import {
+ BUDGET_RATIO_MAX,
+ DEFAULT_CEO_BUDGET,
+ MENTION_CHAIN_LIMIT_MAX,
+ ORG_CONFIG_DEFAULTS,
+ TICKET_ID_PATTERN,
+ defaultTicketNotify,
+ detectLanguage,
+ extractMentionTokens,
+ historyNote,
+ orgLanguage,
+ parseCalendarEvent,
+ parseOrgChart,
+ serializeCalendarEvent,
+ serializeOrgChart,
+ slugSuffix,
+ slugify,
+} from "../../organization/files.js";
+import { renderHandbook } from "../../organization/handbook.js";
+import {
+ DEFAULT_CHANNEL_ID,
+ ORG_TICKET_COLUMNS,
+ ceoAgentId,
+ isChannelId,
+ isHandbookFilePath,
+ isTicketColumn,
+ normalizeWorkspaceSpec,
+} from "../../organization/paths.js";
+import {
+ agentPrincipal,
+ parsePrincipal,
+ principalAgentId,
+ 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_PATTERN } from "../../services/ids.js";
+import { latestSlotAt, nextSlotAfter, slotInWindow } from "../schedule-file.js";
+import type { ScheduleDefinition } from "../schedule-file.js";
+import { budgetLine, budgetRatio, computeSpend, pausedEmployees } from "./budget.js";
+import type { OrgSpend } from "./budget.js";
+import { DEFAULT_EMPLOYEE_PLUGINS, OrgRuns, OrgSessions, employeePlugins } from "./deps.js";
+import type { OrgDeps } from "./deps.js";
+import { loadOrg, sharedWorkspace } from "./model.js";
+import type { LoadedOrg } from "./model.js";
+import {
+ channelArchiveChanged,
+ channelCreated,
+ channelMemberAdded,
+ channelMemberRemoved,
+ employeeJoined,
+ employeeLeft,
+ systemMessage,
+} from "./notices.js";
+import { appendChannelMessage, listTickets, syncCaches } from "./reconcile.js";
+import type { LoadedTicket } from "./reconcile.js";
+import { rotaWarnings } from "./rota.js";
+import { OrganizationScheduler } from "./scheduler.js";
+import { dispatchToDesk, ensureDesk, openTicketSession } from "./triggers.js";
+
+/**
+ * The CEO's partition of the shared workspace. The root of the shared workspace holds the
+ * inputs every desk reads — specs, data, prior deliverables — and is nobody's desk, so the
+ * CEO gets a sub-directory of its own like every other employee.
+ */
+const CEO_WORKSPACE = "ceo";
+
+/**
+ * Who performs a write: a person (route user) or, through the control-env token from the
+ * control environment of a session, that session's employee. `agentId` is the employee the
+ * command subprocess was handed (`PENGUIN_AGENT_ID`) and it wins over the session, so a
+ * command run from a subagent or a nested session of an employee is still recorded as that
+ * employee; `sessionId` answers when there is no Agent id to go by.
+ */
+export interface Actor {
+ userId: string;
+ sessionId?: string;
+ agentId?: string;
+}
+
+const notFound = (orgId: string): HttpError =>
+ new HttpError(404, "org_not_found", `Organization does not exist: ${orgId}`);
+
+const ticketNotFound = (ticketId: string): HttpError =>
+ new HttpError(404, "ticket_not_found", `Ticket does not exist: ${ticketId}`);
+
+const channelNotFound = (channelId: string): HttpError =>
+ new HttpError(404, "channel_not_found", `Channel does not exist: ${channelId}`);
+
+const channelArchived = (channelId: string): HttpError =>
+ new HttpError(
+ 409,
+ "channel_archived",
+ `Channel ${channelId} is archived: unarchive it before writing to it.`,
+ );
+
+const notAMember = (channelId: string, principal: string, why?: string): HttpError =>
+ new HttpError(
+ 403,
+ "not_a_member",
+ why ?? `${principal} is not a member of the channel ${channelId}.`,
+ );
+
+const allHandsImmutable = (message: string): HttpError =>
+ new HttpError(400, "all_hands_immutable", message);
+
+/**
+ * The two numeric settings, held to the bounds the config parser enforces. The settings
+ * write path is the looser of the two, so a value it let through would be written and then
+ * refuse to parse on the next load — the organization is marked invalid and its automation
+ * stops. The bounds themselves live beside the parser; only the request wording is here.
+ */
+const requireChainLimit = (value: number): number => {
+ if (!Number.isInteger(value) || value < 0 || value > MENTION_CHAIN_LIMIT_MAX) {
+ throw badRequest(
+ `mentionChainLimit must be an integer between 0 and ${MENTION_CHAIN_LIMIT_MAX}.`,
+ );
+ }
+ return value;
+};
+
+const requireBudgetRatio = (key: string, value: number): number => {
+ if (!(value > 0) || value > BUDGET_RATIO_MAX)
+ throw badRequest(`${key} must be a number in (0, ${BUDGET_RATIO_MAX}].`);
+ return value;
+};
+
+export class OrganizationService {
+ constructor(
+ private readonly deps: OrgDeps,
+ private readonly scheduler: OrganizationScheduler,
+ ) {}
+
+ private now(): number {
+ return this.deps.now?.() ?? Date.now();
+ }
+
+ /** The organization a session belongs to, for the `PENGUIN_ORG_ID` control variable. */
+ orgIdOfSession(sessionId: string): string | null {
+ return this.deps.cache.ownerOfSession(sessionId)?.orgId ?? null;
+ }
+
+ /**
+ * 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.
+ */
+ 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(
+ projectId,
+ `${req.kind} id for "${req.name}": no id could be built from the model's answer: ${lastAnswer.trim()}`,
+ );
+ 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);
+ this.deps.log?.(`org: id suggestion fell back for ${projectId}: ${message}`);
+ this.deps.errors.record({
+ source: "organization",
+ code: "id_suggest_failed",
+ kind: "expected",
+ ctx: { projectId },
+ err: new Error(message),
+ });
+ }
+
+ private async requireOrg(projectId: string, orgId: string): Promise<LoadedOrg> {
+ const org = await loadOrg(this.deps, projectId, orgId);
+ if (org === null) throw notFound(orgId);
+ return org;
+ }
+
+ /** A write that needs the chart: an invalid organization is repaired by editing its files, not through the API. */
+ private async requireValidOrg(projectId: string, orgId: string): Promise<LoadedOrg> {
+ const org = await this.requireOrg(projectId, orgId);
+ if (org.invalid !== undefined) {
+ throw new HttpError(409, "org_invalid", `Organization ${orgId} needs repair: ${org.invalid}`);
+ }
+ return org;
+ }
+
+ /**
+ * The principal a write is recorded under: the Agent id the caller carries when it names an
+ * employee of this organization, else the employee of the calling session, else the person.
+ * The Agent id comes first because it is the narrower fact — the session may be a desk that
+ * spawned the command, while `PENGUIN_AGENT_ID` names exactly who ran it.
+ */
+ private actorPrincipal(org: LoadedOrg, actor: Actor): string {
+ if (actor.agentId !== undefined && org.byId.has(actor.agentId)) {
+ return agentPrincipal(actor.agentId);
+ }
+ if (actor.sessionId !== undefined) {
+ const owner = this.deps.cache.ownerOfSession(actor.sessionId);
+ if (owner && owner.projectId === org.projectId && owner.orgId === org.orgId) {
+ return agentPrincipal(owner.agentId);
+ }
+ const row = this.deps.sessions.findById(actor.sessionId);
+ if (row && row.projectId === org.projectId && org.byId.has(row.agentId))
+ return agentPrincipal(row.agentId);
+ }
+ return userPrincipal(actor.userId);
+ }
+
+ /**
+ * The employee an actor writes as, or null when it writes as a person. The one question
+ * the ticket-start rule asks: a desk or ticket session names its employee, everything else
+ * — the Web App, a signed-in CLI outside a session — is a person of the Project.
+ */
+ private actorEmployee(org: LoadedOrg, actor: Actor): string | null {
+ return principalAgentId(this.actorPrincipal(org, actor));
+ }
+
+ // ---------------------------------------------------------------------------
+ // Organizations
+ // ---------------------------------------------------------------------------
+
+ async list(projectId: string): Promise<OrganizationSummary[]> {
+ const out: OrganizationSummary[] = [];
+ for (const orgId of await this.deps.store.listOrgIds(projectId)) {
+ const org = await loadOrg(this.deps, projectId, orgId);
+ if (org === null) continue;
+ const { tickets } = await listTickets(this.deps, org);
+ const spend = await computeSpend(this.deps, org, tickets);
+ out.push(this.summary(org, tickets, spend));
+ }
+ return out;
+ }
+
+ private summary(
+ org: LoadedOrg,
+ tickets: readonly LoadedTicket[],
+ spend: OrgSpend,
+ ): OrganizationSummary {
+ const paused = pausedEmployees(this.deps, org, spend.period);
+ let running = 0;
+ for (const e of org.chart.employees) if (this.employeeRunning(org, e.agentId)) running++;
+ const ceo = ceoAgentId(org.orgId);
+ const ceoBudget = org.byId.get(ceo)?.budget;
+ const cost = spend.cumulative.get(ceo) ?? 0;
+ return {
+ projectId: org.projectId,
+ orgId: org.orgId,
+ name: org.config.name,
+ mission: org.config.mission,
+ status: org.config.status,
+ employeeCount: org.chart.employees.length,
+ runningCount: running,
+ pausedCount: paused.size,
+ openTickets: tickets.filter((t) => t.column !== "done" && t.column !== "rejected").length,
+ blockedTickets: tickets.filter((t) => t.doc.blocked !== undefined && t.doc.blocked !== "")
+ .length,
+ createdBy: org.config.createdBy,
+ spend: {
+ period: spend.period,
+ cost,
+ ...(ceoBudget !== undefined
+ ? { budget: ceoBudget, ratio: budgetRatio(cost, ceoBudget) }
+ : {}),
+ },
+ ...(org.invalid !== undefined ? { invalid: org.invalid } : {}),
+ };
+ }
+
+ private employeeRunning(org: LoadedOrg, agentId: string): boolean {
+ const desk = org.desks[agentId];
+ if (desk && this.deps.runner.statusOf(desk.sessionId) !== "idle") return true;
+ for (const row of this.deps.cache.ticketSessions(org.projectId, org.orgId)) {
+ if (row.agentId === agentId && this.deps.runner.statusOf(row.sessionId) !== "idle")
+ return true;
+ }
+ return false;
+ }
+
+ private settings(org: LoadedOrg): OrganizationSettings {
+ return {
+ name: org.config.name,
+ mission: org.config.mission,
+ status: org.config.status,
+ timezone: org.config.timezone,
+ approvalMode: org.config.approvalMode,
+ mentionChainLimit: org.config.mentionChainLimit,
+ budgetWarnRatio: org.config.budgetWarnRatio,
+ budgetPauseRatio: org.config.budgetPauseRatio,
+ createdBy: org.config.createdBy,
+ // Always the effective language, never the raw field: an organization written before
+ // the field existed still has one, read from its mission.
+ language: orgLanguage(org.config),
+ ...(org.config.workspace !== undefined ? { workspace: org.config.workspace } : {}),
+ ...(org.config.model !== undefined ? { model: org.config.model } : {}),
+ };
+ }
+
+ /** A shared-workspace root chosen by the user: absolute and an existing directory. */
+ private async requireWorkspaceDir(spec: string): Promise<string> {
+ if (!path.isAbsolute(spec)) throw badRequest("workspace must be an absolute path.");
+ const real = await fs.stat(spec).then(
+ (s) => (s.isDirectory() ? spec : null),
+ () => null,
+ );
+ if (real === null) throw badRequest(`workspace directory does not exist: ${spec}`);
+ return real;
+ }
+
+ async detail(projectId: string, orgId: string, userId: string): Promise<OrganizationDetail> {
+ const org = await this.requireOrg(projectId, orgId);
+ const { tickets } = await listTickets(this.deps, org);
+ const spend = await computeSpend(this.deps, org, tickets);
+ const summary = this.summary(org, tickets, spend);
+ const board = Object.fromEntries(ORG_TICKET_COLUMNS.map((c) => [c, 0])) as Record<
+ OrgTicketStatus,
+ number
+ >;
+ for (const t of tickets) board[t.column]++;
+ const nowMs = this.now();
+ const todayDate = zonedDate(org.config.timezone, nowMs);
+ const day = zonedDayRange(org.config.timezone, todayDate);
+ const calendar = await this.calendarItems(org, spend);
+ const today = calendar.events.filter((e) => {
+ const inDay = (iso: string | undefined): boolean => {
+ if (iso === undefined) return false;
+ const ms = Date.parse(iso);
+ return ms >= day.fromMs && ms < day.toMs;
+ };
+ return inDay(e.nextFireAt) || inDay(e.lastFiredAt);
+ });
+ // The overview opens even when the all-hands channel's file is missing or unreadable (a
+ // hand edit): it then reports no recent messages instead of refusing the page.
+ const allHands = await this.deps.store.readChannel(org.dir, DEFAULT_CHANNEL_ID);
+ const recent =
+ allHands?.parsed.ok === true
+ ? await this.channelMessages(projectId, orgId, { userId }, DEFAULT_CHANNEL_ID, {})
+ : null;
+ const mentions = await this.pendingMentions(org, userId);
+ const me = userPrincipal(userId);
+ const items = this.ticketItems(tickets, spend);
+ const ceoDesk = org.desks[ceoAgentId(orgId)];
+ return {
+ ...summary,
+ settings: this.settings(org),
+ board,
+ today,
+ pending: {
+ mentions,
+ reviewTickets: items.filter((t) => t.status === "review"),
+ blockedByMe: items.filter((t) => t.blockedBy === me),
+ },
+ recentMessages: recent?.messages.slice(-20) ?? [],
+ inbox: this.inbox(spend, items, tickets, recent?.messages ?? [], me),
+ alerts: this.alerts(org, spend.period),
+ ...(ceoDesk !== undefined ? { ceoDeskSessionId: ceoDesk.sessionId } : {}),
+ };
+ }
+
+ /**
+ * The overview's inbox — what a person is waited on or told about, read from the same
+ * files `detail` already loaded:
+ *
+ * - `mentions`: the all-hands messages of the window `recentMessages` reads (the
+ * organization's current day) that name the caller or `all`, newest first.
+ * - `blockedTickets`: every ticket carrying a `Blocked` reason, whoever it waits on —
+ * uncapped, because a blocked ticket is work nobody is doing.
+ * - `doneTickets`: tickets in `done` that closed in the current budget period, `closedAt`
+ * taken from the last `moved`-to-`done` history entry. A ticket whose file was moved by
+ * hand has no such entry and no closing time to test, so it is listed with `closedAt`
+ * absent rather than hidden.
+ *
+ * Newest first everywhere; ticket ids start with the filing date, so ordering by id
+ * descending is ordering by age.
+ */
+ private inbox(
+ spend: OrgSpend,
+ items: readonly OrgTicketItem[],
+ tickets: readonly LoadedTicket[],
+ windowMessages: readonly OrgChannelMessage[],
+ me: string,
+ ): OrgInbox {
+ const mentions = windowMessages
+ .filter((m) => m.mentions.includes(me) || m.mentions.includes("all"))
+ .reverse()
+ .slice(0, INBOX_PAGE);
+ const newestFirst = <T extends { ticketId: string }>(a: T, b: T): number =>
+ a.ticketId < b.ticketId ? 1 : a.ticketId > b.ticketId ? -1 : 0;
+ const closedAt = new Map<string, string>();
+ for (const t of tickets) {
+ const at = lastClosedAt(t.doc);
+ if (at !== null) closedAt.set(t.ticketId, at);
+ }
+ const inPeriod = (iso: string): boolean => {
+ const ms = Date.parse(iso);
+ // An unparsable stamp is a hand-edited line, not evidence the ticket closed elsewhen.
+ return Number.isNaN(ms) || (ms >= spend.range.fromMs && ms < spend.range.toMs);
+ };
+ const doneTickets = items
+ .filter((t) => t.status === "done")
+ .map((t): OrgInbox["doneTickets"][number] => {
+ const at = closedAt.get(t.ticketId);
+ return { ...t, ...(at !== undefined ? { closedAt: at } : {}) };
+ })
+ .filter((t) => t.closedAt === undefined || inPeriod(t.closedAt))
+ .sort(newestFirst)
+ .slice(0, INBOX_PAGE);
+ return {
+ mentions,
+ blockedTickets: items.filter((t) => (t.blocked ?? "") !== "").sort(newestFirst),
+ doneTickets,
+ };
+ }
+
+ /** Mentions waiting for a person, summed over every channel they belong to. */
+ private async pendingMentions(org: LoadedOrg, userId: string): Promise<number> {
+ const me = userPrincipal(userId);
+ let mentions = 0;
+ for (const file of await this.deps.store.listChannels(org.dir)) {
+ if (!file.parsed.ok) continue;
+ if (!this.channelMemberPrincipals(org, file.parsed.value).includes(me)) continue;
+ mentions += (await this.channelActivity(org, file.channelId, userId)).mentionsMe;
+ }
+ return mentions;
+ }
+
+ private alerts(org: LoadedOrg, period: string): OrganizationDetail["alerts"] {
+ return this.deps.cache
+ .listBudgetStates(org.projectId, org.orgId, period)
+ .filter((s) => s.warnedAt !== null || s.pausedAt !== null)
+ .map((s) => ({
+ agentId: s.agentId,
+ period: s.period,
+ ...(s.warnedAt !== null ? { warnedAt: s.warnedAt } : {}),
+ ...(s.pausedAt !== null ? { pausedAt: s.pausedAt } : {}),
+ }));
+ }
+
+ /**
+ * Creates an organization as one whole: directory and files, the CEO Agent (with the
+ * company and orchestration plugins and an employee brief), then the initialization work
+ * run on the CEO's desk. Any failure removes what was written; a taken CEO id is a 409
+ * before anything is touched.
+ */
+ async create(
+ projectId: string,
+ req: OrganizationCreateRequest,
+ userId: string,
+ ): Promise<OrganizationDetail> {
+ const orgId = req.orgId;
+ if (!SEMANTIC_ID_PATTERN.test(orgId)) {
+ throw new HttpError(
+ 400,
+ "invalid_org_id",
+ "Organization id must be 2–64 characters: a lowercase letter, then lowercase letters, digits or underscores.",
+ );
+ }
+ const mission = req.mission.trim();
+ if (mission === "") throw badRequest("mission must not be empty.");
+ const timezone = req.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? "UTC";
+ if (!isValidTimeZone(timezone)) throw badRequest(`Unknown timezone: ${timezone}`);
+ if (await this.deps.store.exists(projectId, orgId)) {
+ throw new HttpError(409, "org_exists", `Organization id is already taken: ${orgId}`);
+ }
+ const ceo = ceoAgentId(orgId);
+ if (await this.deps.agents.exists(projectId, ceo)) {
+ throw new HttpError(409, "agent_exists", `The CEO's Agent id is already taken: ${ceo}`);
+ }
+ const name = req.name?.trim() || orgId;
+ if (req.model !== undefined) await this.validateModel(projectId, req.model);
+ const workspace =
+ req.workspace !== undefined ? await this.requireWorkspaceDir(req.workspace) : undefined;
+ // The mission decides the working language unless the request names one: a company given
+ // a Chinese mission writes in Chinese, without anyone having to ask for it.
+ const language = req.language ?? detectLanguage(mission);
+ const config: OrgConfig = {
+ name,
+ mission,
+ status: "active",
+ timezone,
+ language,
+ approvalMode: ORG_CONFIG_DEFAULTS.approvalMode,
+ mentionChainLimit: ORG_CONFIG_DEFAULTS.mentionChainLimit,
+ budgetWarnRatio: ORG_CONFIG_DEFAULTS.budgetWarnRatio,
+ budgetPauseRatio: ORG_CONFIG_DEFAULTS.budgetPauseRatio,
+ createdBy: userId,
+ ...(workspace !== undefined ? { workspace } : {}),
+ ...(req.model !== undefined ? { model: req.model } : {}),
+ };
+ const dir = this.deps.store.dir(projectId, orgId);
+ await this.deps.store.createLayout(dir, new Date(this.now()).toISOString());
+ try {
+ await this.deps.store.writeConfig(dir, config);
+ await this.deps.store.writeChart(dir, {
+ employees: [
+ {
+ agentId: ceo,
+ title: "CEO",
+ reportsTo: null,
+ duties:
+ language === "zh"
+ ? "把使命拆成工单、招募、划分公共工作区、审核工单、向董事会汇报"
+ : "Turn the mission into tickets, hire, partition the shared workspace, review tickets, report to the board",
+ workspace: CEO_WORKSPACE,
+ // Compared on the cumulative line, so this one number is the whole company's cap.
+ budget: req.ceoBudget ?? DEFAULT_CEO_BUDGET,
+ },
+ ],
+ });
+ await this.deps.store.writeHandbook(
+ dir,
+ renderHandbook({ orgId, name, mission, ceoAgentId: ceo, createdBy: userId, language }),
+ );
+ await this.deps.agents.create(
+ projectId,
+ ceo,
+ `${name} CEO`,
+ `CEO of ${name}`,
+ DEFAULT_EMPLOYEE_PLUGINS,
+ );
+ await this.deps.agents.writeAgentsMd(
+ projectId,
+ ceo,
+ employeeBrief({
+ orgId,
+ name,
+ mission,
+ agentId: ceo,
+ title: "CEO",
+ reportsTo: null,
+ language,
+ }),
+ );
+ } catch (err) {
+ await this.deps.store.remove(dir);
+ throw err;
+ }
+ await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireValidOrg(projectId, orgId);
+ const spend = await computeSpend(this.deps, org, []);
+ await dispatchToDesk(this.deps, org, ceo, { kind: "init" }, initBody(org), {
+ hop: 0,
+ budget: budgetLine(org, spend, ceo),
+ });
+ });
+ await this.scheduler.reconcile(projectId, orgId);
+ return this.detail(projectId, orgId, userId);
+ }
+
+ async patch(
+ projectId: string,
+ orgId: string,
+ req: OrganizationPatchRequest,
+ userId: string,
+ ): Promise<OrganizationSettings> {
+ return this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireOrg(projectId, orgId);
+ // A broken config is rewritten whole from the request over the defaults loadOrg filled in.
+ const next: OrgConfig = { ...org.config };
+ // `created_by` is the one default that does not parse: a config that failed to load
+ // carries it empty, and writing that back would leave the file just as unreadable, so
+ // the repair this route exists for would return 200 and change nothing. Whoever is
+ // fixing it becomes its creator; a config that loaded keeps the creator it names.
+ if (next.createdBy === "") next.createdBy = userId;
+ if (req.name !== undefined) {
+ if (req.name.trim() === "") throw badRequest("name must not be empty.");
+ next.name = req.name.trim();
+ }
+ if (req.mission !== undefined) next.mission = req.mission.trim();
+ if (req.status !== undefined) next.status = req.status;
+ if (req.approvalMode !== undefined) next.approvalMode = req.approvalMode;
+ if (req.timezone !== undefined) {
+ if (!isValidTimeZone(req.timezone)) throw badRequest(`Unknown timezone: ${req.timezone}`);
+ next.timezone = req.timezone;
+ }
+ if (req.language !== undefined) next.language = req.language;
+ if (req.mentionChainLimit !== undefined)
+ next.mentionChainLimit = requireChainLimit(req.mentionChainLimit);
+ if (req.budgetWarnRatio !== undefined)
+ next.budgetWarnRatio = requireBudgetRatio("budgetWarnRatio", req.budgetWarnRatio);
+ if (req.budgetPauseRatio !== undefined)
+ next.budgetPauseRatio = requireBudgetRatio("budgetPauseRatio", req.budgetPauseRatio);
+ if (req.workspace === null) delete next.workspace;
+ else if (req.workspace !== undefined)
+ next.workspace = await this.requireWorkspaceDir(req.workspace);
+ if (req.model === null) delete next.model;
+ else if (req.model !== undefined) {
+ await this.validateModel(projectId, req.model);
+ next.model = req.model;
+ }
+ await this.deps.store.writeConfig(org.dir, next);
+ org.config = next;
+ return this.settings(org);
+ });
+ }
+
+ // ---------------------------------------------------------------------------
+ // Employees, desks, handbook
+ // ---------------------------------------------------------------------------
+
+ async chart(projectId: string, orgId: string): Promise<OrgChartResponse> {
+ const org = await this.requireOrg(projectId, orgId);
+ const { tickets } = await listTickets(this.deps, org);
+ const spend = await computeSpend(this.deps, org, tickets);
+ return { ceoAgentId: ceoAgentId(orgId), employees: await this.employeeItems(org, spend) };
+ }
+
+ private async employeeItems(org: LoadedOrg, spend: OrgSpend): Promise<OrgEmployeeItem[]> {
+ const paused = pausedEmployees(this.deps, org, spend.period);
+ const out: OrgEmployeeItem[] = [];
+ const shared = sharedWorkspace(org);
+ for (const e of org.chart.employees) {
+ const exists = await this.deps.agents.exists(org.projectId, e.agentId);
+ // A relative sub-directory that is not there yet is not a broken entry: it is created
+ // when the employee is first put to work. Only a spec that leaves the shared workspace,
+ // or an absolute directory nobody created, makes the entry unusable.
+ const workspace = this.deps.store.workspaceTarget(shared, e.workspace);
+ const absentAbsolute =
+ workspace !== null &&
+ path.isAbsolute(e.workspace) &&
+ (await this.deps.store.resolveWorkspace(shared, e.workspace)) === null;
+ const invalid = !exists
+ ? `Agent ${e.agentId} does not exist`
+ : workspace === null
+ ? `workspace leaves the shared workspace: ${e.workspace}`
+ : absentAbsolute
+ ? `workspace directory does not exist: ${e.workspace}`
+ : undefined;
+ const own = spend.own.get(e.agentId) ?? 0;
+ const cumulative = spend.cumulative.get(e.agentId) ?? 0;
+ const desk = org.desks[e.agentId];
+ out.push({
+ agentId: e.agentId,
+ name: exists ? await this.deps.agents.displayName(org.projectId, e.agentId) : e.agentId,
+ title: e.title,
+ reportsTo: e.reportsTo,
+ ...(e.duties !== undefined ? { duties: e.duties } : {}),
+ workspace: e.workspace,
+ ...(workspace !== null ? { resolvedWorkspace: workspace } : {}),
+ ...(e.budget !== undefined ? { budget: e.budget } : {}),
+ ...(e.model !== undefined ? { model: e.model } : {}),
+ state: paused.has(e.agentId)
+ ? "paused"
+ : this.employeeRunning(org, e.agentId)
+ ? "running"
+ : "idle",
+ ...(desk !== undefined
+ ? {
+ desk: {
+ sessionId: desk.sessionId,
+ workspace: desk.workspace,
+ openedAt: desk.openedAt,
+ },
+ }
+ : {}),
+ spend: {
+ own,
+ cumulative,
+ ...(e.budget !== undefined ? { ratio: budgetRatio(cumulative, e.budget) } : {}),
+ },
+ ...(invalid !== undefined ? { invalid } : {}),
+ });
+ }
+ return out;
+ }
+
+ private async validateModel(
+ projectId: string,
+ model: { provider: string; modelId: string },
+ ): Promise<void> {
+ const cfg = await this.deps.projectConfig.loadConfig(projectId);
+ const known = cfg.models.some(
+ (m) => m.provider === model.provider && m.model_id === model.modelId,
+ );
+ if (!known)
+ throw badRequest(
+ `Model (${model.provider}, ${model.modelId}) is not configured in this Project.`,
+ );
+ }
+
+ /**
+ * The workspace spec to store for an employee, with its directory ready: `./hr`, `hr/` and
+ * `hr` all become `hr`, a relative partition is created under the shared workspace, and an
+ * absolute path must already exist because it is a directory of the user's, not ours to
+ * make. A spec that climbs out of the shared workspace is refused outright. The spec is
+ * always the caller's: each entry point names its own default rather than falling back here.
+ */
+ private async requireEmployeeWorkspace(org: LoadedOrg, spec: string): Promise<string> {
+ const normalized = normalizeWorkspaceSpec(spec);
+ const shared = sharedWorkspace(org);
+ if (this.deps.store.workspaceTarget(shared, normalized) === null) {
+ throw new HttpError(
+ 400,
+ "invalid_workspace",
+ `workspace must stay inside the shared workspace: ${normalized}`,
+ );
+ }
+ if ((await this.deps.store.ensureWorkspace(shared, normalized)) === null) {
+ throw new HttpError(
+ 400,
+ "invalid_workspace",
+ `workspace directory does not exist: ${normalized}`,
+ );
+ }
+ return normalized;
+ }
+
+ /** Writes a chart after re-validating it through the parser: the API never persists what a hand edit would be refused for. */
+ private async writeChart(org: LoadedOrg, employees: OrgEmployee[]): Promise<void> {
+ const raw = serializeOrgChart({ employees });
+ const parsed = parseOrgChart(raw, org.orgId);
+ if (!parsed.ok) throw badRequest(`Invalid employee tree: ${parsed.error}`);
+ await this.deps.store.writeChart(org.dir, parsed.value);
+ org.chart = parsed.value;
+ org.byId = new Map(parsed.value.employees.map((e) => [e.agentId, e]));
+ }
+
+ async hire(projectId: string, orgId: string, req: OrgHireRequest): Promise<OrgEmployeeItem> {
+ const item = await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireValidOrg(projectId, orgId);
+ const title = req.title.trim();
+ if (title === "") throw badRequest("title must not be empty.");
+ if (!org.byId.has(req.reportsTo))
+ throw badRequest(`reportsTo names no employee: ${req.reportsTo}`);
+ if ((req.agentId === undefined) === (req.newAgent === undefined)) {
+ throw badRequest(
+ "Give exactly one of agentId (an existing Agent) or newAgent (create one).",
+ );
+ }
+ if (req.model !== undefined) await this.validateModel(projectId, req.model);
+ const agentId = req.newAgent?.agentId ?? req.agentId!;
+ if (req.newAgent !== undefined) {
+ if (!SEMANTIC_ID_PATTERN.test(agentId))
+ throw badRequest("newAgent.agentId is not a valid Agent id.");
+ } else if (!(await this.deps.agents.exists(projectId, agentId))) {
+ throw new HttpError(404, "agent_not_found", `Agent does not exist: ${agentId}`);
+ }
+ if (org.byId.has(agentId))
+ throw new HttpError(409, "employee_exists", `${agentId} is already an employee.`);
+ // Before the Agent and the chart entry: the partition an employee is hired into exists
+ // from the moment the employee does, and a spec that leaves the shared workspace is
+ // refused rather than written and found broken on the first trigger. Omitted, it is a
+ // sub-directory named after the employee — the shared root is nobody's desk.
+ const workspace = await this.requireEmployeeWorkspace(org, req.workspace ?? agentId);
+ if (req.newAgent !== undefined) {
+ await this.deps.agents.create(
+ projectId,
+ agentId,
+ req.newAgent.name,
+ req.newAgent.description,
+ employeePlugins(req.newAgent.plugins),
+ );
+ await this.deps.agents.writeAgentsMd(
+ projectId,
+ agentId,
+ employeeBrief({
+ orgId,
+ name: org.config.name,
+ mission: org.config.mission,
+ agentId,
+ title,
+ reportsTo: req.reportsTo,
+ language: orgLanguage(org.config),
+ ...(req.duties !== undefined ? { duties: req.duties } : {}),
+ }),
+ );
+ }
+ const employee: OrgEmployee = {
+ agentId,
+ title,
+ reportsTo: req.reportsTo,
+ ...(req.duties !== undefined && req.duties.trim() !== ""
+ ? { duties: req.duties.trim() }
+ : {}),
+ workspace,
+ ...(req.budget !== undefined ? { budget: req.budget } : {}),
+ ...(req.model !== undefined ? { model: req.model } : {}),
+ };
+ await this.writeChart(org, [...org.chart.employees, employee]);
+ await appendChannelMessage(
+ this.deps,
+ org,
+ DEFAULT_CHANNEL_ID,
+ systemMessage(
+ employeeJoined(agentPrincipal(agentId), title, agentPrincipal(req.reportsTo)),
+ ),
+ );
+ // The desk exists from the moment the employee does. It is what every surface
+ // addressing the employee by Session id needs — the sidebar's desk row and its
+ // messaging binding, `penguin org desk show`, an @-mention — and opening it only on
+ // first use left a fresh hire with a row pointing at no Session at all. A desk is a
+ // Session, not a run: nothing is dispatched here. A failure (the Agent or the
+ // partition disappeared between the writes above and this line) is recorded and the
+ // hire still stands; the reconcile pass provisions the desk on its next sweep.
+ const desk = await ensureDesk(this.deps, org, agentId);
+ if (!desk.ok) {
+ this.deps.errors.record({
+ source: "organization",
+ err: new Error(desk.error),
+ code: "org_desk_unavailable",
+ ctx: { projectId, agentId },
+ });
+ }
+ const spend = await computeSpend(this.deps, org, (await listTickets(this.deps, org)).tickets);
+ const items = await this.employeeItems(org, spend);
+ return items.find((i) => i.agentId === agentId)!;
+ });
+ await this.scheduler.reconcile(projectId, orgId);
+ return item;
+ }
+
+ async patchEmployee(
+ projectId: string,
+ orgId: string,
+ agentId: string,
+ req: OrgEmployeePatchRequest,
+ ): Promise<OrgEmployeeItem> {
+ const item = await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireValidOrg(projectId, orgId);
+ const current = org.byId.get(agentId);
+ if (!current)
+ throw new HttpError(404, "employee_not_found", `${agentId} is not an employee.`);
+ if (req.model !== undefined && req.model !== null)
+ await this.validateModel(projectId, req.model);
+ if (req.reportsTo !== undefined && current.reportsTo === null) {
+ throw badRequest("The CEO reports to nobody.");
+ }
+ const next: OrgEmployee = {
+ ...current,
+ ...(req.title !== undefined ? { title: req.title.trim() } : {}),
+ ...(req.reportsTo !== undefined ? { reportsTo: req.reportsTo } : {}),
+ // A reassigned partition is created here, so the desk the next reconcile renews has
+ // its directory waiting for it.
+ ...(req.workspace !== undefined
+ ? { workspace: await this.requireEmployeeWorkspace(org, req.workspace) }
+ : {}),
+ ...(req.duties !== undefined ? { duties: req.duties.trim() } : {}),
+ };
+ if (req.budget === null) delete next.budget;
+ else if (req.budget !== undefined) next.budget = req.budget;
+ if (req.model === null) delete next.model;
+ else if (req.model !== undefined) next.model = req.model;
+ if (next.duties === "") delete next.duties;
+ if (next.title === "") throw badRequest("title must not be empty.");
+ await this.writeChart(
+ org,
+ org.chart.employees.map((e) => (e.agentId === agentId ? next : e)),
+ );
+ const spend = await computeSpend(this.deps, org, (await listTickets(this.deps, org)).tickets);
+ const items = await this.employeeItems(org, spend);
+ return items.find((i) => i.agentId === agentId)!;
+ });
+ await this.scheduler.reconcile(projectId, orgId);
+ return item;
+ }
+
+ /** Removes the employee from the tree (subordinates move up to its manager); the Agent and its sessions stay. */
+ async leave(projectId: string, orgId: string, agentId: string): Promise<void> {
+ await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireValidOrg(projectId, orgId);
+ const current = org.byId.get(agentId);
+ if (!current)
+ throw new HttpError(404, "employee_not_found", `${agentId} is not an employee.`);
+ if (current.reportsTo === null) throw badRequest("The CEO cannot leave the organization.");
+ const manager = current.reportsTo;
+ await this.writeChart(
+ org,
+ org.chart.employees
+ .filter((e) => e.agentId !== agentId)
+ .map((e) => (e.reportsTo === agentId ? { ...e, reportsTo: manager } : e)),
+ );
+ if (org.desks[agentId] !== undefined) {
+ delete org.desks[agentId];
+ await this.deps.store.writeDesks(org.dir, org.desks);
+ }
+ // Nothing will sweep for this employee again, so its queued ticket changes go with it.
+ this.deps.cache.deleteDeskNotices(projectId, orgId, agentId);
+ for (const f of await this.deps.store.listCalendar(org.dir)) {
+ if (f.agentId === agentId)
+ await this.deps.store.deleteCalendarEvent(org.dir, agentId, f.name);
+ }
+ // A departed employee is nobody's channel member any more: the files say who is in a
+ // channel, and a principal that is no longer an employee would be counted and listed.
+ for (const file of await this.deps.store.listChannels(org.dir)) {
+ if (!file.parsed.ok || file.parsed.value.everyone === true) continue;
+ const members = file.parsed.value.members ?? [];
+ if (!members.includes(agentPrincipal(agentId))) continue;
+ await this.deps.store.writeChannel(org.dir, file.channelId, {
+ ...file.parsed.value,
+ members: members.filter((m) => m !== agentPrincipal(agentId)),
+ });
+ }
+ await appendChannelMessage(
+ this.deps,
+ org,
+ DEFAULT_CHANNEL_ID,
+ systemMessage(employeeLeft(agentPrincipal(agentId), agentPrincipal(manager))),
+ );
+ });
+ await this.scheduler.reconcile(projectId, orgId);
+ }
+
+ async desk(
+ projectId: string,
+ orgId: string,
+ agentId: string,
+ opts: { renew?: boolean },
+ ): Promise<OrgDeskResponse> {
+ return this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireValidOrg(projectId, orgId);
+ if (!org.byId.has(agentId))
+ throw new HttpError(404, "employee_not_found", `${agentId} is not an employee.`);
+ const r = await ensureDesk(this.deps, org, agentId, opts);
+ if (!r.ok) throw new HttpError(409, "desk_unavailable", r.error);
+ return { agentId, ...r.desk };
+ });
+ }
+
+ async handbook(projectId: string, orgId: string): Promise<string> {
+ const org = await this.requireOrg(projectId, orgId);
+ return this.deps.store.readHandbook(org.dir);
+ }
+
+ async writeHandbook(projectId: string, orgId: string, content: string): Promise<void> {
+ const org = await this.requireOrg(projectId, orgId);
+ await this.deps.store.writeHandbook(org.dir, content);
+ }
+
+ /** The handbook directory is the company's knowledge base; the index is listed first. */
+ async handbookFiles(projectId: string, orgId: string): Promise<OrgHandbookFilesResponse> {
+ const org = await this.requireOrg(projectId, orgId);
+ const files = await this.deps.store.listHandbookFiles(org.dir);
+ return {
+ files: files.map((f) => ({
+ path: f.path,
+ size: f.size,
+ updatedAt: new Date(f.mtimeMs).toISOString(),
+ })),
+ };
+ }
+
+ async handbookFile(
+ projectId: string,
+ orgId: string,
+ rel: string,
+ ): Promise<OrgHandbookFileResponse> {
+ requireHandbookPath(rel);
+ const org = await this.requireOrg(projectId, orgId);
+ const content = await this.deps.store.readHandbookFile(org.dir, rel);
+ if (content === null)
+ throw new HttpError(404, "handbook_file_not_found", `${rel} is not in the handbook.`);
+ return { path: rel, content };
+ }
+
+ async writeHandbookFile(
+ projectId: string,
+ orgId: string,
+ rel: string,
+ content: string,
+ ): Promise<OrgHandbookFileResponse> {
+ requireHandbookPath(rel);
+ const org = await this.requireOrg(projectId, orgId);
+ await this.deps.store.writeHandbookFile(org.dir, rel, content);
+ return { path: rel, content };
+ }
+
+ /** The index stays: it is what every trigger tells the employee to read. */
+ async deleteHandbookFile(projectId: string, orgId: string, rel: string): Promise<void> {
+ requireHandbookPath(rel);
+ if (rel === "README.md")
+ throw new HttpError(
+ 400,
+ "handbook_index_required",
+ "The handbook index (README.md) cannot be deleted.",
+ );
+ const org = await this.requireOrg(projectId, orgId);
+ if ((await this.deps.store.readHandbookFile(org.dir, rel)) === null)
+ throw new HttpError(404, "handbook_file_not_found", `${rel} is not in the handbook.`);
+ await this.deps.store.deleteHandbookFile(org.dir, rel);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Calendar
+ // ---------------------------------------------------------------------------
+
+ private async calendarItems(org: LoadedOrg, spend: OrgSpend): Promise<OrgCalendarResponse> {
+ const files = await this.deps.store.listCalendar(org.dir);
+ const paused = pausedEmployees(this.deps, org, spend.period);
+ const nowMs = this.now();
+ const events: OrgCalendarItem[] = [];
+ const invalidFiles: OrgCalendarResponse["invalidFiles"] = [];
+ for (const f of files) {
+ if (!f.parsed.ok) {
+ invalidFiles.push({ agentId: f.agentId, name: f.name, error: f.parsed.error });
+ continue;
+ }
+ if (!org.byId.has(f.agentId)) {
+ invalidFiles.push({ agentId: f.agentId, name: f.name, error: "belongs to no employee" });
+ continue;
+ }
+ const state = this.deps.cache.findCalendar(org.projectId, org.orgId, f.agentId, f.name);
+ const def = f.parsed.value;
+ const held = org.config.status === "paused" || paused.has(f.agentId);
+ const next = calendarNextFireAt(def, state, nowMs);
+ events.push({
+ agentId: f.agentId,
+ name: f.name,
+ ...(def.title !== undefined ? { title: def.title } : {}),
+ prompt: def.prompt,
+ enabled: def.enabled,
+ startAt: def.startAt,
+ ...(def.period !== undefined ? { period: def.period } : {}),
+ ...(def.endAt !== undefined ? { endAt: def.endAt } : {}),
+ status: calendarStatus(def, state, nowMs),
+ ...(state?.invalidReason ? { invalidReason: state.invalidReason } : {}),
+ ...(next !== undefined ? { nextFireAt: next } : {}),
+ ...(state?.lastFiredAt ? { lastFiredAt: state.lastFiredAt } : {}),
+ ...(state?.lastOutcome ? { lastOutcome: state.lastOutcome } : {}),
+ paused: held,
+ });
+ }
+ return { events, invalidFiles };
+ }
+
+ async calendar(projectId: string, orgId: string): Promise<OrgCalendarResponse> {
+ const org = await this.requireOrg(projectId, orgId);
+ const { tickets } = await listTickets(this.deps, org);
+ const spend = await computeSpend(this.deps, org, tickets);
+ return this.calendarItems(org, spend);
+ }
+
+ async upsertCalendar(
+ projectId: string,
+ orgId: string,
+ agentId: string,
+ name: string,
+ fields: Omit<OrgCalendarUpsertRequest, "agentId" | "name">,
+ opts: { create: boolean },
+ ): Promise<OrgCalendarWriteResponse> {
+ await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireValidOrg(projectId, orgId);
+ if (!org.byId.has(agentId))
+ throw new HttpError(404, "employee_not_found", `${agentId} is not an employee.`);
+ const existing = await this.deps.store.readCalendarEvent(org.dir, agentId, name);
+ if (opts.create && existing !== null) {
+ throw new HttpError(
+ 409,
+ "calendar_event_exists",
+ `Calendar event already exists: ${agentId}/${name}`,
+ );
+ }
+ if (!opts.create && existing === null) {
+ throw new HttpError(
+ 404,
+ "calendar_event_not_found",
+ `Calendar event does not exist: ${agentId}/${name}`,
+ );
+ }
+ const raw = serializeCalendarEvent({
+ ...(fields.title !== undefined ? { title: fields.title } : {}),
+ prompt: fields.prompt,
+ enabled: fields.enabled,
+ startAt: fields.startAt,
+ ...(fields.period !== undefined ? { period: fields.period } : {}),
+ ...(fields.endAt !== undefined ? { endAt: fields.endAt } : {}),
+ });
+ const parsed = parseCalendarEvent(name, raw);
+ if (!parsed.ok) throw badRequest(`Invalid calendar event: ${parsed.error}`);
+ await this.deps.store.writeCalendarEvent(org.dir, agentId, name, raw);
+ });
+ await this.scheduler.reconcile(projectId, orgId);
+ const org = await this.requireOrg(projectId, orgId);
+ const spend = await computeSpend(this.deps, org, (await listTickets(this.deps, org)).tickets);
+ const list = await this.calendarItems(org, spend);
+ const item = list.events.find((e) => e.agentId === agentId && e.name === name);
+ if (!item)
+ throw new HttpError(
+ 404,
+ "calendar_event_not_found",
+ `Calendar event does not exist: ${agentId}/${name}`,
+ );
+ // Advisory, computed over the whole calendar after the write: the rota is a property of
+ // the organization, not of the one event, and the write is never refused for it.
+ const warnings = rotaWarnings(list.events, item, this.now(), org.config.timezone);
+ return { ...item, ...(warnings.length > 0 ? { warnings } : {}) };
+ }
+
+ async deleteCalendar(
+ projectId: string,
+ orgId: string,
+ agentId: string,
+ name: string,
+ ): Promise<void> {
+ await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireOrg(projectId, orgId);
+ const removed = await this.deps.store.deleteCalendarEvent(org.dir, agentId, name);
+ if (!removed)
+ throw new HttpError(
+ 404,
+ "calendar_event_not_found",
+ `Calendar event does not exist: ${agentId}/${name}`,
+ );
+ this.deps.cache.deleteCalendar(projectId, orgId, agentId, name);
+ });
+ }
+
+ // ---------------------------------------------------------------------------
+ // Tickets
+ // ---------------------------------------------------------------------------
+
+ /** `known` is every ticket id in the same listing: a `Parent` naming none is flagged invalid. */
+ private ticketItem(t: LoadedTicket, spend: OrgSpend, known: ReadonlySet<string>): OrgTicketItem {
+ const d = t.doc;
+ const running = d.sessions.some((s) => this.deps.runner.statusOf(s) !== "idle");
+ return {
+ ticketId: t.ticketId,
+ title: d.title,
+ status: d.status,
+ owner: d.owner,
+ ...(d.parent !== undefined ? { parent: d.parent } : {}),
+ notify: d.notify,
+ priority: d.priority,
+ ...(d.due !== undefined ? { due: d.due } : {}),
+ ...(d.blocked !== undefined && d.blocked !== "" ? { blocked: d.blocked } : {}),
+ ...(d.blockedBy !== undefined && d.blockedBy !== "" ? { blockedBy: d.blockedBy } : {}),
+ sessions: d.sessions,
+ running,
+ cost: spend.ticket.get(t.ticketId) ?? 0,
+ ...(d.parent !== undefined && !known.has(d.parent)
+ ? { invalid: `Parent ${d.parent} does not exist` }
+ : {}),
+ };
+ }
+
+ private ticketItems(tickets: readonly LoadedTicket[], spend: OrgSpend): OrgTicketItem[] {
+ const known = new Set(tickets.map((t) => t.ticketId));
+ return tickets.map((t) => this.ticketItem(t, spend, known));
+ }
+
+ async tickets(projectId: string, orgId: string): Promise<OrgTicketsResponse> {
+ const org = await this.requireOrg(projectId, orgId);
+ const { tickets, invalid } = await listTickets(this.deps, org);
+ const spend = await computeSpend(this.deps, org, tickets);
+ const columns = Object.fromEntries(
+ ORG_TICKET_COLUMNS.map((c) => [c, [] as OrgTicketItem[]]),
+ ) as Record<OrgTicketStatus, OrgTicketItem[]>;
+ for (const item of this.ticketItems(tickets, spend)) columns[item.status].push(item);
+ return { columns, invalidFiles: invalid };
+ }
+
+ private async ticketDetail(org: LoadedOrg, ticketId: string): Promise<OrgTicketDetail> {
+ const { tickets } = await listTickets(this.deps, org);
+ const spend = await computeSpend(this.deps, org, tickets);
+ const t = tickets.find((x) => x.ticketId === ticketId);
+ if (!t) throw ticketNotFound(ticketId);
+ const item = this.ticketItem(t, spend, new Set(tickets.map((x) => x.ticketId)));
+ const sessionItems: OrgTicketSessionItem[] = t.doc.sessions.map((sessionId) => {
+ const row = this.deps.sessions.findById(sessionId);
+ return {
+ sessionId,
+ agentId: row?.agentId ?? "",
+ ...(row?.title ? { title: row.title } : {}),
+ status: this.deps.runner.statusOf(sessionId),
+ ...(row?.lastActiveAt ? { lastActiveAt: row.lastActiveAt } : {}),
+ };
+ });
+ const file = await this.deps.store.findTicket(org.dir, ticketId);
+ return {
+ ...item,
+ goal: t.doc.goal,
+ acceptanceCriteria: t.doc.acceptanceCriteria,
+ progress: t.doc.progress,
+ result: t.doc.result,
+ history: t.doc.history,
+ body: file?.raw ?? "",
+ children: tickets.filter((x) => x.doc.parent === ticketId).map((x) => x.ticketId),
+ rolledUpCost: spend.ticketRolledUp.get(ticketId) ?? 0,
+ sessionItems,
+ };
+ }
+
+ async ticket(projectId: string, orgId: string, ticketId: string): Promise<OrgTicketDetail> {
+ const org = await this.requireOrg(projectId, orgId);
+ return this.ticketDetail(org, ticketId);
+ }
+
+ private async requireTicket(org: LoadedOrg, ticketId: string): Promise<LoadedTicket> {
+ if (!TICKET_ID_PATTERN.test(ticketId)) throw ticketNotFound(ticketId);
+ const file = await this.deps.store.findTicket(org.dir, ticketId);
+ if (file === null) throw ticketNotFound(ticketId);
+ if (!file.parsed.ok)
+ throw new HttpError(
+ 409,
+ "ticket_invalid",
+ `Ticket ${ticketId} needs repair: ${file.parsed.error}`,
+ );
+ return { ticketId, column: file.column, relPath: file.relPath, doc: file.parsed.value };
+ }
+
+ /**
+ * Refuses a parent that already sits under the ticket. Nothing downstream survives a loop:
+ * the cost roll-up memoizes after its recursion rather than before, so a two-ticket cycle
+ * recurses to the depth bound and leaves both tickets reporting many times the pair's real
+ * spend. The walk is bounded by the ids it has already seen, so a cycle a hand edit put on
+ * disk cannot hang the request that would refuse to deepen it.
+ */
+ private async requireNoParentCycle(
+ org: LoadedOrg,
+ ticketId: string,
+ parent: string,
+ ): Promise<void> {
+ const seen = new Set<string>();
+ let cur: string | undefined = parent;
+ while (cur !== undefined && !seen.has(cur)) {
+ if (cur === ticketId) throw badRequest(`parent line of ${ticketId} forms a cycle`);
+ seen.add(cur);
+ const file = await this.deps.store.findTicket(org.dir, cur);
+ cur = file !== null && file.parsed.ok ? file.parsed.value.parent : undefined;
+ }
+ }
+
+ private requirePerson(raw: string, label: string): string {
+ const p = parsePrincipal(raw);
+ if (p === null || (p.kind !== "agent" && p.kind !== "user")) {
+ throw badRequest(`${label} must be agent:<id> or user:<id>.`);
+ }
+ return raw.trim();
+ }
+
+ /**
+ * `owner`: the one principal responsible for the ticket. A bare Agent id or `agent:<id>`
+ * has to be an employee and `user:<id>` a Project member — a ticket owned by somebody the
+ * organization does not have is a ticket nobody can be notified about, and nobody can start
+ * a session for.
+ */
+ private requireOwner(org: LoadedOrg, raw: string): string {
+ const value = raw.trim();
+ const parsed = parsePrincipal(value);
+ if (parsed === null && org.byId.has(value)) return agentPrincipal(value);
+ if (parsed?.kind === "agent" && org.byId.has(parsed.id)) return agentPrincipal(parsed.id);
+ if (parsed?.kind === "user" && this.projectUserIds(org).includes(parsed.id)) {
+ return userPrincipal(parsed.id);
+ }
+ throw badRequest(
+ `owner must be an employee of ${org.orgId} (an Agent id or agent:<id>) or a member of this Project (user:<id>): ${raw}`,
+ );
+ }
+
+ /**
+ * The `notify` list a ticket gets when nobody named one: an employee owner is told at its
+ * desk, so it defaults to itself; a person is not, because one @-mention per closed ticket
+ * is a badge nobody asked for — a person who wants to be told lists itself.
+ */
+ private defaultNotify(owner: string): string[] {
+ return defaultTicketNotify(owner);
+ }
+
+ /** One history entry appended to the ticket; every write leaves exactly one. */
+ private recordHistory(
+ doc: TicketDoc,
+ by: string,
+ action: OrgTicketHistoryAction,
+ note?: string,
+ ): void {
+ doc.history = [
+ ...doc.history,
+ {
+ at: new Date(this.now()).toISOString(),
+ by,
+ action,
+ ...(note !== undefined && note !== "" ? { note } : {}),
+ },
+ ];
+ }
+
+ /**
+ * Books the calling session as a contributing session of the ticket. A write that claims
+ * work — a progress line, an edit of the body, the move into `review` — from inside one of
+ * this organization's sessions puts that session on the ticket's `sessions` list, so its
+ * cost is split onto the ticket: a desk that did the work at its own table is at least paid
+ * for out of the ticket's budget. Management writes (accepting, closing, blocking,
+ * unblocking) book nothing — a CEO's desk that accepts twenty tickets has not worked on
+ * twenty tickets. Mutates `doc`; returns the session booked, or null when there was none.
+ */
+ private bookSession(
+ org: LoadedOrg,
+ actor: Actor,
+ doc: TicketDoc,
+ ): { sessionId: string; agentId: string } | null {
+ const sessionId = actor.sessionId;
+ if (sessionId === undefined) return null;
+ const agentId = principalAgentId(this.actorPrincipal(org, actor));
+ if (agentId === null || doc.sessions.includes(sessionId)) return null;
+ doc.sessions = [...doc.sessions, sessionId];
+ return { sessionId, agentId };
+ }
+
+ /** The cache twin of `bookSession`: the projection a write outside a reconcile would not refresh. */
+ private cacheBookedSession(
+ org: LoadedOrg,
+ ticketId: string,
+ booked: { sessionId: string; agentId: string } | null,
+ ): void {
+ if (booked === null) return;
+ this.deps.cache.addTicketSession(
+ org.projectId,
+ org.orgId,
+ ticketId,
+ booked.sessionId,
+ booked.agentId,
+ );
+ }
+
+ /**
+ * The slug half of a new ticket id. `slug` as given always wins, validated against the
+ * pattern the id carries. Otherwise the title is slugified; a title that yields fewer than
+ * two words carries too little meaning to name the work — which is every title written in
+ * a language with no Latin letters — so the Project's model is asked for an English one,
+ * with a single retry when its answer sanitizes to nothing. When there is no model, or it
+ * cannot name it either, the caller is told to pass `--slug` rather than given a ticket
+ * called `t-4f2a`: a ticket id is read by people for the life of the organization.
+ */
+ private async ticketSlug(
+ projectId: string,
+ title: string,
+ requested: string | undefined,
+ ): Promise<string> {
+ if (requested !== undefined && requested.trim() !== "") {
+ const slug = requested.trim().toLowerCase();
+ if (!TICKET_SLUG_PATTERN.test(slug)) {
+ throw badRequest(
+ `slug must be lowercase English words joined by hyphens: ${requested.trim()}`,
+ );
+ }
+ return slug;
+ }
+ const fromTitle = slugify(title);
+ if (fromTitle.includes("-")) return fromTitle;
+ const complete = this.deps.completeOnce;
+ if (complete !== undefined) {
+ const base = ticketSlugPrompt(title);
+ for (const prompt of [base, `${base} ${TICKET_SLUG_RETRY_RULE}`]) {
+ const res = await complete(projectId, prompt);
+ if (!res.ok) {
+ this.deps.log?.(`org: ticket slug for "${title}" fell back: ${res.error}`);
+ break;
+ }
+ const proposed = slugify(firstLine(res.text));
+ if (proposed !== "") return proposed;
+ }
+ }
+ if (fromTitle !== "") return fromTitle;
+ throw new HttpError(
+ 400,
+ "slug_required",
+ "pass --slug: lowercase English words joined by hyphens",
+ );
+ }
+
+ async createTicket(
+ projectId: string,
+ orgId: string,
+ req: OrgTicketCreateRequest,
+ actor: Actor,
+ ): Promise<OrgTicketDetail> {
+ const ticketId = await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireValidOrg(projectId, orgId);
+ const title = req.title.trim();
+ if (title === "") throw badRequest("title must not be empty.");
+ const by = this.actorPrincipal(org, actor);
+ const owner =
+ req.owner !== undefined && req.owner.trim() !== "" ? this.requireOwner(org, req.owner) : by;
+ // The model ask that names an untitled-in-English ticket runs under the organization's
+ // lock: filing a ticket is rare, and a slug settled outside it could collide with one
+ // filed meanwhile.
+ const slug = await this.ticketSlug(projectId, title, req.slug);
+ const date = zonedDate(org.config.timezone, this.now());
+ let id = `${date}-${slug}`;
+ for (let n = 2; (await this.deps.store.findTicket(org.dir, id)) !== null; n++) {
+ id = `${date}-${slug}-${slugSuffix(n)}`;
+ }
+ if (
+ req.parent !== undefined &&
+ (await this.deps.store.findTicket(org.dir, req.parent)) === null
+ ) {
+ throw badRequest(`Parent ticket does not exist: ${req.parent}`);
+ }
+ const notify = (req.notify ?? []).map((n) => this.requirePerson(n, "notify"));
+ const doc: TicketDoc = {
+ title,
+ status: "proposed",
+ owner,
+ ...(req.parent !== undefined ? { parent: req.parent } : {}),
+ notify: notify.length > 0 ? notify : this.defaultNotify(owner),
+ priority: req.priority ?? "P2",
+ ...(req.due !== undefined ? { due: req.due } : {}),
+ sessions: [],
+ history: [],
+ goal: (req.body ?? req.goal ?? "").trim(),
+ acceptanceCriteria: req.body !== undefined ? "" : (req.acceptanceCriteria ?? "").trim(),
+ progress: [],
+ result: "",
+ extra: {},
+ extraSections: [],
+ };
+ this.recordHistory(doc, by, "created");
+ // Filing for somebody else is two facts: who filed it, and who it landed on.
+ if (owner !== by) this.recordHistory(doc, by, "assigned", owner);
+ // Baseline the notice state with no owner, so the owner is noticed as an assignment.
+ this.deps.cache.upsertTicketState({
+ projectId,
+ orgId,
+ ticketId: id,
+ status: "proposed",
+ owner: "",
+ blocked: "",
+ blockedBy: "",
+ });
+ await this.deps.store.writeTicket(org.dir, id, "proposed", doc);
+ this.deps.notifyProject(projectId, {
+ type: "org_ticket",
+ projectId,
+ orgId,
+ ticketId: id,
+ change: "created",
+ });
+ return id;
+ });
+ await this.scheduler.reconcile(projectId, orgId);
+ return this.ticket(projectId, orgId, ticketId);
+ }
+
+ async updateTicket(
+ projectId: string,
+ orgId: string,
+ ticketId: string,
+ req: OrgTicketUpdateRequest,
+ actor: Actor,
+ ): Promise<OrgTicketDetail> {
+ await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireValidOrg(projectId, orgId);
+ const t = await this.requireTicket(org, ticketId);
+ const d = t.doc;
+ const by = this.actorPrincipal(org, actor);
+ // The fields the edit actually changed, for the history entry that records it.
+ const changed: string[] = [];
+ if (req.title !== undefined) {
+ if (req.title.trim() === "") throw badRequest("title must not be empty.");
+ if (d.title !== req.title.trim()) changed.push("title");
+ d.title = req.title.trim();
+ }
+ let assigned: string | null = null;
+ if (req.owner !== undefined && req.owner.trim() !== "") {
+ const owner = this.requireOwner(org, req.owner);
+ if (owner !== d.owner) assigned = owner;
+ d.owner = owner;
+ }
+ if (req.parent === null) {
+ if (d.parent !== undefined) changed.push("parent");
+ delete d.parent;
+ } else if (req.parent !== undefined) {
+ if (
+ req.parent === ticketId ||
+ (await this.deps.store.findTicket(org.dir, req.parent)) === null
+ ) {
+ throw badRequest(`Parent ticket does not exist: ${req.parent}`);
+ }
+ await this.requireNoParentCycle(org, ticketId, req.parent);
+ if (d.parent !== req.parent) changed.push("parent");
+ d.parent = req.parent;
+ }
+ if (req.notify !== undefined) {
+ const notify = req.notify.map((n) => this.requirePerson(n, "notify"));
+ d.notify = notify.length > 0 ? notify : this.defaultNotify(d.owner);
+ changed.push("notify");
+ }
+ if (req.priority !== undefined) {
+ if (d.priority !== req.priority) changed.push("priority");
+ d.priority = req.priority;
+ }
+ if (req.due === null) {
+ if (d.due !== undefined) changed.push("due");
+ delete d.due;
+ } else if (req.due !== undefined) {
+ if (d.due !== req.due) changed.push("due");
+ d.due = req.due;
+ }
+ if (req.goal !== undefined) {
+ if (d.goal !== req.goal.trim()) changed.push("goal");
+ d.goal = req.goal.trim();
+ }
+ if (req.acceptanceCriteria !== undefined) {
+ if (d.acceptanceCriteria !== req.acceptanceCriteria.trim())
+ changed.push("acceptance criteria");
+ d.acceptanceCriteria = req.acceptanceCriteria.trim();
+ }
+ if (req.result !== undefined) {
+ if (d.result !== req.result.trim()) changed.push("result");
+ d.result = req.result.trim();
+ }
+ // An assignment is its own entry; the rest of the edit is one `edited` entry naming
+ // the fields, so a ticket assigned and retitled at once reads as the two things it was.
+ if (assigned !== null) this.recordHistory(d, by, "assigned", assigned);
+ if (changed.length > 0) this.recordHistory(d, by, "edited", changed.join(", "));
+ const booked = this.bookSession(org, actor, d);
+ await this.deps.store.writeTicket(org.dir, ticketId, t.column, d);
+ this.cacheBookedSession(org, ticketId, booked);
+ this.deps.notifyProject(projectId, {
+ type: "org_ticket",
+ projectId,
+ orgId,
+ ticketId,
+ change: "updated",
+ });
+ });
+ await this.scheduler.reconcile(projectId, orgId);
+ return this.ticket(projectId, orgId, ticketId);
+ }
+
+ async moveTicket(
+ projectId: string,
+ orgId: string,
+ ticketId: string,
+ status: OrgTicketStatus,
+ reason: string | undefined,
+ actor: Actor,
+ ): Promise<OrgTicketDetail> {
+ await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireValidOrg(projectId, orgId);
+ if (!isTicketColumn(status)) throw badRequest("status must be a board column.");
+ const t = await this.requireTicket(org, ticketId);
+ if (status === "rejected" && (reason === undefined || reason.trim() === "")) {
+ throw badRequest("Moving a ticket to rejected needs a reason.");
+ }
+ const by = this.actorPrincipal(org, actor);
+ const d = t.doc;
+ const from = t.column;
+ d.status = status;
+ const why = reason?.trim() ?? "";
+ if (why !== "") {
+ d.result = d.result.trim() === "" ? why : `${d.result.trim()}\n\n${why}`;
+ }
+ this.recordHistory(d, by, "moved", why === "" ? status : `${status}: ${why}`);
+ // Handing work in is a claim of work; accepting, closing and rejecting are decisions.
+ const booked = status === "review" ? this.bookSession(org, actor, d) : null;
+ await this.deps.store.moveTicket(org.dir, ticketId, from, status, d);
+ this.cacheBookedSession(org, ticketId, booked);
+ });
+ await this.scheduler.reconcile(projectId, orgId);
+ return this.ticket(projectId, orgId, ticketId);
+ }
+
+ async blockTicket(
+ projectId: string,
+ orgId: string,
+ ticketId: string,
+ reason: string,
+ by: string | undefined,
+ actor: Actor,
+ ): Promise<OrgTicketDetail> {
+ await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireValidOrg(projectId, orgId);
+ const t = await this.requireTicket(org, ticketId);
+ if (reason.trim() === "") throw badRequest("reason must not be empty.");
+ if (by !== undefined && by !== "") {
+ const p = parsePrincipal(by);
+ const isTicket = TICKET_ID_PATTERN.test(by);
+ if (!isTicket && (p === null || (p.kind !== "agent" && p.kind !== "user"))) {
+ throw badRequest("by must be a ticket id or agent:<id> / user:<id>.");
+ }
+ if (isTicket && (await this.deps.store.findTicket(org.dir, by)) === null) {
+ throw badRequest(`Blocking ticket does not exist: ${by}`);
+ }
+ }
+ const d = t.doc;
+ d.blocked = reason.trim();
+ if (by !== undefined && by !== "") d.blockedBy = by.trim();
+ else delete d.blockedBy;
+ this.recordHistory(
+ d,
+ this.actorPrincipal(org, actor),
+ "blocked",
+ `${reason.trim()}${by ? ` (by ${by.trim()})` : ""}`,
+ );
+ await this.deps.store.writeTicket(org.dir, ticketId, t.column, d);
+ });
+ await this.scheduler.reconcile(projectId, orgId);
+ return this.ticket(projectId, orgId, ticketId);
+ }
+
+ async unblockTicket(
+ projectId: string,
+ orgId: string,
+ ticketId: string,
+ actor: Actor,
+ ): Promise<OrgTicketDetail> {
+ await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireValidOrg(projectId, orgId);
+ const t = await this.requireTicket(org, ticketId);
+ const d = t.doc;
+ delete d.blocked;
+ delete d.blockedBy;
+ this.recordHistory(d, this.actorPrincipal(org, actor), "unblocked");
+ await this.deps.store.writeTicket(org.dir, ticketId, t.column, d);
+ });
+ await this.scheduler.reconcile(projectId, orgId);
+ return this.ticket(projectId, orgId, ticketId);
+ }
+
+ async progressTicket(
+ projectId: string,
+ orgId: string,
+ ticketId: string,
+ text: string,
+ actor: Actor,
+ ): Promise<OrgTicketDetail> {
+ await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireValidOrg(projectId, orgId);
+ const t = await this.requireTicket(org, ticketId);
+ const sentence = text.replace(/\s*\n\s*/g, " ").trim();
+ if (sentence === "") throw badRequest("text must not be empty.");
+ // The section is prose: the sentence alone, with who wrote it and when in the history.
+ t.doc.progress = [...t.doc.progress, sentence];
+ this.recordHistory(t.doc, this.actorPrincipal(org, actor), "progress", historyNote(sentence));
+ const booked = this.bookSession(org, actor, t.doc);
+ await this.deps.store.writeTicket(org.dir, ticketId, t.column, t.doc);
+ this.cacheBookedSession(org, ticketId, booked);
+ this.deps.notifyProject(projectId, {
+ type: "org_ticket",
+ projectId,
+ orgId,
+ ticketId,
+ change: "progress",
+ });
+ });
+ return this.ticket(projectId, orgId, ticketId);
+ }
+
+ /**
+ * Opens a ticket session. Who may open one is the ticket's own rule: a person may open a
+ * session for any ticket, naming the employee with `agentId`; an employee may open one
+ * only for a ticket it owns. A desk that wants a colleague's ticket worked assigns it and
+ * lets that desk pick it up in its next sweep — an assignment is how work moves between
+ * employees, and a session opened around it leaves the owner with work it never saw. The
+ * owner may still pass `agentId` to enlist a colleague on its OWN ticket, which is how a
+ * request for help in a channel is answered.
+ */
+ async startTicket(
+ projectId: string,
+ orgId: string,
+ ticketId: string,
+ req: { agentId?: string; message?: string; workspace?: string },
+ actor: Actor,
+ ): Promise<{ sessionId: string }> {
+ const sessionId = await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireValidOrg(projectId, orgId);
+ const t = await this.requireTicket(org, ticketId);
+ const owner = principalAgentId(t.doc.owner);
+ const caller = this.actorEmployee(org, actor);
+ if (caller !== null && caller !== owner) {
+ throw new HttpError(
+ 403,
+ "not_ticket_owner",
+ owner === null
+ ? `Only the ticket's owner starts its sessions; ${ticketId} has no employee owner — assign an owner first (\`penguin org ticket assign ${ticketId} --owner agent:<employee>\`) and its desk picks it up in its next sweep.`
+ : `Only the ticket's owner starts its sessions; assign the ticket (\`penguin org ticket assign ${ticketId} --owner agent:<employee>\`) and its desk picks it up in its next sweep.`,
+ );
+ }
+ const agentId = req.agentId ?? owner;
+ if (agentId === null) {
+ throw badRequest("The ticket has no employee owner; pass agentId.");
+ }
+ if (!org.byId.has(agentId))
+ throw new HttpError(404, "employee_not_found", `${agentId} is not an employee.`);
+ const spend = await computeSpend(this.deps, org, (await listTickets(this.deps, org)).tickets);
+ const r = await openTicketSession(this.deps, org, t, agentId, {
+ ...(req.message !== undefined ? { message: req.message } : {}),
+ ...(req.workspace !== undefined ? { workspace: req.workspace } : {}),
+ budget: budgetLine(org, spend, agentId),
+ by: this.actorPrincipal(org, actor),
+ });
+ if (!r.ok) throw new HttpError(409, "ticket_session_failed", r.error);
+ return r.sessionId;
+ });
+ await this.scheduler.reconcile(projectId, orgId, { triggers: false });
+ return { sessionId };
+ }
+
+ async attachTicket(
+ projectId: string,
+ orgId: string,
+ ticketId: string,
+ sessionId: string,
+ actor: Actor,
+ ): Promise<OrgTicketDetail> {
+ await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireValidOrg(projectId, orgId);
+ const t = await this.requireTicket(org, ticketId);
+ const row = this.deps.sessions.findById(sessionId);
+ if (!row || row.projectId !== projectId)
+ throw new HttpError(404, "session_not_found", `Session does not exist: ${sessionId}`);
+ // Spend is summed along the reporting line, so a session of an Agent nobody employs
+ // would land on the ticket's total and in no employee's cumulative — invisible to the
+ // CEO's cap and to the warn and pause that hang off it. Booking a session implicitly
+ // is employee-gated already; attaching one by hand is held to the same rule.
+ if (!org.byId.has(row.agentId)) {
+ throw new HttpError(
+ 400,
+ "not_employee_session",
+ `${sessionId} belongs to ${row.agentId}, who is not an employee of ${org.orgId}.`,
+ );
+ }
+ if (!t.doc.sessions.includes(sessionId)) {
+ t.doc.sessions = [...t.doc.sessions, sessionId];
+ this.recordHistory(t.doc, this.actorPrincipal(org, actor), "session_attached", sessionId);
+ await this.deps.store.writeTicket(org.dir, ticketId, t.column, t.doc);
+ this.deps.cache.addTicketSession(projectId, orgId, ticketId, sessionId, row.agentId);
+ this.deps.notifyProject(projectId, {
+ type: "org_ticket",
+ projectId,
+ orgId,
+ ticketId,
+ change: "attached",
+ });
+ }
+ });
+ return this.ticket(projectId, orgId, ticketId);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Channels
+ // ---------------------------------------------------------------------------
+
+ /** Who is asking: an employee when the call came from one of its sessions, else the signed-in person. */
+ private caller(
+ org: LoadedOrg,
+ actor: Actor,
+ ): { principal: string; agentId: string | null; userId: string | null } {
+ const principal = this.actorPrincipal(org, actor);
+ const agentId = principalAgentId(principal);
+ return { principal, agentId, userId: agentId === null ? actor.userId : null };
+ }
+
+ /** The Project's people: its owner and its members, the `user:` half of the all-hands channel. */
+ private projectUserIds(org: LoadedOrg): string[] {
+ const project = this.deps.projects.findById(org.projectId);
+ const out: string[] = [];
+ for (const id of [
+ ...(project ? [project.ownerUserId] : []),
+ ...this.deps.members.list(org.projectId).map((m) => m.userId),
+ ]) {
+ if (!out.includes(id)) out.push(id);
+ }
+ return out;
+ }
+
+ /** A channel's membership as principals: the all-hands channel resolves to everyone, the rest to their list. */
+ private channelMemberPrincipals(org: LoadedOrg, cfg: ChannelConfig): string[] {
+ if (cfg.everyone !== true) return cfg.members ?? [];
+ return [
+ ...org.chart.employees.map((e) => agentPrincipal(e.agentId)),
+ ...this.projectUserIds(org).map(userPrincipal),
+ ];
+ }
+
+ /**
+ * The channel's config, or 404. An unparsable `channel.toml` is skipped everywhere else,
+ * so it is not there to be read or written either; the reason travels in the message
+ * rather than in a second error code.
+ */
+ private async requireChannel(org: LoadedOrg, channelId: string): Promise<ChannelConfig> {
+ if (!isChannelId(channelId)) throw channelNotFound(channelId);
+ const file = await this.deps.store.readChannel(org.dir, channelId);
+ if (file === null) throw channelNotFound(channelId);
+ if (!file.parsed.ok) {
+ throw new HttpError(
+ 404,
+ "channel_not_found",
+ `Channel ${channelId} has an invalid channel.toml: ${file.parsed.error}`,
+ );
+ }
+ return file.parsed.value;
+ }
+
+ /** The last message's time, plus the caller's unread counts when the caller is a person. */
+ private async channelActivity(
+ org: LoadedOrg,
+ channelId: string,
+ userId: string | null,
+ ): Promise<{ unread: number; mentionsMe: number; lastMessageAt: string | null }> {
+ const days = await this.deps.store.listMessageDays(org.dir, channelId);
+ let lastMessageAt: string | null = null;
+ for (const d of days) {
+ const list = (await this.deps.store.readMessageDay(org.dir, channelId, d)).messages;
+ if (list.length > 0) {
+ lastMessageAt = list.at(-1)!.time;
+ break;
+ }
+ }
+ // Read cursors belong to people; an employee reads its channel through its trigger.
+ if (userId === null) return { unread: 0, mentionsMe: 0, lastMessageAt };
+ const lastReadId = this.deps.cache.readCursor(org.projectId, org.orgId, channelId, userId);
+ const counts = await this.countUnread(org, channelId, days, userPrincipal(userId), lastReadId);
+ return { ...counts, lastMessageAt };
+ }
+
+ /**
+ * What one person has not read in a channel, and how much of it names them. Two rules the
+ * loop is here to keep in one place:
+ *
+ * A person's own lines are never unread. Only `markRead` moves the cursor, so posting from
+ * the CLI — or from the Web App when the read that follows a post does not land — would
+ * otherwise leave a person with a badge counting what they just wrote.
+ *
+ * The walk stops at the read cursor, not at a fixed number of files. Days come newest
+ * first and only days with messages have one, so a count that stopped after seven of them
+ * silently truncated anyone who last read more than seven *active* days ago — the normal
+ * case for an organization left running for weeks. Ids sort in write order, so the first
+ * day holding anything at or before the cursor is the cursor's own day and every older day
+ * is read through. A person who has read nothing has no day to stop at: the whole channel
+ * is unread and the whole (finite) day list is walked, which is the same bound with the
+ * cursor at the beginning of time.
+ */
+ private async countUnread(
+ org: LoadedOrg,
+ channelId: string,
+ days: readonly string[],
+ me: string,
+ lastReadId: string | null,
+ loaded?: { date: string; messages: OrgChannelMessage[] },
+ ): Promise<{ unread: number; mentionsMe: number }> {
+ let unread = 0;
+ let mentionsMe = 0;
+ for (const d of days) {
+ const list =
+ loaded !== undefined && loaded.date === d
+ ? loaded.messages
+ : (await this.deps.store.readMessageDay(org.dir, channelId, d)).messages;
+ let reachedCursor = false;
+ for (const m of list) {
+ if (lastReadId !== null && m.id <= lastReadId) {
+ reachedCursor = true;
+ continue;
+ }
+ if (m.sender === me) continue;
+ unread++;
+ if (m.mentions.includes(me)) mentionsMe++;
+ }
+ if (reachedCursor) break;
+ }
+ return { unread, mentionsMe };
+ }
+
+ private async channelItem(
+ org: LoadedOrg,
+ channelId: string,
+ cfg: ChannelConfig,
+ caller: { principal: string; userId: string | null },
+ ): Promise<OrgChannelItem> {
+ const members = this.channelMemberPrincipals(org, cfg);
+ return {
+ channelId,
+ name: cfg.name,
+ purpose: cfg.purpose,
+ everyone: cfg.everyone === true,
+ archived: cfg.archived,
+ createdBy: cfg.createdBy,
+ createdAt: cfg.createdAt,
+ memberCount: members.length,
+ isMember: members.includes(caller.principal),
+ ...(await this.channelActivity(org, channelId, caller.userId)),
+ };
+ }
+
+ private async channelMembers(org: LoadedOrg, cfg: ChannelConfig): Promise<OrgChannelMember[]> {
+ const out: OrgChannelMember[] = [];
+ for (const principal of this.channelMemberPrincipals(org, cfg)) {
+ const parsed = parsePrincipal(principal);
+ if (parsed?.kind === "agent") {
+ const name = (await this.deps.agents.exists(org.projectId, parsed.id))
+ ? await this.deps.agents.displayName(org.projectId, parsed.id)
+ : parsed.id;
+ out.push({ principal, name, kind: "agent" });
+ } else if (parsed?.kind === "user") {
+ out.push({ principal, name: parsed.id, kind: "user" });
+ }
+ }
+ return out;
+ }
+
+ private async channelDetail(
+ org: LoadedOrg,
+ channelId: string,
+ cfg: ChannelConfig,
+ caller: { principal: string; userId: string | null },
+ ): Promise<OrgChannelDetail> {
+ return {
+ ...(await this.channelItem(org, channelId, cfg, caller)),
+ members: await this.channelMembers(org, cfg),
+ };
+ }
+
+ /** People are the board and see every channel; an employee sees the channels it belongs to. */
+ async channels(projectId: string, orgId: string, actor: Actor): Promise<OrgChannelsResponse> {
+ const org = await this.requireOrg(projectId, orgId);
+ const caller = this.caller(org, actor);
+ const channels: OrgChannelItem[] = [];
+ for (const file of await this.deps.store.listChannels(org.dir)) {
+ if (!file.parsed.ok) continue;
+ const item = await this.channelItem(org, file.channelId, file.parsed.value, caller);
+ if (caller.agentId !== null && !item.isMember) continue;
+ channels.push(item);
+ }
+ channels.sort((a, b) =>
+ a.channelId === DEFAULT_CHANNEL_ID
+ ? -1
+ : b.channelId === DEFAULT_CHANNEL_ID
+ ? 1
+ : a.name.localeCompare(b.name) || a.channelId.localeCompare(b.channelId),
+ );
+ return { channels };
+ }
+
+ /** A new channel holds exactly its creator; everyone else arrives by invitation (people may also join). */
+ async createChannel(
+ projectId: string,
+ orgId: string,
+ req: OrgChannelCreateRequest,
+ actor: Actor,
+ ): Promise<OrgChannelItem> {
+ const channelId = req.channelId;
+ const item = await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireOrg(projectId, orgId);
+ if (!isChannelId(channelId)) {
+ throw badRequest(
+ "Channel id must be 2–64 characters: a lowercase letter, then lowercase letters, digits or underscores.",
+ );
+ }
+ if ((await this.deps.store.readChannel(org.dir, channelId)) !== null) {
+ throw new HttpError(409, "channel_exists", `Channel id is already taken: ${channelId}`);
+ }
+ const caller = this.caller(org, actor);
+ const cfg: ChannelConfig = {
+ name: req.name?.trim() || channelId,
+ purpose: req.purpose?.trim() ?? "",
+ createdBy: caller.principal,
+ createdAt: new Date(this.now()).toISOString(),
+ archived: false,
+ members: [caller.principal],
+ };
+ await this.deps.store.writeChannel(org.dir, channelId, cfg);
+ await appendChannelMessage(
+ this.deps,
+ org,
+ channelId,
+ systemMessage(channelCreated(caller.principal)),
+ );
+ return this.channelItem(org, channelId, cfg, caller);
+ });
+ await this.scheduler.reconcile(projectId, orgId);
+ return item;
+ }
+
+ async channel(
+ projectId: string,
+ orgId: string,
+ channelId: string,
+ actor: Actor,
+ ): Promise<OrgChannelDetail> {
+ const org = await this.requireOrg(projectId, orgId);
+ const cfg = await this.requireChannel(org, channelId);
+ const caller = this.caller(org, actor);
+ this.requireReadAccess(org, channelId, cfg, caller);
+ return this.channelDetail(org, channelId, cfg, caller);
+ }
+
+ /** People read every channel; an employee only the ones it belongs to. */
+ private requireReadAccess(
+ org: LoadedOrg,
+ channelId: string,
+ cfg: ChannelConfig,
+ caller: { principal: string; agentId: string | null },
+ ): void {
+ if (caller.agentId === null) return;
+ if (this.channelMemberPrincipals(org, cfg).includes(caller.principal)) return;
+ throw notAMember(channelId, caller.principal);
+ }
+
+ async patchChannel(
+ projectId: string,
+ orgId: string,
+ channelId: string,
+ req: OrgChannelPatchRequest,
+ actor: Actor,
+ ): Promise<OrgChannelItem> {
+ const item = await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireOrg(projectId, orgId);
+ const cfg = await this.requireChannel(org, channelId);
+ const caller = this.caller(org, actor);
+ const members = this.channelMemberPrincipals(org, cfg);
+ if (req.archived !== undefined) {
+ if (channelId === DEFAULT_CHANNEL_ID) {
+ throw allHandsImmutable("The all-hands channel cannot be archived.");
+ }
+ if (caller.agentId !== null) {
+ throw notAMember(channelId, caller.principal, "Only people archive a channel.");
+ }
+ }
+ // Everything but lifting the archive itself is refused while the channel is archived.
+ if (cfg.archived && req.archived !== false) throw channelArchived(channelId);
+ const renaming = req.name !== undefined || req.purpose !== undefined;
+ if (renaming && !members.includes(caller.principal)) {
+ throw notAMember(channelId, caller.principal);
+ }
+ const next: ChannelConfig = { ...cfg };
+ if (req.name !== undefined) {
+ if (req.name.trim() === "") throw badRequest("name must not be empty.");
+ next.name = req.name.trim();
+ }
+ if (req.purpose !== undefined) next.purpose = req.purpose.trim();
+ const archiveChanged = req.archived !== undefined && req.archived !== cfg.archived;
+ // The notice is written before the flag: an archived channel is skipped by the scan,
+ // so a line written after it would wait for the unarchive to reach the event stream.
+ if (archiveChanged) {
+ await appendChannelMessage(
+ this.deps,
+ org,
+ channelId,
+ systemMessage(channelArchiveChanged(caller.principal, req.archived === true)),
+ );
+ next.archived = req.archived === true;
+ }
+ await this.deps.store.writeChannel(org.dir, channelId, next);
+ return this.channelItem(org, channelId, next, caller);
+ });
+ await this.scheduler.reconcile(projectId, orgId);
+ return item;
+ }
+
+ /** `agent:<id>` must be an employee and `user:<id>` a Project member — nobody else can be in a channel. */
+ private requireChannelPrincipal(org: LoadedOrg, raw: string): string {
+ const parsed = parsePrincipal(raw);
+ if (parsed?.kind === "agent" && org.byId.has(parsed.id)) return agentPrincipal(parsed.id);
+ if (parsed?.kind === "user" && this.projectUserIds(org).includes(parsed.id)) {
+ return userPrincipal(parsed.id);
+ }
+ throw new HttpError(
+ 400,
+ "invalid_principal",
+ `Not an employee of ${org.orgId} or a member of this Project: ${raw}`,
+ );
+ }
+
+ /** Any member invites; a person may also join by itself, an employee may not. */
+ async addChannelMember(
+ projectId: string,
+ orgId: string,
+ channelId: string,
+ rawPrincipal: string,
+ actor: Actor,
+ ): Promise<OrgChannelDetail> {
+ const detail = await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireOrg(projectId, orgId);
+ const cfg = await this.requireChannel(org, channelId);
+ if (channelId === DEFAULT_CHANNEL_ID) {
+ throw allHandsImmutable("Everyone is in the all-hands channel already.");
+ }
+ if (cfg.archived) throw channelArchived(channelId);
+ const principal = this.requireChannelPrincipal(org, rawPrincipal);
+ const caller = this.caller(org, actor);
+ const members = cfg.members ?? [];
+ if (principal === caller.principal) {
+ if (caller.agentId !== null) {
+ throw notAMember(
+ channelId,
+ caller.principal,
+ "An employee joins a channel only when a member invites it.",
+ );
+ }
+ } else if (!members.includes(caller.principal)) {
+ throw notAMember(channelId, caller.principal);
+ }
+ if (members.includes(principal)) return this.channelDetail(org, channelId, cfg, caller);
+ const next: ChannelConfig = { ...cfg, members: [...members, principal] };
+ await this.deps.store.writeChannel(org.dir, channelId, next);
+ await appendChannelMessage(
+ this.deps,
+ org,
+ channelId,
+ systemMessage(channelMemberAdded(caller.principal, principal)),
+ );
+ return this.channelDetail(org, channelId, next, caller);
+ });
+ await this.scheduler.reconcile(projectId, orgId);
+ return detail;
+ }
+
+ /** A member removes itself; a person may remove anyone. Removing a non-member changes nothing. */
+ async removeChannelMember(
+ projectId: string,
+ orgId: string,
+ channelId: string,
+ rawPrincipal: string,
+ actor: Actor,
+ ): Promise<void> {
+ await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireOrg(projectId, orgId);
+ const cfg = await this.requireChannel(org, channelId);
+ if (channelId === DEFAULT_CHANNEL_ID) {
+ throw allHandsImmutable("Nobody leaves the all-hands channel.");
+ }
+ if (cfg.archived) throw channelArchived(channelId);
+ const parsed = parsePrincipal(rawPrincipal);
+ if (parsed?.kind !== "agent" && parsed?.kind !== "user") {
+ throw new HttpError(400, "invalid_principal", `Not a principal: ${rawPrincipal}`);
+ }
+ const principal =
+ parsed.kind === "agent" ? agentPrincipal(parsed.id) : userPrincipal(parsed.id);
+ const caller = this.caller(org, actor);
+ if (caller.agentId !== null && principal !== caller.principal) {
+ throw notAMember(
+ channelId,
+ caller.principal,
+ "An employee removes only itself from a channel.",
+ );
+ }
+ const members = cfg.members ?? [];
+ if (!members.includes(principal)) return;
+ await this.deps.store.writeChannel(org.dir, channelId, {
+ ...cfg,
+ members: members.filter((m) => m !== principal),
+ });
+ await appendChannelMessage(
+ this.deps,
+ org,
+ channelId,
+ systemMessage(channelMemberRemoved(caller.principal, principal)),
+ );
+ });
+ await this.scheduler.reconcile(projectId, orgId);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Channel messages
+ // ---------------------------------------------------------------------------
+
+ async channelMessages(
+ projectId: string,
+ orgId: string,
+ actor: Actor,
+ channelId: string,
+ opts: { date?: string },
+ ): Promise<OrgChannelMessagesResponse> {
+ const org = await this.requireOrg(projectId, orgId);
+ const cfg = await this.requireChannel(org, channelId);
+ const caller = this.caller(org, actor);
+ this.requireReadAccess(org, channelId, cfg, caller);
+ const days = await this.deps.store.listMessageDays(org.dir, channelId);
+ const today = zonedDate(org.config.timezone, this.now());
+ const date = opts.date ?? today;
+ const messages = (await this.deps.store.readMessageDay(org.dir, channelId, date)).messages;
+ const lastReadId =
+ caller.userId === null
+ ? null
+ : this.deps.cache.readCursor(projectId, orgId, channelId, caller.userId);
+ const me = caller.userId === null ? null : userPrincipal(caller.userId);
+ const { unread, mentionsMe } =
+ me === null
+ ? { unread: 0, mentionsMe: 0 }
+ : await this.countUnread(org, channelId, days, me, lastReadId, { date, messages });
+ return {
+ channelId,
+ date,
+ days,
+ messages,
+ unread,
+ mentionsMe,
+ ...(lastReadId !== null ? { lastReadId } : {}),
+ };
+ }
+
+ /** Resolves `@` tokens: employees first, then Project members; the writer disambiguates with a prefix. */
+ private resolveMentions(org: LoadedOrg, text: string): string[] {
+ const users = new Set(this.projectUserIds(org));
+ const out: string[] = [];
+ const add = (p: string): void => {
+ if (!out.includes(p)) out.push(p);
+ };
+ for (const token of extractMentionTokens(text)) {
+ if (token.id === "all" && token.prefix === undefined) {
+ add("all");
+ continue;
+ }
+ if (token.prefix === "agent") {
+ if (org.byId.has(token.id)) add(agentPrincipal(token.id));
+ } else if (token.prefix === "user") {
+ if (users.has(token.id)) add(userPrincipal(token.id));
+ } else if (org.byId.has(token.id)) {
+ add(agentPrincipal(token.id));
+ } else if (users.has(token.id)) {
+ add(userPrincipal(token.id));
+ }
+ }
+ return out;
+ }
+
+ async sendChannelMessage(
+ projectId: string,
+ orgId: string,
+ userId: string,
+ channelId: string,
+ req: OrgChannelMessageSendRequest,
+ ): Promise<OrgChannelMessage> {
+ const msg = await this.scheduler.withLock(projectId, orgId, async () => {
+ const org = await this.requireOrg(projectId, orgId);
+ const text = req.text.trim();
+ if (text === "") throw badRequest("text must not be empty.");
+ const cfg = await this.requireChannel(org, channelId);
+ if (cfg.archived) throw channelArchived(channelId);
+ let sender = userPrincipal(userId);
+ let hop = 0;
+ if (req.sessionId !== undefined) {
+ const owner = this.deps.cache.ownerOfSession(req.sessionId);
+ if (owner && owner.projectId === projectId && owner.orgId === orgId) {
+ sender = agentPrincipal(owner.agentId);
+ hop = owner.triggerHop + 1;
+ } else {
+ const row = this.deps.sessions.findById(req.sessionId);
+ if (row && row.projectId === projectId && org.byId.has(row.agentId)) {
+ sender = agentPrincipal(row.agentId);
+ hop = 1;
+ }
+ }
+ }
+ const members = this.channelMemberPrincipals(org, cfg);
+ if (!members.includes(sender)) throw notAMember(channelId, sender);
+ const mentions = this.resolveMentions(org, text);
+ // `@all` is the channel's own membership, so only named principals can be outsiders.
+ const outsiders = mentions.filter((m) => m !== "all" && !members.includes(m));
+ if (outsiders.length > 0) {
+ throw new HttpError(
+ 400,
+ "mention_not_member",
+ `Not a member of ${channelId}: ${outsiders.join(", ")}. Invite them first, or write in a channel they are in.`,
+ );
+ }
+ const refs = req.refs;
+ return appendChannelMessage(this.deps, org, channelId, {
+ sender,
+ hop,
+ text,
+ mentions,
+ ...(refs !== undefined && Object.keys(refs).length > 0 ? { refs } : {}),
+ });
+ });
+ await this.scheduler.reconcile(projectId, orgId);
+ return msg;
+ }
+
+ async markRead(
+ projectId: string,
+ orgId: string,
+ userId: string,
+ channelId: string,
+ upTo: string,
+ ): Promise<void> {
+ const org = await this.requireOrg(projectId, orgId);
+ await this.requireChannel(org, channelId);
+ const current = this.deps.cache.readCursor(projectId, orgId, channelId, userId);
+ if (current === null || upTo > current)
+ this.deps.cache.setReadCursor(projectId, orgId, channelId, userId, upTo);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Finance and sessions
+ // ---------------------------------------------------------------------------
+
+ async finance(projectId: string, orgId: string, period?: string): Promise<OrgFinanceResponse> {
+ const org = await this.requireOrg(projectId, orgId);
+ const { tickets } = await listTickets(this.deps, org);
+ const spend = await computeSpend(this.deps, org, tickets, period);
+ const marks = new Map(
+ this.deps.cache.listBudgetStates(projectId, orgId, spend.period).map((s) => [s.agentId, s]),
+ );
+ const employees: OrgFinanceResponse["employees"] = [];
+ for (const e of org.chart.employees) {
+ const cumulative = spend.cumulative.get(e.agentId) ?? 0;
+ const mark = marks.get(e.agentId);
+ employees.push({
+ agentId: e.agentId,
+ name: (await this.deps.agents.exists(projectId, e.agentId))
+ ? await this.deps.agents.displayName(projectId, e.agentId)
+ : e.agentId,
+ title: e.title,
+ reportsTo: e.reportsTo,
+ own: spend.own.get(e.agentId) ?? 0,
+ cumulative,
+ ...(e.budget !== undefined
+ ? { budget: e.budget, ratio: budgetRatio(cumulative, e.budget) }
+ : {}),
+ warned: mark?.warnedAt !== undefined && mark.warnedAt !== null,
+ paused: mark?.pausedAt !== undefined && mark.pausedAt !== null,
+ });
+ }
+ const daily = await this.deps.usage.dailyCostForSessions(
+ projectId,
+ spend.sessionIds,
+ new Date(spend.range.fromMs).toISOString(),
+ new Date(spend.range.toMs - 1).toISOString(),
+ );
+ return {
+ period: spend.period,
+ currency: "USD",
+ employees,
+ tickets: tickets.map((t) => ({
+ ticketId: t.ticketId,
+ title: t.doc.title,
+ status: t.doc.status,
+ ...(t.doc.parent !== undefined ? { parent: t.doc.parent } : {}),
+ cost: spend.ticket.get(t.ticketId) ?? 0,
+ rolledUp: spend.ticketRolledUp.get(t.ticketId) ?? 0,
+ })),
+ daily,
+ alerts: this.alerts(org, spend.period),
+ total: spend.cumulative.get(ceoAgentId(orgId)) ?? 0,
+ unpriced: spend.unpriced,
+ };
+ }
+
+ async sessions(projectId: string, orgId: string): Promise<OrgSessionsResponse> {
+ const org = await this.requireOrg(projectId, orgId);
+ const { tickets } = await listTickets(this.deps, org);
+ syncCaches(this.deps, org, tickets);
+ const desks: OrgSessionsResponse["desks"] = [];
+ for (const e of org.chart.employees) {
+ const desk = org.desks[e.agentId];
+ if (!desk) continue;
+ const row = this.deps.sessions.findById(desk.sessionId);
+ desks.push({
+ agentId: e.agentId,
+ name: (await this.deps.agents.exists(projectId, e.agentId))
+ ? await this.deps.agents.displayName(projectId, e.agentId)
+ : e.agentId,
+ sessionId: desk.sessionId,
+ ...(row?.title ? { title: row.title } : {}),
+ status: this.deps.runner.statusOf(desk.sessionId),
+ workspace: desk.workspace,
+ ...(row?.lastActiveAt ? { lastActiveAt: row.lastActiveAt } : {}),
+ });
+ }
+ const ticketGroups: OrgSessionsResponse["tickets"] = [];
+ for (const t of tickets) {
+ if (t.doc.sessions.length === 0) continue;
+ ticketGroups.push({
+ ticketId: t.ticketId,
+ title: t.doc.title,
+ status: t.doc.status,
+ sessions: t.doc.sessions.map((sessionId) => {
+ const row = this.deps.sessions.findById(sessionId);
+ return {
+ sessionId,
+ agentId: row?.agentId ?? "",
+ ...(row?.title ? { title: row.title } : {}),
+ status: this.deps.runner.statusOf(sessionId),
+ ...(row?.lastActiveAt ? { lastActiveAt: row.lastActiveAt } : {}),
+ };
+ }),
+ });
+ }
+ return { desks, tickets: ticketGroups };
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Texts
+// ---------------------------------------------------------------------------
+
+function requireHandbookPath(rel: string): void {
+ if (!isHandbookFilePath(rel))
+ throw new HttpError(
+ 400,
+ "invalid_path",
+ `${rel} is not a handbook path: plain segments, no hidden files, no traversal.`,
+ );
+}
+
+/** How many rows one inbox list carries: a page, the same cap the overview renders. */
+const INBOX_PAGE = 20;
+
+/** The `note` a `moved` history entry carries when a ticket lands in `done`, reason or not. */
+const MOVED_TO_DONE = /^done(?::|$)/;
+
+/**
+ * The time a ticket last moved into `done`, from its history. Null when the history has no
+ * such entry, which is what a ticket moved by editing its file — or one converted from the
+ * format that predates the history — looks like.
+ */
+function lastClosedAt(doc: TicketDoc): string | null {
+ for (let i = doc.history.length - 1; i >= 0; i -= 1) {
+ const entry = doc.history[i]!;
+ if (entry.action === "moved" && MOVED_TO_DONE.test(entry.note ?? "")) return entry.at;
+ }
+ 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
+ .split("\n")
+ .map((l) => l.trim())
+ .find((l) => l !== "");
+ return (line ?? "").replace(/^[`"'“”‘’]+|[`"'“”‘’.]+$/g, "");
+}
+
+/** Appended on the one retry an unusable slug buys: the answer IS the slug, not a sentence about it. */
+const TICKET_SLUG_RETRY_RULE =
+ "Answer with the slug only — lowercase English words joined by hyphens, nothing else.";
+
+/**
+ * The prompt behind a model-named ticket slug. A ticket id is read by people for the life of
+ * the organization, so the ask is for words that name the work rather than a transliteration:
+ * the common case is a Chinese title, which nothing mechanical can turn into English.
+ */
+function ticketSlugPrompt(title: string): string {
+ return [
+ "You name work items. Given a ticket title, answer with ONE slug of 2–5 English words in",
+ "kebab-case: lowercase ASCII letters joined by hyphens, no digits, no explanation, nothing",
+ "else. Translate a non-English title rather than transliterating it. Examples:",
+ "上线站点 → launch-the-site; 季度财报 → quarterly-financial-report; 招募前端 →",
+ "hire-a-frontend-engineer.",
+ `Title: ${title}`,
+ ].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;
+ name: string;
+ mission: string;
+ agentId: string;
+ title: string;
+ reportsTo: string | null;
+ language: OrgLanguage;
+ duties?: string;
+}): string {
+ if (input.language === "zh") {
+ return `# 员工简介
+
+你是 \`${input.agentId}\`,组织 **${input.name}**(\`${input.orgId}\`)的${input.title},向${input.reportsTo === null ? "董事会" : `\`${input.reportsTo}\``}汇报。
+
+使命:${input.mission}
+${input.duties !== undefined ? `\n职责:${input.duties}\n` : ""}
+本组织的工作语言是中文:频道消息、工单、手册文档与汇报都用中文书写,命令、文件名、id 与字段名保持 ASCII。
+
+你的组织目录是 \`<app_data_dir>/organizations/${input.orgId}/\`。每轮工作开始时先读 \`handbook/README.md\`(组织手册的索引;这个目录是公司的知识库),然后按 \`company-employee\` Skill 行事;头衔属于哪个角色,就再用 \`company-ceo\`、\`company-hr\` 或 \`company-finance\`。在你的会话里,\`penguin org\` 命令已经从环境中知道你的组织、Project、Agent 与当前会话。
+`;
+ }
+ return `# Employee brief
+
+You are \`${input.agentId}\`, ${input.title} of the organization **${input.name}** (\`${input.orgId}\`), reporting to ${input.reportsTo === null ? "the board" : `\`${input.reportsTo}\``}.
+
+Mission: ${input.mission}
+${input.duties !== undefined ? `\nDuties: ${input.duties}\n` : ""}
+This organization works in English: channel messages, tickets, handbook documents and reports are written in it; commands, file names, ids and field names stay ASCII.
+
+Your organization directory is \`<app_data_dir>/organizations/${input.orgId}/\`. At the start of every work run read \`handbook/README.md\` (the handbook index; the directory is the company's knowledge base), then follow the \`company-employee\` skill; use \`company-ceo\`, \`company-hr\` or \`company-finance\` when your title is that role. Inside your sessions the \`penguin org\` commands already know your organization, Project, Agent and session from the environment.
+`;
+}
+
+/** The body of the CEO's initialization work run, in the organization's working language. */
+function initBody(org: LoadedOrg): string {
+ const board = userPrincipal(org.config.createdBy);
+ const ceo = ceoAgentId(org.orgId);
+ if (orgLanguage(org.config) === "zh") {
+ return [
+ `使命:${org.config.mission}`,
+ "",
+ "如果上面的使命说的是「镜像一家现实公司」——为现实同事各建一个数字分身、公司只负责传话——就改按 `company-mirror` Skill 行事,跳过下面这份清单。",
+ "",
+ "你是一家全新组织的 CEO,这是它的初始化运行。重要的事由董事会拍板,你负责提案。按顺序完成下面几件事:",
+ `1. 读手册。然后在全员频道里给董事会(${board})写一份提案——\`penguin org channel send -m "@${board} …"\`——写清你对使命的理解、打算开的工作线与首批工单、打算招募的角色(先人事与财务)及其预算与 Model,以及公共工作区怎么划分。以明确的问题结尾,然后结束本轮:董事会答复之前不招人、不排日程、不开工单。`,
+ `2. 答复会以提及或本会话消息的形式到来。董事会确认后,先招人事与财务——\`penguin org hire --new-agent ${org.orgId}_hr --title HR --reports-to ${ceo} --duties "…"\`,\`${org.orgId}_finance\` 同理——再招确认过的其他角色。`,
+ "3. 按确认的方案划分公共工作区。你自己在 `ceo/` 里工作,招募时不给 `--workspace` 的员工落在以其 Agent id 命名的子目录里,公共工作区的根目录只放大家共读的共享输入、不是任何人的工位。要换个分区名字再单独分配(`penguin org employee set <agent_id> --workspace <子目录>`);相对子目录会在分配时自动建好。",
+ "4. 把你自己、人事与财务排进日历(`penguin org calendar add …`),做成轮值表而不是广播:你每天 09:00,人事每三天 10:00,财务每周 16:00(组织时区,写成带偏移量的 ISO 时刻,绝不用 `--start-at now`),此后每招一人就给它一个各自不同的时点。",
+ "5. 把确认过的工单开进 `proposed`(`penguin org ticket create …`):一个项目级目标一张父工单,每条工作线一张子工单。接受一张工单进入 `in_progress` 时就指派负责人(`penguin org ticket assign <id> --owner agent:<员工>`):那名员工的工位会在下一次巡检时接手并发起工单会话。只有工单的负责人可以为它发起会话,所以你只为自己名下的工单执行 `penguin org ticket start <id>`;工位只负责调度与跟踪,绝不在工位上做工单本身的活。",
+ "6. 每条工作线开一个频道(`penguin org channel create ch_<工作线> --name …`)并邀请它的负责人(`penguin org channel invite ch_<工作线> agent:<agent_id>`),免得一条线索淹没全员频道。",
+ `7. 在全员频道里向董事会汇报并 @${board},如果还需要拍板,就点明下一个决定。`,
+ ].join("\n");
+ }
+ return [
+ `Mission: ${org.config.mission}`,
+ "",
+ "If the mission above says the organization MIRRORS a real company — one digital twin per real colleague, a company that only relays between people — follow the `company-mirror` skill instead and skip the checklist below.",
+ "",
+ "You are the CEO of a brand-new organization and this is its initialization run. The board decides the important things; you propose. Work through the following, in order:",
+ `1. Read the handbook. Then write ONE proposal to the board (${board}) in the all-hands channel — \`penguin org channel send -m "@${board} …"\` — with your reading of the mission, the streams and first tickets you intend to file, the roles you intend to hire (HR and finance first) with budgets and model, and how you will split the shared workspace. End with the explicit question and END THIS RUN: hire nothing, schedule nothing and file nothing before the board answers.`,
+ `2. The answer arrives as a mention or in this conversation. Once the board confirms, hire HR and finance first — \`penguin org hire --new-agent ${org.orgId}_hr --title HR --reports-to ${ceo} --duties "…"\` and the same for \`${org.orgId}_finance\` — then the confirmed roles.`,
+ "3. Partition the shared workspace as confirmed. You already work in `ceo/`, and a hire given no `--workspace` lands in a sub-directory named after its Agent id; the root of the shared workspace holds the shared inputs everyone reads and is nobody's desk. Assign a different sub-directory where a partition should be named for the stream rather than the employee (`penguin org employee set <agent_id> --workspace <sub-directory>`); a relative sub-directory is created when you assign it.",
+ "4. Put yourself, HR and finance on the calendar (`penguin org calendar add …`) as a rota, not a broadcast: you daily at 09:00, HR every three days at 10:00, finance weekly at 16:00 (organization timezone, ISO instants with the offset — never `--start-at now`), and give every later hire its own distinct hour.",
+ "5. File the confirmed tickets in `proposed` (`penguin org ticket create …`): one parent ticket for the project-level goal and children per stream. Assign an owner as you accept one into `in_progress` (`penguin org ticket assign <id> --owner agent:<employee>`): that employee's desk picks it up in its next sweep and starts the ticket session itself. Only a ticket's owner may start its sessions, so run `penguin org ticket start <id>` for the tickets you own yourself — the desk schedules and tracks, and never does the ticket work itself.",
+ "6. Open one channel per stream (`penguin org channel create ch_<stream> --name …`) and invite its owner (`penguin org channel invite ch_<stream> agent:<agent_id>`), so a stream's thread does not drown the all-hands channel.",
+ `7. Report to the board in the all-hands channel, mentioning @${board}, and name the next decision you need, if any.`,
+ ].join("\n");
+}
+
+/** Next scheduled fire time, as the schedules route computes it. */
+function calendarNextFireAt(
+ def: ScheduleDefinition,
+ state: {
+ invalidReason: string | null;
+ firedOnce: boolean;
+ missed: boolean;
+ lastSlotMs: number | null;
+ } | null,
+ nowMs: number,
+): string | undefined {
+ if (!def.enabled || state?.invalidReason) return undefined;
+ if (def.periodMs === undefined && state && (state.firedOnce || state.missed)) return undefined;
+ const due = latestSlotAt(def, nowMs);
+ if (
+ due !== null &&
+ slotInWindow(def, due) &&
+ (state === null || state.lastSlotMs === null || due > state.lastSlotMs)
+ ) {
+ return new Date(due).toISOString();
+ }
+ const next = nextSlotAfter(def, nowMs);
+ return next !== null ? new Date(next).toISOString() : undefined;
+}
+
+function calendarStatus(
+ def: ScheduleDefinition,
+ state: { invalidReason: string | null; firedOnce: boolean; missed: boolean } | null,
+ nowMs: number,
+): ScheduleStatus {
+ if (state?.invalidReason) return "invalid";
+ if (def.periodMs === undefined && state?.firedOnce) return "done";
+ if (def.periodMs === undefined && state?.missed) return "missed";
+ if (def.endAtMs !== undefined && nowMs > def.endAtMs) return "expired";
+ return def.enabled ? "active" : "disabled";
+}
+
+/**
+ * What the organization routes need of the runtime — declared where they consume it, so
+ * the route group names one node instead of reaching into a bag.
+ */
+export abstract class OrgService extends Interface<
+ Pick<
+ OrganizationService,
+ | "list"
+ | "create"
+ | "detail"
+ | "patch"
+ | "leave"
+ | "suggestId"
+ | "chart"
+ | "hire"
+ | "patchEmployee"
+ | "desk"
+ | "sessions"
+ | "calendar"
+ | "upsertCalendar"
+ | "deleteCalendar"
+ | "tickets"
+ | "ticket"
+ | "createTicket"
+ | "updateTicket"
+ | "moveTicket"
+ | "blockTicket"
+ | "unblockTicket"
+ | "progressTicket"
+ | "startTicket"
+ | "attachTicket"
+ | "channels"
+ | "channel"
+ | "createChannel"
+ | "patchChannel"
+ | "addChannelMember"
+ | "removeChannelMember"
+ | "channelMessages"
+ | "sendChannelMessage"
+ | "markRead"
+ | "finance"
+ | "handbook"
+ | "writeHandbook"
+ | "handbookFiles"
+ | "handbookFile"
+ | "writeHandbookFile"
+ | "deleteHandbookFile"
+ >
+>() {}
+
+/** The organization scheduler as the boot sequence drives it (the pass itself is internal). */
+export abstract class OrgScheduler extends Interface<
+ Pick<OrganizationScheduler, "start" | "stop">
+>() {}
+
+/**
+ * Company mode's runtime, assembled over the same narrow seams the schedule scheduler
+ * uses: the session manager for run state and task start, SessionService for sessions,
+ * AgentService and AgentConfigService for hiring, UsageService for spend. The scheduler
+ * is started by the platform's Startup component (one reconcile pass, no backfill) and
+ * stopped with this App, like every other timer in the tree.
+ */
+@Module()
+export class OrganizationModule {
+ @Use() private readonly config!: Config;
+ @Use() private readonly channels!: Channels;
+ @Use() private readonly clock!: Clock;
+ @Use() private readonly log!: Log;
+ @Use() private readonly cache!: OrgCache;
+ @Use() private readonly projects!: Projects;
+ @Use() private readonly members!: Members;
+ @Use() private readonly sessionsRepo!: SessionIndex;
+ @Use() private readonly runner!: OrgRuns;
+ @Use() private readonly sessionCreator!: OrgSessions;
+ @Use() private readonly agentService!: AgentLifecycle;
+ @Use() private readonly agentConfig!: AgentConfig;
+ @Use() private readonly agentsRepo!: AgentIndex;
+ @Use() private readonly projectConfig!: ProjectConfigStore;
+ @Use() private readonly usage!: UsageQueries;
+ @Use() private readonly errors!: Errors;
+ @Use() private readonly settings!: Settings;
+ @Provide() orgService!: OrgService;
+ @Provide() orgScheduler!: OrgScheduler;
+ setup({ effect }: ClassCtx) {
+ const channels = this.channels as ChannelHub;
+ const agentService = this.agentService;
+ const agentConfig = this.agentConfig;
+ const agentsRepo = this.agentsRepo;
+ const runner = this.runner;
+ const projectConfig = this.projectConfig;
+ const deps: OrgDeps = {
+ root: this.config.root,
+ store: new OrgStore(this.config.root),
+ cache: this.cache,
+ projects: this.projects,
+ members: this.members,
+ sessions: this.sessionsRepo,
+ runner,
+ sessionCreator: this.sessionCreator,
+ agents: {
+ exists: async (projectId, agentId) =>
+ agentsRepo.exists(projectId, agentId) || agentConfig.exists(projectId, agentId),
+ create: async (projectId, agentId, name, description, plugins) => {
+ await agentService.createAgent(projectId, agentId, name, description, plugins);
+ },
+ displayName: async (projectId, agentId) =>
+ (await agentConfig.readCardMeta(projectId, agentId)).name ?? agentId,
+ writeAgentsMd: (projectId, agentId, content) =>
+ agentConfig.updateConfig(projectId, agentId, { agentsMd: content }),
+ pluginVersion: (projectId, agentId, plugin) =>
+ agentService.pluginVersion(projectId, agentId, plugin),
+ updatePlugin: async (projectId, agentId, plugin) => {
+ await agentService.updatePlugin(projectId, agentId, plugin);
+ // Same reason the plugins route invalidates: a hook package is bound when a core
+ // Session is built, so a runtime cached for this employee would keep the old set
+ // until it was evicted. A Task in flight keeps what it started with.
+ runner.invalidateAgentRuntimes(projectId, agentId);
+ },
+ },
+ projectConfig,
+ completeOnce: (projectId, prompt) => projectConfig.completeOnce(projectId, prompt),
+ usage: this.usage,
+ errors: this.errors,
+ notifyProject: (projectId, event) => {
+ const ownerUserId = this.projects.findById(projectId)?.ownerUserId;
+ if (ownerUserId === undefined) return;
+ const audience = new Set([
+ ownerUserId,
+ ...this.members.list(projectId).map((m) => m.userId),
+ ]);
+ for (const userId of audience) {
+ channels.peek(userChannelKey(userId))?.publish(event, "server_event");
+ }
+ },
+ companyModeEnabled: () => this.settings.getCompanyMode(),
+ now: () => this.clock.now().getTime(),
+ log: (line: string) => this.log.line(line),
+ };
+ const orgScheduler = new OrganizationScheduler(deps);
+ this.orgScheduler = orgScheduler;
+ this.orgService = new OrganizationService(deps, orgScheduler);
+ // Only active while this App is; the successor's start() reconciles from the files.
+ effect(() => orgScheduler.stop());
+ }
+}
diff --git a/packages/server/src/runtime/organization/triggers.ts b/packages/server/src/runtime/organization/triggers.ts
new file mode 100644
index 00000000..a41b54c2
--- /dev/null
+++ b/packages/server/src/runtime/organization/triggers.ts
@@ -0,0 +1,295 @@
+/**
+ * Delivering work to employees. Every automatic trigger is one user input sent to a
+ * session: an `[org_trigger]` block (built by core's marker module, which also owns the
+ * parser the frontend folds it with) followed by the trigger's content. `ensureDesk` here
+ * is the single way a desk session comes into being — the hire opens one, the reconcile
+ * pass provisions the ones that are missing, a trigger falls back on it, and it renews a
+ * desk when the CEO reassigns a workspace; ticket sessions are opened per start. Both are
+ * stamped `client: "org"` at creation — the durable marker development mode's list reads to
+ * leave them out of it.
+ */
+import { buildOrgTriggerMessage, userText } from "@prismshadow/penguin-core";
+import type { OrgTriggerOrigin } from "@prismshadow/penguin-core";
+import type { TicketDoc } from "../../organization/files.js";
+import { orgLanguage, serializeTicket } from "../../organization/files.js";
+import { agentPrincipal } from "../../organization/principal.js";
+import type { OrgDeps } from "./deps.js";
+import type { LoadedOrg } from "./model.js";
+import { employeeLine, sharedWorkspace } from "./model.js";
+
+/** The desk session's title, in the organization's working language. */
+function deskTitle(org: LoadedOrg, name: string): string {
+ return orgLanguage(org.config) === "zh" ? `${name} 的工位` : `${name}'s desk`;
+}
+
+export interface DeskHandle {
+ sessionId: string;
+ workspace: string;
+ openedAt: string;
+ created: boolean;
+}
+
+export type DeskResult = { ok: true; desk: DeskHandle } | { ok: false; error: string };
+
+/**
+ * The employee's desk session: reused while it exists and still sits in the workspace the
+ * chart resolves to; otherwise (the hire, a desk the pass found missing, a session deleted
+ * by hand or with its Agent, a reassigned workspace, or an explicit renewal) a new one is
+ * opened and the ledger rewritten. The old session stays as history under `previous` so its
+ * cost keeps counting. A relative workspace that is not on disk is created here too — a
+ * hand-edited chart, or the calendar reaching a desk before anyone opened it, must not leave
+ * an employee unable to work over a missing directory.
+ */
+export async function ensureDesk(
+ deps: OrgDeps,
+ org: LoadedOrg,
+ agentId: string,
+ opts: { renew?: boolean } = {},
+): Promise<DeskResult> {
+ const employee = org.byId.get(agentId);
+ if (!employee) return { ok: false, error: `${agentId} is not an employee of ${org.orgId}` };
+ if (!(await deps.agents.exists(org.projectId, agentId))) {
+ return { ok: false, error: `Agent ${agentId} does not exist` };
+ }
+ const shared = sharedWorkspace(org);
+ if (deps.store.workspaceTarget(shared, employee.workspace) === null) {
+ return {
+ ok: false,
+ error: `workspace leaves the shared workspace for ${agentId}: ${employee.workspace}`,
+ };
+ }
+ const workspace = await deps.store.ensureWorkspace(shared, employee.workspace);
+ if (workspace === null) {
+ return {
+ ok: false,
+ error: `workspace directory does not exist for ${agentId}: ${employee.workspace}`,
+ };
+ }
+ const model = employee.model ?? org.config.model;
+ const existing = org.desks[agentId];
+ if (
+ existing &&
+ opts.renew !== true &&
+ existing.workspace === workspace &&
+ deps.sessions.findById(existing.sessionId) !== null
+ ) {
+ return {
+ ok: true,
+ desk: {
+ sessionId: existing.sessionId,
+ workspace: existing.workspace,
+ openedAt: existing.openedAt,
+ created: false,
+ },
+ };
+ }
+ let created: { sessionId: string; workspace: string };
+ try {
+ created = await deps.sessionCreator.createSession({
+ projectId: org.projectId,
+ agentId,
+ workspace,
+ ...(model !== undefined ? { modelId: model.modelId, provider: model.provider } : {}),
+ approvalMode: org.config.approvalMode,
+ client: "org",
+ });
+ } catch (err) {
+ return {
+ ok: false,
+ error: `failed to open a desk session for ${agentId}: ${err instanceof Error ? err.message : String(err)}`,
+ };
+ }
+ const name = await deps.agents.displayName(org.projectId, agentId);
+ // A manual title: the auto-title pass only fills empty titles, so the desk keeps its name.
+ deps.sessions.updateTitle(created.sessionId, deskTitle(org, name));
+ const openedAt = new Date(deps.now?.() ?? Date.now()).toISOString();
+ const previous = existing ? [...existing.previous, existing.sessionId] : [];
+ org.desks[agentId] = {
+ sessionId: created.sessionId,
+ workspace: created.workspace,
+ openedAt,
+ previous,
+ };
+ await deps.store.writeDesks(org.dir, org.desks);
+ syncDeskCache(deps, org);
+ return {
+ ok: true,
+ desk: { sessionId: created.sessionId, workspace: created.workspace, openedAt, created: true },
+ };
+}
+
+/** Projects the ledger into `org_sessions` (current desks and their history). */
+export function syncDeskCache(deps: OrgDeps, org: LoadedOrg): void {
+ const rows: Array<{ sessionId: string; agentId: string; current: boolean }> = [];
+ for (const [agentId, desk] of Object.entries(org.desks)) {
+ rows.push({ sessionId: desk.sessionId, agentId, current: true });
+ for (const prev of desk.previous) rows.push({ sessionId: prev, agentId, current: false });
+ }
+ deps.cache.syncDeskSessions(org.projectId, org.orgId, rows);
+}
+
+export type DeskTrigger = Omit<OrgTriggerOrigin, "org" | "employee" | "budget">;
+
+export type DispatchOutcome = "sent" | "queued" | "skipped";
+
+/**
+ * Sends one work run to an employee's desk: opens the desk if needed, prefixes the block,
+ * queues behind a running Task (`queueIfBusy`: a busy desk never loses a trigger, it works
+ * it next), records the chain hop and notifies the Project's users.
+ */
+export async function dispatchToDesk(
+ deps: OrgDeps,
+ org: LoadedOrg,
+ agentId: string,
+ trigger: DeskTrigger,
+ body: string,
+ opts: { hop: number; budget?: string },
+): Promise<DispatchOutcome> {
+ const desk = await ensureDesk(deps, org, agentId);
+ if (!desk.ok) {
+ deps.errors.record({
+ source: "organization",
+ err: new Error(desk.error),
+ code: "org_desk_unavailable",
+ ctx: { projectId: org.projectId, agentId },
+ });
+ return "skipped";
+ }
+ const origin: OrgTriggerOrigin = {
+ org: org.orgId,
+ employee: employeeLine(org, agentId),
+ ...trigger,
+ ...(opts.budget !== undefined ? { budget: opts.budget } : {}),
+ };
+ const text = buildOrgTriggerMessage(origin, body);
+ let queued = false;
+ try {
+ // sender "server": in the Trace this user turn was injected by the organization scheduler, not typed by a person.
+ const res = await deps.runner.startTask(desk.desk.sessionId, [userText(text, "server")], {
+ queueIfBusy: true,
+ });
+ queued = res.queued === true;
+ } catch (err) {
+ deps.errors.record({
+ source: "organization",
+ err,
+ code: "org_dispatch_failed",
+ ctx: { projectId: org.projectId, agentId, sessionId: desk.desk.sessionId },
+ });
+ return "skipped";
+ }
+ deps.cache.setTriggerHop(desk.desk.sessionId, opts.hop);
+ deps.notifyProject(org.projectId, {
+ type: "org_run",
+ projectId: org.projectId,
+ orgId: org.orgId,
+ agentId,
+ sessionId: desk.desk.sessionId,
+ kind: trigger.kind,
+ });
+ return queued ? "queued" : "sent";
+}
+
+/**
+ * Opens a ticket session: an ordinary session of the employee's Agent in the desk's (or a
+ * chosen) workspace, appended to the ticket's `sessions` list — the fact that makes the
+ * session the ticket's — and started with one input carrying where it stands, the rule that
+ * references and deliverables are named by full path, and the whole ticket. The ticket file
+ * and the cache learn of the session only once the task is away: a start that throws must
+ * leave no session behind for the spend, the history and the `#n` titles to count. `by` is
+ * the principal the `session_started` history entry is recorded under; it defaults to the
+ * employee the session runs as, which is who started it in every path but a person's.
+ */
+export async function openTicketSession(
+ deps: OrgDeps,
+ org: LoadedOrg,
+ ticket: { ticketId: string; column: TicketDoc["status"]; doc: TicketDoc },
+ agentId: string,
+ opts: { message?: string; workspace?: string; budget?: string; by?: string },
+): Promise<{ ok: true; sessionId: string } | { ok: false; error: string }> {
+ const employee = org.byId.get(agentId);
+ if (!employee) return { ok: false, error: `${agentId} is not an employee of ${org.orgId}` };
+ const spec = opts.workspace ?? employee.workspace;
+ const workspace = await deps.store.ensureWorkspace(sharedWorkspace(org), spec);
+ if (workspace === null) {
+ return { ok: false, error: `workspace directory does not exist: ${spec}` };
+ }
+ const model = employee.model ?? org.config.model;
+ let created: { sessionId: string; workspace: string };
+ try {
+ created = await deps.sessionCreator.createSession({
+ projectId: org.projectId,
+ agentId,
+ workspace,
+ ...(model !== undefined ? { modelId: model.modelId, provider: model.provider } : {}),
+ approvalMode: org.config.approvalMode,
+ client: "org",
+ });
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+ // The session joins the ticket in memory first, because the trigger below sends the ticket
+ // as it now stands; nothing is persisted until the task has started.
+ const n = ticket.doc.sessions.length + 1;
+ deps.sessions.updateTitle(created.sessionId, `${ticket.doc.title} #${n}`);
+ ticket.doc.sessions = [...ticket.doc.sessions, created.sessionId];
+ ticket.doc.history = [
+ ...ticket.doc.history,
+ {
+ at: new Date(deps.now?.() ?? Date.now()).toISOString(),
+ by: opts.by ?? agentPrincipal(agentId),
+ action: "session_started",
+ note: created.sessionId,
+ },
+ ];
+ // Messages a ticket session sends carry hop 1: it was opened by a work run, not by a person.
+ deps.cache.setTriggerHop(created.sessionId, 0);
+ const origin: OrgTriggerOrigin = {
+ org: org.orgId,
+ employee: employeeLine(org, agentId),
+ kind: "ticket_work",
+ ticket: ticket.ticketId,
+ ...(opts.budget !== undefined ? { budget: opts.budget } : {}),
+ };
+ // Where the session stands, then the naming rule: colleagues read each other's tickets,
+ // not each other's terminals, so a reference nobody can open is a reference nobody has.
+ const note = opts.message?.trim() ?? "";
+ const body = [
+ `Workspace: ${created.workspace} — the organization is at \`<app_data_dir>/organizations/${org.orgId}/\`.`,
+ "Name every input you rely on and every deliverable you produce by its full path (absolute, or `<app_data_dir>/…`) in your progress lines and in `## Result`; a colleague must be able to open it without asking.",
+ ...(note !== "" ? [`Note from the desk: ${note}`] : []),
+ `The ticket, as filed:\n\n${serializeTicket(ticket.doc).trimEnd()}`,
+ ].join("\n\n");
+ try {
+ await deps.runner.startTask(created.sessionId, [
+ userText(buildOrgTriggerMessage(origin, body), "server"),
+ ]);
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+ // The task is away: the ticket may own the session now.
+ await deps.store.writeTicket(org.dir, ticket.ticketId, ticket.column, ticket.doc);
+ deps.cache.addTicketSession(
+ org.projectId,
+ org.orgId,
+ ticket.ticketId,
+ created.sessionId,
+ agentId,
+ );
+ deps.notifyProject(org.projectId, {
+ type: "org_run",
+ projectId: org.projectId,
+ orgId: org.orgId,
+ agentId,
+ sessionId: created.sessionId,
+ kind: "ticket_work",
+ });
+ deps.notifyProject(org.projectId, {
+ type: "org_ticket",
+ projectId: org.projectId,
+ orgId: org.orgId,
+ ticketId: ticket.ticketId,
+ change: "session_started",
+ });
+ return { ok: true, sessionId: created.sessionId };
+}
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index de9acef7..b660030d 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -95,6 +95,7 @@ import type { Errors, UsageRecording } from "../mechanisms/observability.js";
import type { TraceIndex, TraceIndexStore } from "../mechanisms/traces.js";
import type { Settings } from "../mechanisms/settings.js";
import type { MessagingBindings } from "../mechanisms/messaging.js";
+import type { OrgCache } from "../mechanisms/organization.js";
/**
* 409 for when there's nothing to compact: give the specific reason rather than a
@@ -363,6 +364,27 @@ export interface SessionManagerDeps {
* backfill assumes when it reads MAX(ts) as a session's last activity.
*/
now?: () => Date;
+ /**
+ * Called when a Task starts (or is queued) from a PERSON's input — a message typed in the
+ * Web App, the CLI or a bound messaging bot, as opposed to one the harness injected
+ * (`sender: "server"` / `"harness"`). Company mode uses it to reset the desk's @-chain
+ * accounting: a person's message opens a fresh chain (hop 0), whatever mention last woke
+ * the desk. Optional; unit tests that do not wire it get nothing.
+ */
+ onHumanInput?: (sessionId: string) => void;
+}
+
+/**
+ * Whether a Task's input came from a person: every text payload either carries no sender or
+ * `sender: "user"`. A harness-injected turn (`"server"`, `"harness"`, `"parent_agent"`) on any
+ * message makes the whole input non-human — the org scheduler's trigger and a subagent's
+ * prompt both arrive that way.
+ */
+export function isHumanInput(input: readonly OmniMessage[]): boolean {
+ return input.every((m) => {
+ const p = m.payload as { sender?: string };
+ return p.sender === undefined || p.sender === "user";
+ });
}
/**
@@ -967,6 +989,9 @@ export class SessionManager {
this.assertAgentNotDeleting(sessionId);
this.assertSessionNotDeleting(sessionId);
const entry = await this.ensureEntry(sessionId);
+ // A person's message opens a fresh chain for company mode's hop accounting, whether the
+ // Task starts now or waits in the queue (see SessionManagerDeps.onHumanInput).
+ if (isHumanInput(input)) this.deps.onHumanInput?.(sessionId);
if (entry.status !== "idle" && opts?.queueIfBusy) {
entry.followUps.push({
id: randomUUID(),
@@ -2267,6 +2292,8 @@ export class SessionsModule {
@Use() private readonly projectsRepo!: Projects;
@Use() private readonly membersRepo!: Members;
@Use() private readonly messagingRepo!: MessagingBindings;
+ /** Company-mode caches: which organization owns a Session (read at every command spawn). */
+ @Use() private readonly orgCache!: OrgCache;
@Provide() manager!: Sessions;
@Provide() sessionService!: SessionServiceIface;
@Provide() env!: SessionEnv;
@@ -2280,6 +2307,7 @@ export class SessionsModule {
const errors = this.errors;
const projectConfig = this.projectConfig;
const sandbox = this.sandbox as SandboxService;
+ const orgCache = this.orgCache;
// Which commands run confined, under which policy, by which backend is policy — the
// sandbox module's; core only carries the spawn seam, reached through this getter.
@@ -2295,12 +2323,17 @@ export class SessionsModule {
? "127.0.0.1"
: (loopbackHostRoles(config.host)?.app ?? config.host);
const token = authState.apiToken;
+ const orgId = orgCache.ownerOfSession(ctx.sessionId)?.orgId ?? null;
return {
PENGUIN_API_URL: `http://${host}:${config.port}`,
...(token !== null ? { PENGUIN_API_TOKEN: token } : {}),
PENGUIN_PROJECT_ID: ctx.projectId,
PENGUIN_AGENT_ID: ctx.agentId,
PENGUIN_SESSION_ID: ctx.sessionId,
+ // A desk or ticket session also learns its organization, so `penguin org` needs no
+ // --org-id inside it. Looked up per spawn from the cache the ledger and the tickets
+ // project into.
+ ...(orgId !== null ? { PENGUIN_ORG_ID: orgId } : {}),
};
},
// The directory core puts at the FRONT of PATH for every command an Agent runs (and for
@@ -2347,6 +2380,11 @@ export class SessionsModule {
titles,
log,
notifyProjectUsers,
+ // A person talking to a desk (the chat page, a bound bot) starts a new @-chain: the
+ // desk's next channel message is hop 1 again, whatever mention last woke it.
+ onHumanInput: (sessionId) => {
+ if (orgCache.ownerOfSession(sessionId) !== null) orgCache.setTriggerHop(sessionId, 0);
+ },
now: () => this.clock.now(),
});
const sessionService = new SessionService({
@@ -2368,6 +2406,13 @@ export class SessionsModule {
? enabled.channel
: null;
},
+ // Company mode: which organization owns a Session, so development mode's list can hide
+ // organization sessions and the company sidebar can group its own. The caches are a
+ // projection of the organization's files, rebuilt every reconcile pass, so a row that
+ // has not been projected yet reads as an ordinary Session for one pass — never as the
+ // wrong organization.
+ orgIdOfSession: (sessionId) => orgCache.ownerOfSession(sessionId)?.orgId,
+ orgIdsOfProject: (projectId) => orgCache.orgIdsOfProject(projectId),
pathPrepend: env.pathPrepend,
confineSpawn: env.confineSpawn,
});
diff --git a/packages/server/src/services/agent-service.ts b/packages/server/src/services/agent-service.ts
index 647a2066..5059c4a0 100644
--- a/packages/server/src/services/agent-service.ts
+++ b/packages/server/src/services/agent-service.ts
@@ -29,6 +29,7 @@ import {
skillsDir,
systemConfigPath,
comparePluginVersions,
+ libraryPlugin,
loadLibraryPlugins,
parseSkillFrontmatter,
} from "@prismshadow/penguin-core";
@@ -256,6 +257,63 @@ export class AgentService implements AgentLifecycle {
};
}
+ /**
+ * Where one library plugin stands on one Agent: `installed` is the OLDEST version among the
+ * plugin's installed skills and its installed hook package — the same "any component behind
+ * the library is an update" rule {@link installedPlugins} draws the list cards' hints from —
+ * and null when the Agent carries none of them; `library` is the version the library offers
+ * now, null when the library has no such plugin. Only the head of each SKILL.md is read
+ * (see SKILL_HEAD_BYTES), so the answer costs one small read per skill the plugin ships.
+ *
+ * The organization runtime asks this per employee per pass to keep company plugins current.
+ * A skill the Agent does not carry — never installed, or removed by hand — counts for
+ * nothing: what is compared is the oldest version the Agent actually has, so a plugin whose
+ * skills are all current reads as current even where one of them is missing. Restoring a
+ * deleted skill is the Agents page's business, not a pass's.
+ */
+ async pluginVersion(
+ projectId: string,
+ agentId: string,
+ pluginName: string,
+ ): Promise<{ installed: string | null; library: string | null }> {
+ const plugin = libraryPlugin(pluginName);
+ if (!plugin) return { installed: null, library: null };
+ const base = skillsDir(this.root, projectId, agentId);
+ const versions: string[] = [];
+ for (const skill of plugin.skills) {
+ try {
+ const head = await readHead(path.join(base, skill.name, "SKILL.md"), SKILL_HEAD_BYTES);
+ versions.push(parseSkillFrontmatter(head)?.version ?? "");
+ } catch {
+ // The Agent does not carry this skill: it says nothing about the installed version.
+ }
+ }
+ if (plugin.hooks !== undefined) {
+ const hooks = await listInstalledHooks(this.root, projectId, agentId);
+ const installedHook = hooks.find((h) => h.name === pluginName);
+ if (installedHook) versions.push(installedHook.version);
+ }
+ let installed: string | null = null;
+ for (const version of versions) {
+ if (installed === null || comparePluginVersions(version, installed) < 0) installed = version;
+ }
+ return { installed, library: plugin.version };
+ }
+
+ /**
+ * Reinstall one library plugin over an Agent's copy: the same whole-plugin update the
+ * Agents page performs, through the same `installPlugin` writer, which overwrites every
+ * skill the plugin ships and its hook package with library content. Throws 404
+ * `unknown_plugin` when the library does not carry the name. Callers that may hold a cached
+ * runtime for the Agent invalidate it afterwards — hook packages are bound when a core
+ * Session is built, unlike skills, which are read from disk on demand.
+ */
+ async updatePlugin(projectId: string, agentId: string, pluginName: string): Promise<void> {
+ for (const plugin of resolveLibraryPlugins([pluginName])) {
+ await installPlugin(this.root, projectId, agentId, plugin);
+ }
+ }
+
/** Number of memory topic files: regular `*.md` files (minus each scope's MEMORY.md index) summed over the scope directories under memory/ (0 if the directory doesn't exist). */
private async memoryCount(projectId: string, agentId: string): Promise<number> {
const base = memoryDir(this.root, projectId, agentId);
diff --git a/packages/server/src/services/project-config-service.ts b/packages/server/src/services/project-config-service.ts
index 34a05885..ba66250f 100644
--- a/packages/server/src/services/project-config-service.ts
+++ b/packages/server/src/services/project-config-service.ts
@@ -39,6 +39,7 @@ import {
catalogEntryFor,
defaultProjectConfig,
imageUrlMessage,
+ metaMaxTokens,
projectConfigFromTable,
projectConfigPath,
renderProjectConfigToml,
@@ -48,6 +49,7 @@ import {
import { providerInfo } from "@prismshadow/penguin-core/model-catalog";
import type {
CommandPolicyRule,
+ GenerativeModelConfig,
LLMOutcome,
ModelRef,
OmniMessage,
@@ -257,6 +259,102 @@ const LIST_MODELS_TIMEOUT_MS = 20_000;
const SPEED_PROBE_PROMPT =
"Count from 1 to 50 as a comma-separated list, and nothing else. Do not think or explain.\n<think></think>";
+/**
+ * Bounds for a one-off utility completion (see completeOnce). The budget is core's own
+ * meta-request budget, the one `createBareLLM` sizes session titles and vision descriptions
+ * with, tightened by the entry's pinned per-model cap: an identifier is a handful of tokens,
+ * but on a reasoning model the thinking is spent out of the same cap, and a budget cut to the
+ * size of the answer leaves the answer itself with nothing (`finish_reason=length` before a
+ * single text token — the failure the connectivity probe's `probeVerdict` tolerates by name).
+ * The caller is a dialog waiting on the answer, so the wait stays short.
+ */
+const UTILITY_COMPLETION_BUDGET = 300;
+const UTILITY_COMPLETION_TIMEOUT_MS = 15_000;
+
+/**
+ * What one utility completion produced: the model's text, or why there is none. A bare null
+ * would say "no answer" and nothing else — and every one of these failures (no model
+ * configured, a missing credential, a provider rejection, a timeout, an answer that was all
+ * thinking) is one the user can act on, so the reason travels to the caller, which records it.
+ */
+export type UtilityCompletion =
+ | { ok: true; text: string }
+ | {
+ ok: false;
+ /** `no_model`: the Project names no default model, or names one it has no entry for — nothing was asked. `failed`: the model was asked and produced no text. */
+ cause: "no_model" | "failed";
+ error: string;
+ };
+
+/** How much of a failure detail is kept for display; the error recorder truncates again at its own bound. */
+const MAX_FAILURE_DETAIL = 300;
+
+/**
+ * What a request that did not complete has to say: the provider's own message when the outcome
+ * carries one, and the bare status (`aborted`, a `retryable` idle timeout) when it does not.
+ */
+function outcomeDetail(outcome: LLMOutcome): string {
+ const detail = outcome.errorMessage ? outcome.errorMessage : outcome.status;
+ return String(detail).slice(0, MAX_FAILURE_DETAIL);
+}
+
+/**
+ * The model config one utility completion runs with, built from the Project's default model
+ * entry. Exported because two of its fields decide whether an answer arrives at all, and
+ * reading them here costs no network:
+ *
+ * - `thinkingLevel: "none"`, the level core's own out-of-band requests use. Every provider the
+ * product ships works with it; a level that leaves thinking on spends the budget below on
+ * reasoning nobody reads.
+ * - `maxTokens`: the shared meta budget, tightened by the entry's pinned per-model cap — never
+ * a budget cut to the size of an identifier. A reasoning model spends its thinking out of the
+ * same cap, so a budget that small ends the request at `finish_reason=length` with the answer
+ * never started (see `probeVerdict`, which tolerates exactly that ending for the probe).
+ */
+export function utilityCompletionConfig(
+ modelId: string,
+ entry: Record<string, unknown>,
+): GenerativeModelConfig {
+ const apiKey = optStr(entry.api_key);
+ const baseUrl = optStr(entry.base_url);
+ const clientType = canonicalClientType(optStr(entry.client_type));
+ return {
+ modelId,
+ ...(apiKey ? { apiKey } : {}),
+ ...(baseUrl ? { baseUrl } : {}),
+ ...(clientType ? { clientType } : {}),
+ tools: [],
+ thinkingLevel: "none",
+ maxTokens: metaMaxTokens(UTILITY_COMPLETION_BUDGET, optNum(entry.max_tokens)),
+ requestTimeoutMs: UTILITY_COMPLETION_TIMEOUT_MS,
+ };
+}
+
+/**
+ * Drains a model stream into the answer's text, or the reason there is none.
+ *
+ * Complete `text` messages only. Every partial fragment is backfilled into one complete `text`
+ * message when the stream ends — on a normal finish and on an interrupted one alike (the
+ * translator's `finish` and `finishInterrupted` both flush the text buffer) — so counting both
+ * would return the answer twice, and counting only the partials would drop nothing but gain
+ * nothing either. A stream that carried only thinking leaves the buffer empty, and the
+ * terminal outcome is then what has something to say about why.
+ */
+export async function collectUtilityCompletion(
+ stream: AsyncGenerator<OmniMessage, LLMOutcome>,
+): Promise<UtilityCompletion> {
+ let text = "";
+ for (;;) {
+ const step = await stream.next();
+ if (step.done) {
+ if (text.trim() !== "") return { ok: true, text };
+ return { ok: false, cause: "failed", error: outcomeDetail(step.value) };
+ }
+ const p = step.value.payload as { type?: string; text?: string };
+ if (p.type === "text" && typeof p.text === "string") text += p.text;
+ }
+}
+
@Component()
export class ProjectConfigService implements ProjectConfigStore {
/**
@@ -631,11 +729,7 @@ export class ProjectConfigService implements ProjectConfigStore {
if (step.done) {
const outcome = classifyVisionProbe(step.value, sawContent);
if (outcome !== "failed") return { outcome };
- const detail =
- "errorMessage" in step.value && step.value.errorMessage
- ? step.value.errorMessage
- : step.value.status;
- return { outcome, message: String(detail).slice(0, 300) };
+ return { outcome, message: outcomeDetail(step.value) };
}
if (isProbeContent(step.value)) sawContent = true;
}
@@ -649,6 +743,53 @@ export class ProjectConfigService implements ProjectConfigStore {
}
}
+ /**
+ * One short completion on the Project's **default** model, for utility asks that belong to
+ * no Session — today the English identifier a display name is translated into. Everything
+ * comes from the stored default entry (credential, base URL, pinned protocol), and the
+ * answer is the model's plain text. Nothing throws: no default model, no entry for it, a
+ * construction that throws on a missing credential, a refusal, a timeout, or an answer with
+ * no text all come back as `{ ok: false }` carrying the reason, which the caller records so
+ * the errors panel can say why the ask produced nothing. Callers must still have a result
+ * that works without it. The request is not metered — it carries no Session to attribute
+ * it to.
+ *
+ * Thinking is off and the budget is the shared meta budget, for the same reason core's own
+ * out-of-band requests set them that way: a reasoning model spends thinking out of
+ * `maxTokens`, so a budget the size of the answer ends the request at `finish_reason=length`
+ * with no text at all.
+ */
+ async completeOnce(projectId: string, prompt: string): Promise<UtilityCompletion> {
+ const raw = await this.readRaw(projectId);
+ const ref = optRef(raw.default_model);
+ if (ref === undefined) {
+ return { ok: false, cause: "no_model", error: "the Project names no default model" };
+ }
+ const entry = asArray(raw.models).find((m) => entryMatches(m, ref.provider, ref.model_id));
+ if (entry === undefined) {
+ return {
+ ok: false,
+ cause: "no_model",
+ error: `the default model ${ref.provider}/${ref.model_id} has no entry in the Project config`,
+ };
+ }
+ try {
+ // Inside the try for the same reason as the probes: the SDK throws during
+ // construction when a credential is missing, and that must read as a failure with a
+ // reason rather than an exception out of a dialog's helper.
+ const llm = new GenerativeModel(utilityCompletionConfig(ref.model_id, entry));
+ return await collectUtilityCompletion(
+ llm.streamGenerate({ newMessages: [userText(prompt)] }),
+ );
+ } catch (err) {
+ return {
+ ok: false,
+ cause: "failed",
+ error: (err instanceof Error ? err.message : String(err)).slice(0, MAX_FAILURE_DETAIL),
+ };
+ }
+ }
+
async testModel(projectId: string, req: ModelTestRequest): Promise<ModelTestResponse> {
const raw = await this.readRaw(projectId);
// Testable even if the model isn't in the config yet (validate before saving when adding a custom model): in that case all parameters come from the request body.
@@ -1142,9 +1283,7 @@ export function probeVerdict(
): { ok: true } | { ok: false; message: string } {
if (outcome.status === "completed") return { ok: true };
if (outcome.status === "retryable" && sawContent) return { ok: true };
- const detail =
- "errorMessage" in outcome && outcome.errorMessage ? outcome.errorMessage : outcome.status;
- return { ok: false, message: String(detail).slice(0, 300) };
+ return { ok: false, message: outcomeDetail(outcome) };
}
/**
diff --git a/packages/server/src/services/project-service.ts b/packages/server/src/services/project-service.ts
index 7c6d5bfc..2e1a97b2 100644
--- a/packages/server/src/services/project-service.ts
+++ b/packages/server/src/services/project-service.ts
@@ -37,6 +37,7 @@ import type { Users } from "../mechanisms/identity.js";
import type { Schedules, SessionIndex } from "../mechanisms/sessions.js";
import type { ErrorLog, UsageStore } from "../mechanisms/observability.js";
import type { TraceIndex } from "../mechanisms/traces.js";
+import type { OrgCache } from "../mechanisms/organization.js";
/** Fallback timeout for waiting on runs to settle before deleting a Project. */
const ABORT_SETTLE_TIMEOUT_MS = 5000;
@@ -65,6 +66,8 @@ export class ProjectService implements ProjectLifecycle {
@Use() private readonly usage!: UsageStore;
@Use() private readonly errors!: ErrorLog;
@Use() private readonly schedules!: Schedules;
+ /** Company-mode caches: a destroyed Project takes its organization projections with it. */
+ @Use() private readonly orgCache!: OrgCache;
@Use() private readonly projectConfig!: ProjectConfigStore;
/** What destroying a Project needs of the session runtime — declared at the consumer. */
@Use() private readonly manager!: ProjectRuns;
@@ -262,6 +265,7 @@ export class ProjectService implements ProjectLifecycle {
this.usage.deleteByProject(projectId);
this.errors.deleteByProject(projectId);
this.schedules.deleteByProject(projectId);
+ this.orgCache.deleteProject(projectId);
this.traceIndex.removeProject(projectId);
await fs.rm(projectDir(this.root, projectId), { recursive: true, force: true });
}
diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.ts
index e5af87b9..b827f906 100644
--- a/packages/server/src/services/session-service.ts
+++ b/packages/server/src/services/session-service.ts
@@ -37,6 +37,9 @@ import type { ProjectConfigStore } from "../mechanisms/projects.js";
const SESSION_ID_TS_RE = /^session-(\d{4})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-(\d{2})-[0-9a-f]{8}$/;
+/** Stands in for the organization map when company mode is not wired in (tests, older assemblies). */
+const EMPTY_ORG_IDS: ReadonlyMap<string, string> = new Map();
+
/** Derives creation time from the local timestamp embedded in session_id; returns null if it doesn't match. */
export function sessionIdCreatedAt(sessionId: string): string | null {
const m = SESSION_ID_TS_RE.exec(sessionId);
@@ -82,6 +85,17 @@ export interface SessionServiceDeps {
* means the field is never set.
*/
messagingChannel?: (sessionId: string) => MessagingChannel | null;
+ /**
+ * Company mode: the organization owning a Session (a desk session, or a session
+ * contributing to a ticket), for `SessionInfo.orgId` — development mode's list hides
+ * those rows, the company sidebar groups them. Two shapes because the two flows cost
+ * differently: the single-Session GET asks about one id, a list asks once for the whole
+ * Project and looks its rows up in the returned map, so a long list never costs a query
+ * per row. Lambdas rather than the repo, so the service stays decoupled from the
+ * company-mode caches; absent (older assemblies/tests) means the field is never set.
+ */
+ orgIdOfSession?: (sessionId: string) => string | undefined;
+ orgIdsOfProject?: (projectId: string) => ReadonlyMap<string, string>;
/** Spawn-confinement getter (the sandbox module's), forwarded into core beside proxyEnv. */
confineSpawn?: () => SpawnConfiner | null;
}
@@ -94,10 +108,18 @@ export class SessionService {
* Async because `source` is derived from session_meta: a registry miss (Session predating
* this process) falls back to reading the Trace head once (see sourceOf). `traces` is the
* list flow's one-walk discovery result; without it a miss locates the shard itself.
+ *
+ * `orgIds` is the list flow's one-query organization map (see listSessions); without it the
+ * organization is a point lookup, which is what the single-Session paths want.
*/
- async toInfo(row: SessionRow, hasTrace: boolean): Promise<SessionInfo> {
+ async toInfo(
+ row: SessionRow,
+ hasTrace: boolean,
+ orgIds?: ReadonlyMap<string, string>,
+ ): Promise<SessionInfo> {
const source = await this.sourceOf(row, hasTrace);
const messagingChannel = this.deps.messagingChannel?.(row.sessionId) ?? null;
+ const orgId = orgIds ? orgIds.get(row.sessionId) : this.deps.orgIdOfSession?.(row.sessionId);
const backgroundTasks = this.deps.manager.backgroundTasksOf(row.sessionId);
return {
sessionId: row.sessionId,
@@ -118,6 +140,8 @@ export class SessionService {
hasTrace,
archived: (row.archivedAt ?? null) !== null,
...(messagingChannel !== null ? { messagingChannel } : {}),
+ ...(orgId !== undefined ? { orgId } : {}),
+ ...(row.client !== null && row.client !== undefined ? { client: row.client } : {}),
...(backgroundTasks !== undefined ? { backgroundTasks } : {}),
};
}
@@ -207,6 +231,10 @@ export class SessionService {
const rows = new Map(
this.deps.sessions.listByAgent(projectId, agentId).map((r) => [r.sessionId, r]),
);
+ // One query for the whole Project's organization-owned sessions, looked up per row
+ // below: the company caches are small, and a lookup per row would put a statement
+ // behind every entry of a long sidebar list.
+ const orgIds = this.deps.orgIdsOfProject?.(projectId) ?? EMPTY_ORG_IDS;
let traces: ReadonlySet<string> | undefined;
if ([...rows.values()].some((r) => this.deps.sources.get(r.sessionId) === undefined)) {
@@ -229,7 +257,7 @@ export class SessionService {
const rowHasTrace = (row: SessionRow): boolean =>
traces ? traces.has(row.sessionId) : row.hasTrace === true;
const toPage = (page: SessionRow[]) =>
- Promise.all(page.map((row) => this.toInfo(row, rowHasTrace(row))));
+ Promise.all(page.map((row) => this.toInfo(row, rowHasTrace(row), orgIds)));
// No classification asked for: slice straight away (the pre-category behavior).
if (category === undefined && workspaceGroup === undefined && !withCounts) {
@@ -346,10 +374,11 @@ export class SessionService {
source?: "schedule" | "benchmark";
/**
* Creating-client hint stored on the index row (`POST .../sessions` body `client`):
- * "cli" from the CLI, defaulting to "web". Purely informational — lists no longer
- * filter on it.
+ * "cli" from the CLI, defaulting to "web". "org" is not accepted over HTTP — the
+ * organization runtime calls this method directly and is the only caller that passes
+ * it, so no request can claim an organization's provenance for itself.
*/
- client?: "web" | "cli";
+ client?: "web" | "cli" | "org";
}): Promise<SessionInfo> {
if ((args.modelId === undefined) !== (args.provider === undefined)) {
throw badRequest(
@@ -422,8 +451,8 @@ export class SessionService {
approvalMode: args.approvalMode ?? "allow-all",
title: null,
// The creator's hint: "cli" when the CLI created this Session through the API,
- // otherwise "web" (schedule runs included). NULL means a legacy row, treated as
- // web. Informational only — lists serve every row.
+ // "org" when the organization runtime opened a desk or a ticket session, otherwise
+ // "web" (schedule runs included). NULL means a legacy row, treated as web.
client: args.client ?? "web",
// Creation is the first activity; the first driven run advances it (see SessionManager.drive).
lastActiveAt: createdAt,
diff --git a/packages/server/src/services/usage-service.ts b/packages/server/src/services/usage-service.ts
index cd46f39e..6933f55f 100644
--- a/packages/server/src/services/usage-service.ts
+++ b/packages/server/src/services/usage-service.ts
@@ -214,6 +214,73 @@ export class UsageService implements UsageQueries {
}));
}
+ /**
+ * Period cost per session, for company mode's attribution by the sessions an organization
+ * owns: sums by paired reference priced at the current rates (each half at the tier its own
+ * records ran in). `unpriced` says some usage ran on a model without pricing, so the numbers
+ * are a lower bound.
+ */
+ async costBySession(
+ projectId: string,
+ sessionIds: readonly string[],
+ fromTs: string,
+ toTs: string,
+ ): Promise<{ bySession: Map<string, number>; unpriced: boolean }> {
+ const bySession = new Map<string, number>();
+ if (sessionIds.length === 0) return { bySession, unpriced: false };
+ const rows = this.usage.groupsByModel(
+ projectId,
+ "session",
+ { sessionIds, fromTs, toTs },
+ this.tiers(),
+ );
+ const rates = new Map<string, TieredRates | undefined>();
+ let unpriced = false;
+ for (const r of rows) {
+ const key = refKey(r.provider, r.modelId);
+ if (!rates.has(key)) {
+ rates.set(key, await this.lookupPricing(projectId, r.provider, r.modelId));
+ }
+ const rate = rates.get(key);
+ if (!rate) {
+ unpriced = true;
+ continue;
+ }
+ bySession.set(r.key, (bySession.get(r.key) ?? 0) + costOf(r, rate));
+ }
+ return { bySession, unpriced };
+ }
+
+ /** Daily cost of a set of sessions over a window (the organization finance trend). */
+ async dailyCostForSessions(
+ projectId: string,
+ sessionIds: readonly string[],
+ fromTs: string,
+ toTs: string,
+ ): Promise<Array<{ date: string; cost: number }>> {
+ if (sessionIds.length === 0) return [];
+ const rows = this.usage.seriesByModel(
+ projectId,
+ "day",
+ { sessionIds, fromTs, toTs },
+ this.tiers(),
+ );
+ const rates = new Map<string, TieredRates | undefined>();
+ const byDate = new Map<string, number>();
+ for (const r of rows) {
+ const key = refKey(r.provider, r.modelId);
+ if (!rates.has(key)) {
+ rates.set(key, await this.lookupPricing(projectId, r.provider, r.modelId));
+ }
+ const rate = rates.get(key);
+ if (!rate) continue;
+ byDate.set(r.key, (byDate.get(r.key) ?? 0) + costOf(r, rate));
+ }
+ return [...byDate.entries()]
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([date, cost]) => ({ date, cost }));
+ }
+
async query(projectId: string, q: UsageQuery): Promise<UsageResponse> {
const today = formatLocalDate(this.clock.now());
// Top-level filter: agent + model (the cost center switches views by agent/model; the model filter is always sent as a pair).
diff --git a/packages/server/test/admin-settings.test.ts b/packages/server/test/admin-settings.test.ts
index 9821bd7a..d41160df 100644
--- a/packages/server/test/admin-settings.test.ts
+++ b/packages/server/test/admin-settings.test.ts
@@ -1,9 +1,9 @@
/**
- * Admin server-settings route tests: permission boundary (non-admin 403), the proxy
- * defaults (absent rows read as both switches on, no explicit address), adoption of the
- * legacy single-switch key, PUT persistence and validation (proxy-address normalization
- * and rejection), and merge semantics (an omitted field keeps its current value; a
- * rejected PUT writes nothing).
+ * Admin server-settings route tests: permission boundary (non-admin 403), the defaults
+ * (absent rows read as both proxy switches on with no explicit address, and company mode
+ * off), adoption of the legacy single-switch key, PUT persistence and validation
+ * (proxy-address normalization and rejection), and merge semantics (an omitted field keeps
+ * its current value; a rejected PUT writes nothing).
*
* The upload limits ride the same route and are covered here too: their defaults, the bounded
* range (the reason "100GB" is a clear refusal rather than an accepted number), the relation
@@ -65,7 +65,7 @@ describe("admin server settings", () => {
expect((await getSettings()).settings.proxyForApp).toBe(true);
});
- it("defaults while no rows exist: both switches on, no explicit address", async () => {
+ it("defaults while no rows exist: both proxy switches on, company mode off, no explicit address", async () => {
expect(t.deps.db.prepare("SELECT COUNT(*) AS n FROM server_settings").get()).toMatchObject({
n: 0,
});
@@ -73,6 +73,8 @@ describe("admin server settings", () => {
expect(settings.proxyForApp).toBe(true);
expect(settings.proxyForAgent).toBe(true);
expect(settings.proxyUrl).toBeNull();
+ // Company mode is the one switch that starts off: an admin opts the server into it.
+ expect(settings.companyMode).toBe(false);
});
it("adopts the legacy use_system_proxy row as the default for BOTH switches", async () => {
diff --git a/packages/server/test/db-migrations.test.ts b/packages/server/test/db-migrations.test.ts
index dfd96e2e..a905d420 100644
--- a/packages/server/test/db-migrations.test.ts
+++ b/packages/server/test/db-migrations.test.ts
@@ -1,7 +1,8 @@
/**
* The ordered-migration mechanism, the 0.2.4 → 0.2.7 migration that is its first entry, the
- * 0.2.9 → 0.2.10 drop that is its first restart-only one, and the additive column pair that
- * the user profile added to `users`.
+ * 0.2.9 → 0.2.10 drop that is its first restart-only one, the additive column pair that
+ * the user profile added to `users`, and the channels migration that is its first table
+ * recreation.
*
* Two properties carry everything else: a real 0.2.4 database reaches exactly the shape a
* fresh one is created with (so a runtime older than the platform pushed onto it becomes
@@ -44,6 +45,22 @@ const GOAL_STATE_DDL = `
CREATE INDEX idx_goal_session ON goal_state(session_id);
`;
+/** Every company-mode table the migrations add: a database from before them had none. */
+function dropCompanyModeTables(db: DatabaseSync): void {
+ for (const table of [
+ "org_sessions",
+ "org_ticket_sessions",
+ "org_calendar_state",
+ "org_ticket_state",
+ "org_channel_state",
+ "org_channel_reads",
+ "org_budget_state",
+ "org_desk_notices",
+ ]) {
+ db.exec(`DROP TABLE IF EXISTS ${table}`);
+ }
+}
+
/**
* The v0.2.4 schema, as a frozen excerpt: today's declaration minus exactly what 0.2.4
* lacked, plus the one table it had that today's declaration dropped. Derived from
@@ -52,6 +69,7 @@ const GOAL_STATE_DDL = `
function open024(): DatabaseSync {
const db = new sqlite.DatabaseSync(":memory:");
db.exec(SCHEMA_SQL);
+ dropCompanyModeTables(db);
db.exec("DROP TABLE messaging_bindings");
db.exec("DROP INDEX IF EXISTS idx_auth_sessions_expires");
db.exec("DROP INDEX IF EXISTS idx_auth_sessions_user");
@@ -63,10 +81,55 @@ function open024(): DatabaseSync {
return db;
}
+/**
+ * The two chat tables as migration 5 declared them (frozen: company mode's chat became
+ * channels in migration 6 — renamed tables, `channel_id` in the primary keys — and the
+ * migration that recreates them must not learn a new shape).
+ */
+const PRE_CHANNEL_CHAT_DDL = `
+ DROP TABLE IF EXISTS org_channel_state;
+ DROP TABLE IF EXISTS org_channel_reads;
+ CREATE TABLE org_chat_state (
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ date TEXT NOT NULL,
+ offset_bytes INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (project_id, org_id, date)
+ );
+ CREATE TABLE org_chat_reads (
+ project_id TEXT NOT NULL,
+ org_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ last_read_id TEXT NOT NULL,
+ PRIMARY KEY (project_id, org_id, user_id)
+ );
+`;
+
+/** A database stamped at migration 5: company mode's caches, before chat became channels. */
+function open6(): DatabaseSync {
+ const db = new sqlite.DatabaseSync(":memory:");
+ db.exec(SCHEMA_SQL);
+ db.exec(PRE_CHANNEL_CHAT_DDL);
+ // SCHEMA_SQL declares the CURRENT shape; migration 8's queue came after 6.
+ db.exec("DROP TABLE IF EXISTS org_desk_notices");
+ db.exec("PRAGMA user_version = 6");
+ return db;
+}
+
+/** A database stamped at migration 6: channels, and no desk-notice queue yet. */
+function open7(): DatabaseSync {
+ const db = new sqlite.DatabaseSync(":memory:");
+ db.exec(SCHEMA_SQL);
+ db.exec("DROP TABLE IF EXISTS org_desk_notices");
+ db.exec("PRAGMA user_version = 7");
+ return db;
+}
+
/** A 0.2.9 database: everything 0.2.4 had plus what versions 1 and 2 added, and still goal_state. */
function open029(): DatabaseSync {
const db = new sqlite.DatabaseSync(":memory:");
db.exec(SCHEMA_SQL);
+ dropCompanyModeTables(db);
db.exec(GOAL_STATE_DDL);
// SCHEMA_SQL declares the CURRENT shape, and a 0.2.9 database has no machines tables —
// migration 4 is what adds them — and no profile columns, which migration 5 adds. Without
@@ -86,10 +149,30 @@ function openPreProfile(): DatabaseSync {
const db = new sqlite.DatabaseSync(":memory:");
db.exec(SCHEMA_SQL);
dropProfileColumns(db);
+ // Version 4 predates company mode as well: its three migrations (6–8) come after the
+ // profile's, so a database at 4 has none of their tables.
+ dropCompanyTables(db);
db.exec("PRAGMA user_version = 4");
return db;
}
+/** Takes everything migrations 6–8 create off a database built from the current declaration. */
+function dropCompanyTables(db: DatabaseSync): void {
+ db.exec(`
+ DROP INDEX IF EXISTS idx_org_desk_notices_agent;
+ DROP INDEX IF EXISTS idx_org_ticket_sessions_session;
+ DROP INDEX IF EXISTS idx_org_sessions_org;
+ DROP TABLE IF EXISTS org_desk_notices;
+ DROP TABLE IF EXISTS org_budget_state;
+ DROP TABLE IF EXISTS org_channel_reads;
+ DROP TABLE IF EXISTS org_channel_state;
+ DROP TABLE IF EXISTS org_ticket_state;
+ DROP TABLE IF EXISTS org_calendar_state;
+ DROP TABLE IF EXISTS org_ticket_sessions;
+ DROP TABLE IF EXISTS org_sessions;
+ `);
+}
+
/** Takes migration 5's two columns off a database built from the current declaration. */
function dropProfileColumns(db: DatabaseSync): void {
db.exec("ALTER TABLE users DROP COLUMN avatar");
@@ -109,7 +192,8 @@ function withoutRestartOnly<T>(fn: () => T): T {
try {
return fn();
} finally {
- list.push(...removed);
+ // Back where it was: appending would reorder the list once later migrations exist.
+ list.splice(2, 0, ...removed);
}
}
@@ -173,13 +257,7 @@ describe("migration mechanism", () => {
const r = migrate(db);
expect(r.from).toBe(0);
expect(r.to).toBe(LATEST_VERSION);
- expect(r.applied).toEqual([
- "messaging-bindings",
- "messaging-delivery-flags",
- "drop-goal-state",
- "machines",
- "user-profile",
- ]);
+ expect(r.applied).toEqual(MIGRATIONS.map((m) => m.name));
expect(schemaVersion(db)).toBe(LATEST_VERSION);
} finally {
db.close();
@@ -234,12 +312,8 @@ describe("the swap path refuses what a rollback could not survive", () => {
it("applies swap-safe migrations while a pushed platform boots", () => {
const db = open024();
try {
- expect(withoutRestartOnly(() => migrate(db, { swapPath: true }).applied)).toEqual([
- "messaging-bindings",
- "messaging-delivery-flags",
- "machines",
- "user-profile",
- ]);
+ const swapSafe = MIGRATIONS.filter((m) => m.swapSafe).map((m) => m.name);
+ expect(withoutRestartOnly(() => migrate(db, { swapPath: true }).applied)).toEqual(swapSafe);
} finally {
db.close();
}
@@ -254,13 +328,7 @@ describe("the swap path refuses what a rollback could not survive", () => {
expect(shape(db)).toBe(before);
expect(schemaVersion(db)).toBe(0);
// The runtime's own open, which owns the process, may apply it.
- expect(migrate(db).applied).toEqual([
- "messaging-bindings",
- "messaging-delivery-flags",
- "drop-goal-state",
- "machines",
- "user-profile",
- ]);
+ expect(migrate(db).applied).toEqual(MIGRATIONS.map((m) => m.name));
} finally {
db.close();
}
@@ -283,12 +351,13 @@ describe("0.2.9 → current: drop-goal-state", () => {
const fresh = new sqlite.DatabaseSync(":memory:");
try {
fresh.exec(SCHEMA_SQL);
- expect(migrate(db).applied).toEqual(["drop-goal-state", "machines", "user-profile"]);
+ const after029 = MIGRATIONS.filter((m) => m.version > 2).map((m) => m.name);
+ expect(migrate(db).applied).toEqual(after029);
expect(shape(db)).toBe(shape(fresh));
// IF EXISTS: a database this build created, stamped 2 by an older mechanism, has no
// goal_state to drop and must not fail on it.
fresh.exec("PRAGMA user_version = 2");
- expect(migrate(fresh).applied).toEqual(["drop-goal-state", "machines", "user-profile"]);
+ expect(migrate(fresh).applied).toEqual(after029);
} finally {
db.close();
fresh.close();
@@ -320,7 +389,9 @@ describe("pre-profile → current: user-profile", () => {
try {
fresh.exec(SCHEMA_SQL);
expect(userColumns(db)).not.toContain("display_name");
- expect(migrate(db).applied).toEqual(["user-profile"]);
+ expect(migrate(db).applied).toEqual(
+ MIGRATIONS.filter((m) => m.version > 4).map((m) => m.name),
+ );
expect(userColumns(db)).toContain("display_name");
expect(userColumns(db)).toContain("avatar");
expect(shape(db)).toBe(shape(fresh));
@@ -328,7 +399,9 @@ describe("pre-profile → current: user-profile", () => {
// ADOPTION: on a database this build created, the declarative track already added both,
// so the migration must find its work done, add nothing twice, and stamp anyway.
fresh.exec("PRAGMA user_version = 4");
- expect(migrate(fresh).applied).toEqual(["user-profile"]);
+ expect(migrate(fresh).applied).toEqual(
+ MIGRATIONS.filter((m) => m.version > 4).map((m) => m.name),
+ );
expect(userColumns(fresh).filter((c) => c === "avatar")).toEqual(["avatar"]);
} finally {
db.close();
@@ -358,6 +431,101 @@ describe("pre-profile → current: user-profile", () => {
});
});
+describe("migration 6 → current: company-mode-channels", () => {
+ it("renames both chat tables and puts channel_id in their primary keys, recreating them empty", () => {
+ const db = open6();
+ const fresh = new sqlite.DatabaseSync(":memory:");
+ try {
+ fresh.exec(SCHEMA_SQL);
+ db.exec(
+ "INSERT INTO org_chat_reads (project_id, org_id, user_id, last_read_id)" +
+ " VALUES ('p1', 'acme', 'alice', 'msg-2026-09-01-00-00-00-00000000')",
+ );
+ expect(shape(db)).not.toBe(shape(fresh));
+
+ expect(migrate(db).applied).toEqual(
+ MIGRATIONS.filter((m) => m.version > 6).map((m) => m.name),
+ );
+ expect(shape(db)).toBe(shape(fresh));
+ // Renamed and recreated, not altered: the old tables are gone, nothing is carried
+ // over, and a row now names its channel.
+ expect(
+ db
+ .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'org_chat_reads'")
+ .get(),
+ ).toBeUndefined();
+ expect(db.prepare("SELECT COUNT(*) AS n FROM org_channel_reads").get()).toEqual({ n: 0 });
+ db.exec(
+ "INSERT INTO org_channel_reads (project_id, org_id, channel_id, user_id, last_read_id)" +
+ " VALUES ('p1', 'acme', 'default_channel', 'alice', 'msg-2026-09-01-00-00-00-00000000')",
+ );
+ expect(db.prepare("SELECT channel_id FROM org_channel_reads").all()).toEqual([
+ { channel_id: "default_channel" },
+ ]);
+ } finally {
+ db.close();
+ fresh.close();
+ }
+ });
+
+ it("down puts the old tables and the single-chat shape back, empty", () => {
+ const db = open6();
+ const at6 = open6();
+ try {
+ migrate(db);
+ rollbackTo(db, 6);
+ expect(schemaVersion(db)).toBe(6);
+ expect(shape(db)).toBe(shape(at6));
+ expect(db.prepare("SELECT COUNT(*) AS n FROM org_chat_state").get()).toEqual({ n: 0 });
+ } finally {
+ db.close();
+ at6.close();
+ }
+ });
+});
+
+describe("migration 7 → current: company-mode-desk-notices", () => {
+ it("adds the queue a ticket change is delivered through, writable and indexed", () => {
+ const db = open7();
+ const fresh = new sqlite.DatabaseSync(":memory:");
+ try {
+ fresh.exec(SCHEMA_SQL);
+ expect(shape(db)).not.toBe(shape(fresh));
+ expect(migrate(db).applied).toEqual(
+ MIGRATIONS.filter((m) => m.version > 7).map((m) => m.name),
+ );
+ expect(shape(db)).toBe(shape(fresh));
+ db.exec(
+ "INSERT INTO org_desk_notices (project_id, org_id, agent_id, ticket_id, change, at)" +
+ " VALUES ('p1', 'acme', 'acme_hr', '2026-09-08-site', 'assigned', '2026-09-08T01:00:00Z')",
+ );
+ // seq is the delivery order, handed out by the table itself.
+ expect(db.prepare("SELECT seq FROM org_desk_notices").all()).toEqual([{ seq: 1 }]);
+ } finally {
+ db.close();
+ fresh.close();
+ }
+ });
+
+ it("down drops the queue with the notices nobody has been told about yet", () => {
+ const db = open7();
+ const at7 = open7();
+ try {
+ migrate(db);
+ db.exec(
+ "INSERT INTO org_desk_notices (project_id, org_id, agent_id, ticket_id, change, at)" +
+ " VALUES ('p1', 'acme', 'acme_hr', '2026-09-08-site', 'done', '2026-09-08T01:00:00Z')",
+ );
+ rollbackTo(db, 7);
+ expect(schemaVersion(db)).toBe(7);
+ expect(shape(db)).toBe(shape(at7));
+ } finally {
+ db.close();
+ at7.close();
+ }
+ });
+});
+
describe("0.2.4 → current", () => {
/** The whole point: an older runtime's database becomes what a current build creates. */
it("brings a 0.2.4 database to the shape a fresh one is created with", () => {
@@ -419,11 +587,23 @@ describe("rollbackTo", () => {
migrate(db);
expect(schemaVersion(db)).toBe(LATEST_VERSION);
- const r = rollbackTo(db, 2);
+ // Back to version 1: everything after it is undone, so the columns migration 2 added are gone.
+ const r = rollbackTo(db, 1);
expect(r.from).toBe(LATEST_VERSION);
- expect(r.to).toBe(2);
- // Newest first: the profile columns go, then the machines tables, then goal_state returns.
- expect(r.reverted).toEqual(["user-profile", "machines", "drop-goal-state"]);
+ expect(r.to).toBe(1);
+ // Newest first, all the way down to 1.
+ expect(r.reverted).toEqual(
+ MIGRATIONS.filter((m) => m.version > 1)
+ .map((m) => m.name)
+ .reverse(),
+ );
+ const cols = (
+ db.prepare("PRAGMA table_info(messaging_bindings)").all() as { name: string }[]
+ ).map((c) => c.name);
+ expect(cols).not.toContain("render_markdown");
+ expect(cols).not.toContain("final_reply_only");
+ // And what the migrations above 1 created is gone with them; goal_state, which 3
+ // dropped, is back.
const tables = (
db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all() as {
name: string;
@@ -431,6 +611,7 @@ describe("rollbackTo", () => {
).map((t) => t.name);
expect(tables).not.toContain("machines");
expect(tables).not.toContain("machine_project");
+ expect(tables).not.toContain("org_channel_reads");
expect(tables).toContain("goal_state");
} finally {
db.close();
@@ -461,13 +642,11 @@ describe("rollbackTo", () => {
try {
migrate(db);
const r = rollbackTo(db, 0);
- expect(r.reverted).toEqual([
- "user-profile",
- "machines",
- "drop-goal-state",
- "messaging-delivery-flags",
- "messaging-bindings",
- ]);
+ expect(r.reverted).toEqual(
+ MIGRATIONS.filter((m) => m.version > 0)
+ .map((m) => m.name)
+ .reverse(),
+ );
expect(
db
.prepare(
diff --git a/packages/server/test/helpers.ts b/packages/server/test/helpers.ts
index 5661d113..b2a0d48f 100644
--- a/packages/server/test/helpers.ts
+++ b/packages/server/test/helpers.ts
@@ -39,6 +39,8 @@ import type { MessagingBindingsRepo } from "../src/db/repos/messaging-bindings.j
import type { MessagingBridge } from "../src/runtime/messaging/bridge.js";
import type { QQScanService, QQScanTransport } from "../src/runtime/messaging/qq-scan.js";
import type { Scheduler } from "../src/runtime/scheduler.js";
+import type { OrganizationService } from "../src/runtime/organization/service.js";
+import type { OrgCacheRepo } from "../src/db/repos/organizations.js";
import type { SessionManager, SessionLoader } from "../src/runtime/session-manager.js";
import type { ErrorRecorder } from "../src/runtime/error-recorder.js";
import type { MachinesService } from "../src/machines/service.js";
@@ -73,6 +75,7 @@ import type { WeChatTransport } from "../src/runtime/messaging/wechat-api.js";
import { WeChatScanTransportProvider } from "../src/runtime/messaging/wechat-scan.js";
import type { WeChatScanTransport } from "../src/runtime/messaging/wechat-scan.js";
import { MachinesModule, machinesServerProxyRoutes } from "../src/machines/service.js";
+import { OrganizationModule } from "../src/runtime/organization/service.js";
import { machinesRoutes } from "../src/http/routes/machines.js";
import type { Access } from "../src/mechanisms/projects.js";
@@ -158,6 +161,9 @@ export interface TestDeps {
messaging: MessagingBridge;
qqScan: QQScanService;
scheduler: Scheduler;
+ /** Company mode: the organization runtime and its caches. */
+ orgService: OrganizationService;
+ orgCacheRepo: OrgCacheRepo;
manager: SessionManager;
sessionSources: SessionSources;
errors: ErrorRecorder;
@@ -203,6 +209,8 @@ export function flattenForTests(boot: ServerBoot): TestDeps {
messaging: api("MessagingHubModule", "Messaging"),
qqScan: api("MessagingHubModule", "QQScan"),
scheduler: api("SessionRuntimeModule", "Scheduling"),
+ orgService: api("CompanyModule", "OrgService"),
+ orgCacheRepo: api("CompanyModule", "OrgCache"),
manager: api("SessionRuntimeModule", "Sessions"),
sessionSources: api("SessionRuntimeModule", "SessionOrigins"),
errors: api("ObservabilityModule", "Errors"),
@@ -254,6 +262,8 @@ export interface TestAppOptions {
wechatRetryDelayMs?: (failures: number) => number;
/** Test double: machines service whose ssh effects are faked. */
machines?: MachinesService;
+ /** Test double: company mode's organization service, for the route suite (its semantics have their own suites). */
+ orgService?: OrganizationService;
/** Test double: the password work factor (scrypt at full strength is seconds per hash). */
passwordHashCost?: number;
log?: (line: string) => void;
@@ -316,6 +326,17 @@ export function replacementsFor(o: TestAppOptions): Replacements {
if (o.telegramRetryDelayMs) tuning.retryDelayMs = o.telegramRetryDelayMs;
if (o.wechatRetryDelayMs) tuning.retryDelayMs = o.wechatRetryDelayMs;
if (Object.keys(tuning).length > 0) out.push([DefaultMessagingTuning, tuning]);
+ if (o.orgService) {
+ // The whole node stands in: the module provides the service and its scheduler together,
+ // and a suite that fakes the service wants no pass running against the real files.
+ out.push([
+ OrganizationModule,
+ {
+ orgService: o.orgService,
+ orgScheduler: { start: async () => {}, stop: () => {} },
+ },
+ ]);
+ }
if (o.machines) {
const machines = o.machines;
out.push([
diff --git a/packages/server/test/hot-replace.test.ts b/packages/server/test/hot-replace.test.ts
index c354e4f4..fb38048d 100644
--- a/packages/server/test/hot-replace.test.ts
+++ b/packages/server/test/hot-replace.test.ts
@@ -43,6 +43,8 @@ function memorySettings(maxMb = 7): Settings {
return {
get: (k) => kv.get(k) ?? null,
set: (k, v) => void kv.set(k, v),
+ getCompanyMode: () => false,
+ setCompanyMode: () => {},
getProxyForApp: () => false,
setProxyForApp: () => {},
getProxyForAgent: () => false,
diff --git a/packages/server/test/org-harness.ts b/packages/server/test/org-harness.ts
new file mode 100644
index 00000000..7aa38cf3
--- /dev/null
+++ b/packages/server/test/org-harness.ts
@@ -0,0 +1,241 @@
+/**
+ * A company-mode harness on doubles: the real file store, caches and service, with the
+ * session manager, session creation, the Agent lifecycle (plugin versions included) and usage
+ * pricing replaced by recording fakes and the clock under test control. Shared by the runtime
+ * and scenario suites so both exercise the same seams the app binds in production.
+ */
+import { saveProjectConfig } from "@prismshadow/penguin-core";
+import { wire } from "@prismshadow/penguin-core/kernel";
+import type { OmniMessage } from "@prismshadow/penguin-core";
+import type { ServerEvent } from "../src/api/types.js";
+import { openDatabase } from "../src/db/database.js";
+import { MembersRepo } from "../src/db/repos/members.js";
+import { OrgCacheRepo } from "../src/db/repos/organizations.js";
+import { ProjectsRepo } from "../src/db/repos/projects.js";
+import { SessionsRepo } from "../src/db/repos/sessions.js";
+import { UsersRepo } from "../src/db/repos/users.js";
+import { OrgStore } from "../src/organization/store.js";
+import type { ErrorRecordArgs } from "../src/runtime/error-recorder.js";
+import { DEFAULT_EMPLOYEE_PLUGINS } from "../src/runtime/organization/deps.js";
+import type { OrgDeps } from "../src/runtime/organization/deps.js";
+import { OrganizationScheduler } from "../src/runtime/organization/scheduler.js";
+import { OrganizationService } from "../src/runtime/organization/service.js";
+import { ProjectConfigService } from "../src/services/project-config-service.js";
+import { makeTempRoot } from "./helpers.js";
+
+export interface StartedTask {
+ sessionId: string;
+ text: string;
+ queueIfBusy: boolean;
+}
+
+export interface OrgHarness {
+ root: string;
+ projectId: string;
+ store: OrgStore;
+ cache: OrgCacheRepo;
+ sessions: SessionsRepo;
+ service: OrganizationService;
+ scheduler: OrganizationScheduler;
+ /** The controlled clock; assign to move time. */
+ clock: { nowMs: number };
+ /** Sessions currently reported as running by the fake manager. */
+ busy: Set<string>;
+ /** Every Task the runtime started, in order. */
+ started: StartedTask[];
+ /** Every session the fake creator opened. */
+ created: Array<{ projectId: string; agentId: string; workspace?: string; client: "org" }>;
+ /** Agents the fake lifecycle created, with their plugin seeds. */
+ agentsCreated: Array<{ agentId: string; plugins: readonly string[] }>;
+ /** AGENTS.md text written per Agent. */
+ briefs: Map<string, string>;
+ /** Cost per session the fake pricing reports. */
+ costs: Map<string, number>;
+ events: ServerEvent[];
+ errors: ErrorRecordArgs[];
+ /** The admin master switch. */
+ flags: { companyMode: boolean };
+ /** The Agents that exist in the Project, as the fake gateway answers `exists`; delete one to make its desk unopenable. */
+ agents: Set<string>;
+ /** The plugin library and the Agents' installed copies, as the fake gateway answers them. */
+ plugins: FakePlugins;
+}
+
+/**
+ * What the fake `agents` gateway knows about plugins: the version the library offers per
+ * plugin name, the version each Agent carries (keyed `<agentId>:<plugin>`), the updates it was
+ * asked to perform, and the pairs whose update throws. A hire records every plugin it was
+ * created with at the library's version, so an employee is up to date until a test sets one of
+ * its entries back.
+ */
+export interface FakePlugins {
+ library: Map<string, string>;
+ installed: Map<string, string>;
+ updated: Array<{ agentId: string; plugin: string }>;
+ failUpdates: Set<string>;
+}
+
+/** The version the fake library offers for every plugin an employee is hired with. */
+export const FAKE_LIBRARY_VERSION = "2026.09.14.1";
+
+function textOf(input: OmniMessage[]): string {
+ const first = input[0] as { payload?: { text?: string } } | undefined;
+ return first?.payload?.text ?? "";
+}
+
+export async function makeOrgHarness(opts: {
+ projectId?: string;
+ ownerUserId?: string;
+ nowMs: number;
+}): Promise<OrgHarness> {
+ const projectId = opts.projectId ?? "p1";
+ const owner = opts.ownerUserId ?? "alice";
+ const root = await makeTempRoot();
+ await saveProjectConfig(root, projectId, {
+ default_model: { provider: "custom", model_id: "m-bench" },
+ models: [{ provider: "custom", model_id: "m-bench" }],
+ });
+ const db = openDatabase(":memory:");
+ wire(UsersRepo, { db }).insert({
+ userId: owner,
+ passwordHash: "x",
+ isAdmin: false,
+ passwordIsInitial: false,
+ displayName: null,
+ avatar: null,
+ createdAt: "2026-08-01T00:00:00Z",
+ });
+ const projects = wire(ProjectsRepo, { db });
+ projects.insert({ projectId, ownerUserId: owner, createdAt: "2026-08-01T00:00:00Z" });
+ const sessions = wire(SessionsRepo, { db });
+ const cache = wire(OrgCacheRepo, { db });
+ const store = new OrgStore(root);
+ const clock = { nowMs: opts.nowMs };
+ const busy = new Set<string>();
+ const started: StartedTask[] = [];
+ const created: OrgHarness["created"] = [];
+ const agentsCreated: OrgHarness["agentsCreated"] = [];
+ const briefs = new Map<string, string>();
+ const costs = new Map<string, number>();
+ const events: ServerEvent[] = [];
+ const errors: ErrorRecordArgs[] = [];
+ const flags = { companyMode: true };
+ const existingAgents = new Set<string>();
+ const plugins: FakePlugins = {
+ library: new Map(DEFAULT_EMPLOYEE_PLUGINS.map((name) => [name, FAKE_LIBRARY_VERSION])),
+ installed: new Map(),
+ updated: [],
+ failUpdates: new Set(),
+ };
+ let seq = 0;
+ const deps: OrgDeps = {
+ root,
+ store,
+ cache,
+ projects,
+ members: wire(MembersRepo, { db }),
+ sessions,
+ runner: {
+ statusOf: (id) => (busy.has(id) ? "running" : "idle"),
+ startTask: async (sessionId, input, o) => {
+ started.push({ sessionId, text: textOf(input), queueIfBusy: o?.queueIfBusy === true });
+ return { sessionId, queued: busy.has(sessionId) };
+ },
+ },
+ sessionCreator: {
+ createSession: async (args) => {
+ seq++;
+ const sessionId = `session-2026-09-01-00-00-${String(seq).padStart(2, "0")}-${String(seq).padStart(8, "0")}`;
+ created.push({
+ projectId: args.projectId,
+ agentId: args.agentId,
+ ...(args.workspace !== undefined ? { workspace: args.workspace } : {}),
+ client: args.client,
+ });
+ const createdAt = new Date(clock.nowMs).toISOString();
+ sessions.insert({
+ sessionId,
+ projectId: args.projectId,
+ agentId: args.agentId,
+ provider: args.provider ?? "custom",
+ modelId: args.modelId ?? "m-bench",
+ workspace: args.workspace ?? root,
+ approvalMode: args.approvalMode ?? "allow-all",
+ title: null,
+ // The row the real SessionService writes carries the caller's hint verbatim; a
+ // fake that hardcoded "web" here would pass the marker's own test.
+ client: args.client,
+ lastActiveAt: createdAt,
+ createdAt,
+ });
+ return { sessionId, workspace: args.workspace ?? root };
+ },
+ },
+ agents: {
+ exists: async (_p, agentId) => existingAgents.has(agentId),
+ create: async (_p, agentId, _name, _description, seeds) => {
+ existingAgents.add(agentId);
+ agentsCreated.push({ agentId, plugins: seeds });
+ // Creation installs the library's current content, which is why a fresh hire is never
+ // a candidate for the pass that keeps plugins current.
+ for (const name of seeds) {
+ const version = plugins.library.get(name);
+ if (version !== undefined) plugins.installed.set(`${agentId}:${name}`, version);
+ }
+ },
+ displayName: async (_p, agentId) => `Name of ${agentId}`,
+ writeAgentsMd: async (_p, agentId, content) => {
+ briefs.set(agentId, content);
+ },
+ pluginVersion: async (_p, agentId, plugin) => ({
+ installed: plugins.installed.get(`${agentId}:${plugin}`) ?? null,
+ library: plugins.library.get(plugin) ?? null,
+ }),
+ updatePlugin: async (_p, agentId, plugin) => {
+ if (plugins.failUpdates.has(`${agentId}:${plugin}`)) {
+ throw new Error(`plugin ${plugin} could not be written`);
+ }
+ const version = plugins.library.get(plugin);
+ if (version === undefined) throw new Error(`Plugin is not in the library: ${plugin}`);
+ plugins.installed.set(`${agentId}:${plugin}`, version);
+ plugins.updated.push({ agentId, plugin });
+ },
+ },
+ projectConfig: wire(ProjectConfigService, { paths: { root } }),
+ usage: {
+ costBySession: async (_p, ids) => ({
+ bySession: new Map(ids.filter((id) => costs.has(id)).map((id) => [id, costs.get(id)!])),
+ unpriced: false,
+ }),
+ dailyCostForSessions: async () => [],
+ },
+ errors: { record: (e) => void errors.push(e) },
+ notifyProject: (_p, event) => void events.push(event),
+ companyModeEnabled: () => flags.companyMode,
+ now: () => clock.nowMs,
+ log: () => {},
+ };
+ const scheduler = new OrganizationScheduler(deps, { intervalMs: 1_000_000 });
+ const service = new OrganizationService(deps, scheduler);
+ return {
+ root,
+ projectId,
+ store,
+ cache,
+ sessions,
+ service,
+ scheduler,
+ clock,
+ busy,
+ started,
+ created,
+ agentsCreated,
+ briefs,
+ costs,
+ events,
+ errors,
+ flags,
+ agents: existingAgents,
+ plugins,
+ };
+}
diff --git a/packages/server/test/organization-digest.test.ts b/packages/server/test/organization-digest.test.ts
new file mode 100644
index 00000000..c391bfe7
--- /dev/null
+++ b/packages/server/test/organization-digest.test.ts
@@ -0,0 +1,109 @@
+/**
+ * The "Since your last sweep" section: the queued ticket changes as the employee reads them
+ * at the end of its next calendar event. Pure input, pure output — the delivery rule itself
+ * (nothing is sent when a ticket changes) is exercised in `organization-runtime.test.ts`.
+ */
+import { describe, expect, it } from "vitest";
+import type { OrgTicketChange } from "../src/api/types.js";
+import type { OrgDeskNoticeRow } from "../src/db/repos/organizations.js";
+import type { TicketDoc } from "../src/organization/files.js";
+import { deskDigest } from "../src/runtime/organization/digest.js";
+import type { DigestTicket } from "../src/runtime/organization/digest.js";
+
+let seq = 0;
+
+function row(agentId: string, ticketId: string, change: OrgTicketChange): OrgDeskNoticeRow {
+ seq += 1;
+ return {
+ seq,
+ projectId: "p1",
+ orgId: "acme",
+ agentId,
+ ticketId,
+ change,
+ at: "2026-09-08T01:00:00Z",
+ };
+}
+
+function ticket(ticketId: string, title: string, doc: Partial<TicketDoc> = {}): DigestTicket {
+ return {
+ ticketId,
+ doc: {
+ title,
+ status: "in_progress",
+ owner: "user:alice",
+ notify: [],
+ priority: "P1",
+ sessions: [],
+ history: [],
+ goal: "",
+ acceptanceCriteria: "",
+ progress: [],
+ result: "",
+ extra: {},
+ extraSections: [],
+ ...doc,
+ },
+ };
+}
+
+describe("deskDigest", () => {
+ it("says nothing when nothing is queued", () => {
+ expect(deskDigest([], [ticket("2026-09-08-site", "Launch the marketing site")])).toBe("");
+ });
+
+ it("lists one line per change in queue order, with the reason or blocker the ticket carries", () => {
+ const tickets = [
+ ticket("2026-09-08-site-launch", "Launch the marketing site"),
+ ticket("2026-09-08-domain", "Register the domain", {
+ blocked: "waiting for the board",
+ blockedBy: "user:alice",
+ }),
+ ticket("2026-09-08-backend-api", "Backend API", {
+ blocked: "waiting for the domain",
+ blockedBy: "2026-09-08-domain",
+ }),
+ ticket("2026-09-07-copy", "Site copy", { status: "done" }),
+ ticket("2026-09-07-logo", "Logo", { status: "rejected", result: "off-brand" }),
+ ];
+ const rows = [
+ row("acme_dev", "2026-09-08-site-launch", "assigned"),
+ row("acme_dev", "2026-09-08-domain", "blocked"),
+ row("acme_dev", "2026-09-08-backend-api", "blocker_closed"),
+ row("acme_dev", "2026-09-07-copy", "done"),
+ row("acme_dev", "2026-09-07-logo", "rejected"),
+ ];
+ expect(deskDigest(rows, tickets)).toBe(
+ [
+ "## Since your last sweep",
+ "- 2026-09-08-site-launch (Launch the marketing site): assigned to you",
+ '- 2026-09-08-domain (Register the domain): blocked — "waiting for the board" (by user:alice)',
+ "- 2026-09-08-backend-api (Backend API): blocker closed (2026-09-08-domain) — verify, then `penguin org ticket unblock 2026-09-08-backend-api`",
+ "- 2026-09-07-copy (Site copy): done",
+ '- 2026-09-07-logo (Logo): rejected — "off-brand"',
+ "",
+ 'Decide on each: start a ticket session (`penguin org ticket start <id> -m "…"`), verify and unblock, or leave it — do not do the work at your desk.',
+ ].join("\n"),
+ );
+ });
+
+ it("names a ticket whose file is gone, and asks for no command on it", () => {
+ const rows = [
+ row("acme_dev", "2026-09-01-deleted", "assigned"),
+ row("acme_dev", "2026-09-01-also-gone", "blocker_closed"),
+ ];
+ const lines = deskDigest(rows, []).split("\n");
+ expect(lines[1]).toBe("- 2026-09-01-deleted (ticket removed): assigned to you");
+ expect(lines[2]).toBe("- 2026-09-01-also-gone (ticket removed): blocker closed");
+ });
+
+ it("takes one line of a long reason, capped, so a list item stays a list item", () => {
+ const reason = `${"a".repeat(200)}\nthe second line`;
+ const rows = [row("acme_dev", "2026-09-01-long", "rejected")];
+ const line = deskDigest(rows, [
+ ticket("2026-09-01-long", "Long", { status: "rejected", result: reason }),
+ ]).split("\n")[1]!;
+ expect(line).toBe(`- 2026-09-01-long (Long): rejected — "${"a".repeat(119)}…"`);
+ expect(line).not.toContain("the second line");
+ });
+});
diff --git a/packages/server/test/organization-files.test.ts b/packages/server/test/organization-files.test.ts
new file mode 100644
index 00000000..bd88cd5d
--- /dev/null
+++ b/packages/server/test/organization-files.test.ts
@@ -0,0 +1,519 @@
+/**
+ * Organization file formats (src/organization): every intent and fact file round-trips
+ * through its serializer and parser, hand-edit tolerance is the same set of rules the API
+ * writes under, and the timezone arithmetic behind budget periods and message days is exact.
+ */
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import {
+ detectLanguage,
+ extractMentionTokens,
+ orgLanguage,
+ parseCalendarEvent,
+ parseChannelConfig,
+ parseChannelMessageLine,
+ parseDesks,
+ parseOrgChart,
+ parseOrgConfig,
+ parseTicket,
+ serializeCalendarEvent,
+ serializeChannelConfig,
+ serializeChannelMessageLine,
+ serializeDesks,
+ serializeOrgChart,
+ serializeOrgConfig,
+ serializeTicket,
+ slugSuffix,
+ slugify,
+ subordinatesOf,
+ ancestorsOf,
+} from "../src/organization/files.js";
+import type { ChannelConfig, OrgChart, OrgConfig, TicketDoc } from "../src/organization/files.js";
+import {
+ formatPrincipal,
+ parsePrincipal,
+ splitPrincipalList,
+} from "../src/organization/principal.js";
+import {
+ DEFAULT_CHANNEL_ID,
+ channelConfigPath,
+ channelDayPath,
+ isChannelId,
+ normalizeWorkspaceSpec,
+ ticketMonth,
+ ticketPath,
+} from "../src/organization/paths.js";
+import {
+ zonedDate,
+ zonedMonthRange,
+ zonedOffsetMinutes,
+ zonedPeriodRange,
+} from "../src/organization/zoned.js";
+
+const config: OrgConfig = {
+ name: "Acme",
+ mission: "Build a marketplace",
+ status: "active",
+ timezone: "Asia/Shanghai",
+ approvalMode: "allow-all",
+ mentionChainLimit: 3,
+ budgetWarnRatio: 0.8,
+ budgetPauseRatio: 1,
+ createdBy: "alice",
+};
+
+const chart: OrgChart = {
+ employees: [
+ { agentId: "acme_ceo", title: "CEO", reportsTo: null, workspace: ".", budget: 200 },
+ { agentId: "acme_hr", title: "HR", reportsTo: "acme_ceo", workspace: "people", budget: 30 },
+ {
+ agentId: "acme_dev",
+ title: "Developer",
+ reportsTo: "acme_hr",
+ duties: "Build the site",
+ workspace: "site",
+ model: { provider: "custom", modelId: "m-dev" },
+ },
+ ],
+};
+
+describe("org_config.toml", () => {
+ it("round-trips and applies defaults for omitted fields", () => {
+ const parsed = parseOrgConfig(serializeOrgConfig(config));
+ expect(parsed).toEqual({ ok: true, value: config });
+ const minimal = parseOrgConfig('name = "Acme"\nmission = "x"\ncreated_by = "alice"\n');
+ expect(minimal.ok && minimal.value.status).toBe("active");
+ expect(minimal.ok && minimal.value.mentionChainLimit).toBe(3);
+ expect(minimal.ok && minimal.value.timezone).toBe("UTC");
+ });
+
+ it("round-trips the working language and rejects anything but zh or en", () => {
+ const zh = parseOrgConfig(serializeOrgConfig({ ...config, language: "zh" }));
+ expect(zh).toEqual({ ok: true, value: { ...config, language: "zh" } });
+ expect(
+ parseOrgConfig('name = "A"\nmission = "x"\ncreated_by = "u"\nlanguage = "fr"\n').ok,
+ ).toBe(false);
+ });
+
+ it("rejects a bad status, timezone or ratio", () => {
+ expect(parseOrgConfig('name = "A"\nmission = ""\ncreated_by = "u"\nstatus = "off"\n').ok).toBe(
+ false,
+ );
+ expect(
+ parseOrgConfig('name = "A"\nmission = ""\ncreated_by = "u"\ntimezone = "Mars/Olympus"\n').ok,
+ ).toBe(false);
+ expect(
+ parseOrgConfig('name = "A"\nmission = ""\ncreated_by = "u"\nbudget_warn_ratio = 0\n').ok,
+ ).toBe(false);
+ expect(parseOrgConfig("name = [\n").ok).toBe(false);
+ });
+});
+
+describe("the working language", () => {
+ it("reads zh from one Han character anywhere and en from everything else", () => {
+ expect(detectLanguage("做一个插件 Marketplace")).toBe("zh");
+ expect(detectLanguage("Build a marketplace")).toBe("en");
+ expect(detectLanguage("Marketplace(插件)")).toBe("zh");
+ expect(detectLanguage("")).toBe("en");
+ // Kana alone is not Han: only Chinese has a template here.
+ expect(detectLanguage("マーケット")).toBe("en");
+ });
+
+ it("falls back to the mission, so an organization written without the field still has one", () => {
+ expect(orgLanguage({ ...config, mission: "做一个插件市场" })).toBe("zh");
+ expect(orgLanguage({ ...config, mission: "Build a marketplace" })).toBe("en");
+ // The field wins over the mission: a Chinese mission may still be run in English.
+ expect(orgLanguage({ ...config, mission: "做一个插件市场", language: "en" })).toBe("en");
+ });
+});
+
+describe("org_chart.yaml", () => {
+ it("round-trips the tree with budgets and models", () => {
+ const parsed = parseOrgChart(serializeOrgChart(chart), "acme");
+ expect(parsed).toEqual({ ok: true, value: chart });
+ });
+
+ it("requires exactly one root and that it is the CEO", () => {
+ const noRoot =
+ "employees:\n - agent_id: acme_ceo\n title: CEO\n reports_to: acme_hr\n - agent_id: acme_hr\n title: HR\n reports_to: acme_ceo\n";
+ expect(parseOrgChart(noRoot, "acme").ok).toBe(false);
+ const wrongRoot =
+ "employees:\n - agent_id: acme_boss\n title: Boss\n reports_to: null\n";
+ const r = parseOrgChart(wrongRoot, "acme");
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("acme_ceo");
+ });
+
+ it("rejects unknown managers, duplicates and cycles", () => {
+ const unknown =
+ "employees:\n - agent_id: acme_ceo\n title: CEO\n reports_to: null\n - agent_id: acme_hr\n title: HR\n reports_to: nobody\n";
+ expect(parseOrgChart(unknown, "acme").ok).toBe(false);
+ const dup =
+ "employees:\n - agent_id: acme_ceo\n title: CEO\n reports_to: null\n - agent_id: acme_ceo\n title: CEO\n reports_to: null\n";
+ expect(parseOrgChart(dup, "acme").ok).toBe(false);
+ const cycle =
+ "employees:\n - agent_id: acme_ceo\n title: CEO\n reports_to: null\n - agent_id: a\n title: A\n reports_to: b\n - agent_id: b\n title: B\n reports_to: a\n";
+ expect(parseOrgChart(cycle, "acme").ok).toBe(false);
+ });
+
+ it("walks the reporting line both ways", () => {
+ expect(subordinatesOf(chart, "acme_ceo")).toEqual(["acme_hr", "acme_dev"]);
+ expect(subordinatesOf(chart, "acme_dev")).toEqual([]);
+ expect(ancestorsOf(chart, "acme_dev")).toEqual(["acme_hr", "acme_ceo"]);
+ expect(ancestorsOf(chart, "acme_ceo")).toEqual([]);
+ });
+});
+
+describe("desks.toml", () => {
+ it("round-trips the ledger with renewal history", () => {
+ const desks = {
+ acme_ceo: {
+ sessionId: "session-2026-09-01-09-00-00-a1b2c3d4",
+ workspace: "/tmp/ws",
+ openedAt: "2026-09-01T01:00:00.000Z",
+ previous: ["session-2026-08-01-09-00-00-00000000"],
+ },
+ };
+ expect(parseDesks(serializeDesks(desks))).toEqual({ ok: true, value: desks });
+ expect(parseDesks("")).toEqual({ ok: true, value: {} });
+ });
+});
+
+describe("calendar events", () => {
+ it("accepts the schedule fields plus a title and rejects target fields", () => {
+ const raw = serializeCalendarEvent({
+ title: "Morning sweep",
+ prompt: "Look at the board",
+ enabled: true,
+ startAt: "2026-09-01T09:00:00+08:00",
+ period: "1d",
+ });
+ const parsed = parseCalendarEvent("sweep", raw);
+ expect(parsed.ok).toBe(true);
+ if (parsed.ok) {
+ expect(parsed.value.title).toBe("Morning sweep");
+ expect(parsed.value.periodMs).toBe(86_400_000);
+ expect(parsed.value.name).toBe("sweep");
+ }
+ const bad = parseCalendarEvent("sweep", `${raw}session_id = "session-x"\n`);
+ expect(bad.ok).toBe(false);
+ if (!bad.ok) expect(bad.error).toContain("session_id");
+ });
+});
+
+describe("tickets", () => {
+ const doc: TicketDoc = {
+ title: "Launch the site",
+ status: "in_progress",
+ owner: "agent:acme_dev",
+ parent: "2026-09-01-marketplace",
+ notify: ["agent:acme_ceo", "user:alice"],
+ priority: "P1",
+ due: "2026-09-15",
+ blocked: "Domain not confirmed",
+ blockedBy: "user:alice",
+ sessions: ["session-2026-09-02-10-00-00-a1b2c3d4"],
+ history: [
+ { at: "2026-09-02T09:00:00Z", by: "user:alice", action: "created" },
+ { at: "2026-09-02T09:01:00Z", by: "user:alice", action: "assigned", note: "agent:acme_dev" },
+ {
+ at: "2026-09-02T10:12:00Z",
+ by: "agent:acme_dev",
+ action: "progress",
+ note: "scaffolded the site",
+ },
+ ],
+ goal: "Ship the marketplace site.",
+ acceptanceCriteria: "- Home page lists plugins\n- Search works",
+ progress: ["scaffolded the site under /srv/site"],
+ result: "",
+ extra: {},
+ extraSections: [],
+ };
+
+ it("round-trips the frontmatter and the four sections", () => {
+ const text = serializeTicket(doc);
+ expect(text.startsWith("---\ntitle: Launch the site\nstatus: in_progress\n")).toBe(true);
+ // Lists stay on one line and a history entry is one flow mapping: the file is hand-read.
+ expect(text).toContain("notify: [agent:acme_ceo, user:alice]");
+ expect(text).toContain(" - {at: 2026-09-02T09:00:00Z, by: user:alice, action: created}\n");
+ expect(text).toContain("## Progress\n- scaffolded the site under /srv/site\n");
+ expect(parseTicket(text)).toEqual({ ok: true, value: doc });
+ });
+
+ it("defaults notify to the owner and priority to P2, keeps unknown fields and sections", () => {
+ const text = [
+ "---",
+ "title: Minimal",
+ "status: proposed",
+ "owner: agent:acme_ceo",
+ "x_custom: kept",
+ "---",
+ "",
+ "## Goal",
+ "Do the thing",
+ "",
+ "## Notes",
+ "extra",
+ "",
+ ].join("\n");
+ const parsed = parseTicket(text);
+ expect(parsed.ok).toBe(true);
+ if (!parsed.ok) return;
+ expect(parsed.value.notify).toEqual(["agent:acme_ceo"]);
+ expect(parsed.value.priority).toBe("P2");
+ expect(parsed.value.history).toEqual([]);
+ expect(parsed.value.extra).toEqual({ x_custom: "kept" });
+ expect(parsed.value.extraSections).toEqual([{ heading: "Notes", body: "extra" }]);
+ const again = parseTicket(serializeTicket(parsed.value));
+ expect(again).toEqual(parsed);
+ });
+
+ it("rejects a bad status, owner, history action or opening fence", () => {
+ expect(parseTicket("---\ntitle: x\nstatus: flying\nowner: user:a\n---\n").ok).toBe(false);
+ expect(parseTicket("---\ntitle: x\nstatus: done\nowner: alice\n---\n").ok).toBe(false);
+ expect(parseTicket("---\ntitle: x\nstatus: done\nowner: user:a\n").ok).toBe(false);
+ const badAction = parseTicket(
+ "---\ntitle: x\nstatus: done\nowner: user:a\nhistory: [{at: t, by: user:a, action: danced}]\n---\n",
+ );
+ expect(badAction.ok).toBe(false);
+ if (!badAction.ok) expect(badAction.error).toContain("danced");
+ expect(parseTicket("status: done\n").ok).toBe(false);
+ });
+
+ it("reads a ticket in the format that predates the frontmatter, and converts it on write", () => {
+ const legacy = [
+ "# Ticket: Launch the site",
+ "",
+ "Status: in_progress",
+ "Initiator: agent:acme_ceo",
+ "Owner:",
+ "X-Custom: kept",
+ "",
+ "## Goal",
+ "Ship it",
+ "",
+ "## Progress",
+ "- 2026-09-02T10:12:00+08:00 agent:acme_dev scaffolded the site session:session-x",
+ "- 2026-09-02T11:00:00+08:00 user:alice reviewed the copy",
+ "",
+ ].join("\n");
+ const parsed = parseTicket(legacy);
+ expect(parsed.ok).toBe(true);
+ if (!parsed.ok) return;
+ // No Owner header: the ticket belongs to whoever filed it, and Notify follows the owner.
+ expect(parsed.value.owner).toBe("agent:acme_ceo");
+ expect(parsed.value.notify).toEqual(["agent:acme_ceo"]);
+ // The operator and the time leave the prose for the history; the sentence stays.
+ expect(parsed.value.progress).toEqual(["scaffolded the site", "reviewed the copy"]);
+ expect(parsed.value.history).toEqual([
+ { at: "2026-09-02T10:12:00+08:00", by: "agent:acme_ceo", action: "created" },
+ {
+ at: "2026-09-02T10:12:00+08:00",
+ by: "agent:acme_dev",
+ action: "progress",
+ note: "scaffolded the site",
+ },
+ {
+ at: "2026-09-02T11:00:00+08:00",
+ by: "user:alice",
+ action: "progress",
+ note: "reviewed the copy",
+ },
+ ]);
+ expect(parsed.value.extra).toEqual({ "X-Custom": "kept" });
+ // Written back, it is a frontmatter file that parses to the same document.
+ const converted = serializeTicket(parsed.value);
+ expect(converted.startsWith("---\n")).toBe(true);
+ expect(parseTicket(converted)).toEqual(parsed);
+ });
+
+ it("derives ids: letters-only slugs, letter suffixes, month and path", () => {
+ expect(slugify("Launch the Site! v2")).toBe("launch-the-site-v");
+ expect(slugify("上线站点")).toBe("");
+ // Six words at most, twenty characters each.
+ expect(slugify("one two three four five six seven")).toBe("one-two-three-four-five-six");
+ expect(slugify("Supercalifragilisticexpialidocious plan")).toBe("supercalifragilistic-plan");
+ expect(slugSuffix(2)).toBe("b");
+ expect(slugSuffix(26)).toBe("z");
+ expect(slugSuffix(27)).toBe("aa");
+ expect(ticketMonth("2026-09-02-site")).toBe("2026-09");
+ // Joined the way the store joins it, so the assertion holds on Windows too.
+ expect(ticketPath("/org", "2026-09-02-site", "review")).toBe(
+ path.join("/org", "tickets", "2026-09", "review", "2026-09-02-site.md"),
+ );
+ });
+});
+
+describe("channel files", () => {
+ const site: ChannelConfig = {
+ name: "Site launch",
+ purpose: "Everything about shipping the marketplace site",
+ createdBy: "user:alice",
+ createdAt: "2026-09-03T01:00:00.000Z",
+ archived: false,
+ members: ["user:alice", "agent:acme_dev"],
+ };
+
+ it("round-trips a member channel and the all-hands channel", () => {
+ const raw = serializeChannelConfig(site);
+ expect(raw).toContain('members = [ "user:alice", "agent:acme_dev" ]');
+ expect(parseChannelConfig("site", raw)).toEqual({ ok: true, value: site });
+
+ const all: ChannelConfig = {
+ name: "All hands",
+ purpose: "",
+ createdBy: "system",
+ createdAt: "2026-09-03T01:00:00.000Z",
+ archived: false,
+ everyone: true,
+ };
+ const allRaw = serializeChannelConfig(all);
+ expect(allRaw).toContain("everyone = true");
+ expect(allRaw).not.toContain("members =");
+ expect(parseChannelConfig(DEFAULT_CHANNEL_ID, allRaw)).toEqual({ ok: true, value: all });
+ });
+
+ it("tolerates a hand edit: a bare datetime, a missing purpose, archived", () => {
+ const raw = [
+ 'name = "Marketing"',
+ 'created_by = "agent:acme_ceo"',
+ "created_at = 2026-09-03T01:00:00Z",
+ "archived = true",
+ 'members = ["agent:acme_marketing"]',
+ ].join("\n");
+ expect(parseChannelConfig("marketing", raw)).toEqual({
+ ok: true,
+ value: {
+ name: "Marketing",
+ purpose: "",
+ createdBy: "agent:acme_ceo",
+ createdAt: "2026-09-03T01:00:00.000Z",
+ archived: true,
+ members: ["agent:acme_marketing"],
+ },
+ });
+ });
+
+ it("rejects what the API would never write", () => {
+ const errorOf = (channelId: string, lines: string[]): string => {
+ const r = parseChannelConfig(channelId, lines.join("\n"));
+ expect(r.ok).toBe(false);
+ return r.ok ? "" : r.error;
+ };
+ const base = [
+ 'name = "Site"',
+ 'created_by = "user:alice"',
+ 'created_at = "2026-09-03T01:00:00Z"',
+ ];
+ expect(errorOf("site", ['name = ""', ...base.slice(1), "members = []"])).toContain("name");
+ expect(errorOf("site", [...base, "members = []", "created_by = 1"])).toContain("created_by");
+ expect(
+ errorOf("site", ['name = "Site"', 'created_by = "all"', base[2]!, "members = []"]),
+ ).toContain("created_by");
+ expect(
+ errorOf("site", [
+ 'name = "Site"',
+ 'created_by = "user:alice"',
+ 'created_at = "soon"',
+ "members = []",
+ ]),
+ ).toContain("created_at");
+ // Membership: a bad principal, a duplicate, and no list at all.
+ expect(errorOf("site", [...base, 'members = ["acme_dev"]'])).toContain("not a principal");
+ expect(errorOf("site", [...base, 'members = ["agent:acme_dev", "agent:acme_dev"]'])).toContain(
+ "duplicate member",
+ );
+ expect(errorOf("site", base)).toContain("members must be a list");
+ // `everyone` belongs to the all-hands channel and to no other, and it keeps no list.
+ expect(errorOf("site", [...base, "everyone = true"])).toContain("all-hands channel");
+ expect(errorOf(DEFAULT_CHANNEL_ID, [...base, "members = []"])).toContain("everyone = true");
+ expect(
+ errorOf(DEFAULT_CHANNEL_ID, [...base, "everyone = true", 'members = ["user:alice"]']),
+ ).toContain("keeps no members list");
+ });
+
+ it("names a channel's directory, config and day file", () => {
+ expect(isChannelId("site")).toBe(true);
+ expect(isChannelId(DEFAULT_CHANNEL_ID)).toBe(true);
+ expect(isChannelId("Site")).toBe(false);
+ expect(isChannelId("a")).toBe(false);
+ expect(isChannelId("site-launch")).toBe(false);
+ expect(channelConfigPath("/org", "site")).toBe(
+ path.join("/org", "channels", "site", "channel.toml"),
+ );
+ expect(channelDayPath("/org", DEFAULT_CHANNEL_ID, "2026-09-03")).toBe(
+ path.join("/org", "channels", "default_channel", "2026-09-03.jsonl"),
+ );
+ });
+});
+
+describe("workspace specs", () => {
+ it("spells one partition one way, and leaves an absolute path alone", () => {
+ expect(normalizeWorkspaceSpec("./hr")).toBe("hr");
+ expect(normalizeWorkspaceSpec("hr/")).toBe("hr");
+ expect(normalizeWorkspaceSpec(".//hr//people/")).toBe("hr/people");
+ expect(normalizeWorkspaceSpec(" hr ")).toBe("hr");
+ expect(normalizeWorkspaceSpec(".")).toBe(".");
+ expect(normalizeWorkspaceSpec("./")).toBe(".");
+ expect(normalizeWorkspaceSpec("")).toBe(".");
+ // Not ours to rewrite, and still refused later if it does not exist.
+ expect(normalizeWorkspaceSpec("../outside")).toBe("../outside");
+ });
+});
+
+describe("channel message lines", () => {
+ it("round-trips a message with refs and rejects malformed lines", () => {
+ const msg = {
+ id: "msg-2026-09-01-09-05-12-a1b2c3d4",
+ time: "2026-09-01T01:05:12.000Z",
+ sender: "agent:acme_hr",
+ hop: 1,
+ text: "@acme_ceo hired acme_dev",
+ mentions: ["agent:acme_ceo"],
+ refs: { ticket: "2026-09-01-site", replyTo: "msg-2026-09-01-09-00-00-00000000" },
+ };
+ const line = serializeChannelMessageLine(msg);
+ expect(line).toContain('"reply_to"');
+ expect(parseChannelMessageLine(line)).toEqual({ ok: true, value: msg });
+ expect(parseChannelMessageLine("{").ok).toBe(false);
+ expect(parseChannelMessageLine(JSON.stringify({ ...msg, hop: -1 })).ok).toBe(false);
+ expect(parseChannelMessageLine(JSON.stringify({ ...msg, sender: "nobody" })).ok).toBe(false);
+ });
+
+ it("extracts mention tokens in short and prefixed forms", () => {
+ expect(
+ extractMentionTokens("@acme_ceo please review @user:alice and @all, not [email protected]"),
+ ).toEqual([{ id: "acme_ceo" }, { prefix: "user", id: "alice" }, { id: "all" }]);
+ });
+});
+
+describe("principals", () => {
+ it("parses and formats the four forms", () => {
+ expect(parsePrincipal("agent:acme_ceo")).toEqual({ kind: "agent", id: "acme_ceo" });
+ expect(parsePrincipal("user:alice")).toEqual({ kind: "user", id: "alice" });
+ expect(parsePrincipal("all")).toEqual({ kind: "all" });
+ expect(parsePrincipal("system")).toEqual({ kind: "system" });
+ expect(parsePrincipal("acme_ceo")).toBeNull();
+ expect(formatPrincipal({ kind: "user", id: "alice" })).toBe("user:alice");
+ expect(splitPrincipalList(" agent:a, user:b ,agent:a,")).toEqual(["agent:a", "user:b"]);
+ });
+});
+
+describe("zoned time", () => {
+ it("names days and months in the organization's timezone", () => {
+ const ms = Date.parse("2026-08-31T20:30:00Z");
+ expect(zonedDate("Asia/Shanghai", ms)).toBe("2026-09-01");
+ expect(zonedDate("UTC", ms)).toBe("2026-08-31");
+ expect(zonedOffsetMinutes("Asia/Shanghai", ms)).toBe(480);
+ });
+
+ it("bounds the natural month by UTC instants", () => {
+ const r = zonedMonthRange("Asia/Shanghai", Date.parse("2026-09-15T00:00:00Z"));
+ expect(r.period).toBe("2026-09");
+ expect(new Date(r.fromMs).toISOString()).toBe("2026-08-31T16:00:00.000Z");
+ expect(new Date(r.toMs).toISOString()).toBe("2026-09-30T16:00:00.000Z");
+ expect(zonedPeriodRange("UTC", "2026-12")?.toMs).toBe(Date.UTC(2027, 0, 1));
+ expect(zonedPeriodRange("UTC", "2026-13")).toBeNull();
+ });
+});
diff --git a/packages/server/test/organization-notices.test.ts b/packages/server/test/organization-notices.test.ts
new file mode 100644
index 00000000..6f4cc11c
--- /dev/null
+++ b/packages/server/test/organization-notices.test.ts
@@ -0,0 +1,141 @@
+/**
+ * Structured `system` lines: each builder returns the English sentence and its structured
+ * twin together, and a message line carries the notice through the file and back. A line
+ * written before the field existed still parses, and a kind this build does not know is
+ * carried as written rather than rejected.
+ */
+import { describe, expect, it } from "vitest";
+import { parseChannelMessageLine, serializeChannelMessageLine } from "../src/organization/files.js";
+import {
+ budgetPaused,
+ budgetWarned,
+ channelArchiveChanged,
+ channelCreated,
+ channelMemberAdded,
+ channelMemberRemoved,
+ employeeJoined,
+ employeeLeft,
+ systemMessage,
+} from "../src/runtime/organization/notices.js";
+
+const ID = "msg-2026-09-01-10-00-00-0000000a";
+
+describe("organization system notices", () => {
+ it("builds the sentence and the structure from the same facts", () => {
+ expect(employeeJoined("agent:acme_hr", "HR", "agent:acme_ceo")).toEqual({
+ text: "agent:acme_hr joined as HR, reporting to agent:acme_ceo.",
+ notice: {
+ kind: "employee_joined",
+ params: { agent: "agent:acme_hr", title: "HR", reportsTo: "agent:acme_ceo" },
+ },
+ });
+ expect(employeeLeft("agent:acme_hr", "agent:acme_ceo").notice.kind).toBe("employee_left");
+ expect(channelCreated("user:alice").notice).toEqual({
+ kind: "channel_created",
+ params: { by: "user:alice" },
+ });
+ expect(channelArchiveChanged("user:alice", true).notice.kind).toBe("channel_archived");
+ expect(channelArchiveChanged("user:alice", false).notice.kind).toBe("channel_unarchived");
+ });
+
+ it("distinguishes joining from being invited, and leaving from being removed", () => {
+ expect(channelMemberAdded("user:alice", "user:alice")).toEqual({
+ text: "user:alice joined the channel.",
+ notice: { kind: "channel_joined", params: { principal: "user:alice" } },
+ });
+ expect(channelMemberAdded("user:alice", "agent:acme_hr")).toEqual({
+ text: "user:alice invited agent:acme_hr to the channel.",
+ notice: {
+ kind: "channel_invited",
+ params: { by: "user:alice", principal: "agent:acme_hr" },
+ },
+ });
+ expect(channelMemberRemoved("agent:acme_hr", "agent:acme_hr").notice.kind).toBe("channel_left");
+ expect(channelMemberRemoved("user:alice", "agent:acme_hr").notice.kind).toBe("channel_removed");
+ });
+
+ it("carries the budget figures as the sentence prints them", () => {
+ const facts = { agent: "agent:acme_hr", period: "2026-09", percent: 85, cost: 8.5, budget: 10 };
+ expect(budgetWarned(facts)).toEqual({
+ text: "Budget warning: agent:acme_hr has used 85% of its 2026-09 budget (8.50 / 10.00 USD).",
+ notice: {
+ kind: "budget_warned",
+ params: {
+ agent: "agent:acme_hr",
+ period: "2026-09",
+ percent: "85",
+ cost: "8.50",
+ budget: "10.00",
+ },
+ },
+ });
+ expect(budgetPaused(facts).text).toContain("Budget pause: agent:acme_hr reached 85%");
+ expect(budgetPaused(facts).notice.kind).toBe("budget_paused");
+ });
+
+ it("still reads a ticket line written before the board stopped narrating itself", () => {
+ // Nothing writes these any more; the lines already in an organization's files must render.
+ const line = serializeChannelMessageLine({
+ id: ID,
+ time: "2026-09-01T10:00:00.000Z",
+ sender: "system",
+ hop: 0,
+ text: "Ticket 2026-09-01-site (Site) is now done",
+ mentions: [],
+ notice: { kind: "ticket_done", params: { ticket: "2026-09-01-site", title: "Site" } },
+ });
+ const parsed = parseChannelMessageLine(line);
+ expect(parsed.ok).toBe(true);
+ if (parsed.ok) expect(parsed.value.notice?.kind).toBe("ticket_done");
+ });
+
+ it("round-trips a notice through a message line", () => {
+ const msg = {
+ id: ID,
+ time: "2026-09-01T10:00:00.000Z",
+ ...systemMessage(employeeJoined("agent:acme_hr", "HR", "agent:acme_ceo")),
+ refs: { ticket: "2026-09-01-site" },
+ };
+ const parsed = parseChannelMessageLine(serializeChannelMessageLine(msg));
+ expect(parsed).toEqual({ ok: true, value: msg });
+ });
+
+ it("parses a line written before the field existed, and keeps a kind it does not know", () => {
+ const base = {
+ id: ID,
+ time: "2026-09-01T10:00:00.000Z",
+ sender: "system",
+ hop: 0,
+ text: "agent:acme_hr joined as HR, reporting to agent:acme_ceo.",
+ mentions: [],
+ };
+ const old = parseChannelMessageLine(JSON.stringify(base));
+ expect(old).toEqual({ ok: true, value: base });
+ // A newer server's kind still parses; the client falls back to `text` for it.
+ const future = parseChannelMessageLine(
+ JSON.stringify({ ...base, notice: { kind: "office_moved", params: { to: "Berlin" } } }),
+ );
+ expect(future).toMatchObject({
+ ok: true,
+ value: { notice: { kind: "office_moved", params: { to: "Berlin" } } },
+ });
+ // Params default to none, and a malformed notice is a malformed line.
+ expect(parseChannelMessageLine(JSON.stringify({ ...base, notice: { kind: "x" } }))).toEqual({
+ ok: true,
+ value: { ...base, notice: { kind: "x", params: {} } },
+ });
+ for (const notice of [
+ { params: {} },
+ { kind: "", params: {} },
+ { kind: "x", params: [] },
+ "x",
+ ]) {
+ expect(parseChannelMessageLine(JSON.stringify({ ...base, notice }))).toMatchObject({
+ ok: false,
+ });
+ }
+ expect(
+ parseChannelMessageLine(JSON.stringify({ ...base, notice: { kind: "x", params: { n: 1 } } })),
+ ).toMatchObject({ ok: false });
+ });
+});
diff --git a/packages/server/test/organization-rota.test.ts b/packages/server/test/organization-rota.test.ts
new file mode 100644
index 00000000..1c048417
--- /dev/null
+++ b/packages/server/test/organization-rota.test.ts
@@ -0,0 +1,120 @@
+/**
+ * Rota advice for a calendar write: a start minute another employee's recurring event
+ * already holds, a second recurring event on the same cadence for one employee, and the
+ * `--start-at now` habit that pins every event scheduled that way to one minute. The minute
+ * is read in the organization's timezone, and a disabled event is nobody's rota.
+ */
+import { describe, expect, it } from "vitest";
+import { rotaWarnings } from "../src/runtime/organization/rota.js";
+import type { RotaEvent } from "../src/runtime/organization/rota.js";
+
+const TZ = "Asia/Shanghai";
+const NOW = Date.parse("2026-09-01T01:00:00Z");
+
+function event(over: Partial<RotaEvent> & Pick<RotaEvent, "agentId" | "name">): RotaEvent {
+ return {
+ enabled: true,
+ startAt: "2026-09-02T10:00:00+08:00",
+ period: "1d",
+ ...over,
+ };
+}
+
+describe("rotaWarnings", () => {
+ it("names another employee's recurring event on the same start minute", () => {
+ const hr = event({ agentId: "acme_hr", name: "hr-audit" });
+ const dev = event({ agentId: "acme_dev", name: "daily-sweep" });
+ expect(rotaWarnings([hr, dev], dev, NOW, TZ)).toEqual([
+ "`acme_hr/hr-audit` also fires at 10:00; give every employee its own minute.",
+ ]);
+ // The minute is the organization's, not UTC: the same instant written with another
+ // offset is the same minute, and half an hour later is a different one.
+ const sameMinute = event({
+ agentId: "acme_dev",
+ name: "daily-sweep",
+ startAt: "2026-09-02T02:00:00Z",
+ });
+ expect(rotaWarnings([hr, sameMinute], sameMinute, NOW, TZ)).toHaveLength(1);
+ const staggered = event({
+ agentId: "acme_dev",
+ name: "daily-sweep",
+ startAt: "2026-09-02T10:30:00+08:00",
+ });
+ expect(rotaWarnings([hr, staggered], staggered, NOW, TZ)).toEqual([]);
+ });
+
+ it("ignores a disabled or one-shot neighbour, and the written event's own row", () => {
+ const disabled = event({ agentId: "acme_hr", name: "hr-audit", enabled: false });
+ const oneShot = event({ agentId: "acme_ops", name: "kickoff", period: undefined });
+ const dev = event({ agentId: "acme_dev", name: "daily-sweep" });
+ expect(rotaWarnings([disabled, oneShot, dev], dev, NOW, TZ)).toEqual([]);
+ // A disabled event is nobody's rota, so writing one says nothing either.
+ const off = event({ agentId: "acme_dev", name: "daily-sweep", enabled: false });
+ const hr = event({ agentId: "acme_hr", name: "hr-audit" });
+ expect(rotaWarnings([hr, off], off, NOW, TZ)).toEqual([]);
+ });
+
+ it("names a second recurring event of the same period on one employee", () => {
+ const first = event({ agentId: "acme_dev", name: "daily-sweep" });
+ const second = event({
+ agentId: "acme_dev",
+ name: "second-sweep",
+ startAt: "2026-09-02T15:00:00+08:00",
+ });
+ expect(rotaWarnings([first, second], second, NOW, TZ)).toEqual([
+ "`acme_dev` already has a recurring event `daily-sweep` with period 1d; one sweep per employee.",
+ ]);
+ // A different cadence beside a daily sweep is what the rota allows.
+ const weekly = event({
+ agentId: "acme_dev",
+ name: "retro",
+ period: "7d",
+ startAt: "2026-09-02T15:00:00+08:00",
+ });
+ expect(rotaWarnings([first, weekly], weekly, NOW, TZ)).toEqual([]);
+ });
+
+ it("flags a recurring event started at 'now', and lets a one-shot one through", () => {
+ const now = event({
+ agentId: "acme_dev",
+ name: "daily-sweep",
+ startAt: new Date(NOW + 30_000).toISOString(),
+ });
+ expect(rotaWarnings([now], now, NOW, TZ)).toEqual([
+ "A recurring event started at 'now' shares its minute with every other event started the same way; pick the role's hour.",
+ ]);
+ const oneShot = { ...now, period: undefined };
+ expect(rotaWarnings([oneShot], oneShot, NOW, TZ)).toEqual([]);
+ const later = event({
+ agentId: "acme_dev",
+ name: "daily-sweep",
+ startAt: new Date(NOW + 600_000).toISOString(),
+ });
+ expect(rotaWarnings([later], later, NOW, TZ)).toEqual([]);
+ });
+
+ it("reports every problem the one write has, in the order to fix them", () => {
+ const hr = event({
+ agentId: "acme_hr",
+ name: "hr-audit",
+ startAt: new Date(NOW).toISOString(),
+ });
+ const existing = event({ agentId: "acme_dev", name: "daily-sweep" });
+ const written = event({
+ agentId: "acme_dev",
+ name: "extra-sweep",
+ startAt: new Date(NOW).toISOString(),
+ });
+ expect(rotaWarnings([hr, existing, written], written, NOW, TZ)).toEqual([
+ expect.stringContaining("`acme_hr/hr-audit` also fires at"),
+ "`acme_dev` already has a recurring event `daily-sweep` with period 1d; one sweep per employee.",
+ "A recurring event started at 'now' shares its minute with every other event started the same way; pick the role's hour.",
+ ]);
+ });
+
+ it("says nothing about an event whose start_at is not an instant", () => {
+ const broken = event({ agentId: "acme_dev", name: "daily-sweep", startAt: "whenever" });
+ const hr = event({ agentId: "acme_hr", name: "hr-audit" });
+ expect(rotaWarnings([hr, broken], broken, NOW, TZ)).toEqual([]);
+ });
+});
diff --git a/packages/server/test/organization-runtime.test.ts b/packages/server/test/organization-runtime.test.ts
new file mode 100644
index 00000000..fcbcc0e0
--- /dev/null
+++ b/packages/server/test/organization-runtime.test.ts
@@ -0,0 +1,2576 @@
+/**
+ * Organization runtime semantics with doubles and a controlled clock — no real LLM, no
+ * core Session: creation writes the files and opens the CEO's desk with an init run; a hire
+ * opens the newcomer's desk and the reconcile pass opens the desks nothing else did (a
+ * hand-added employee, a session deleted from under the ledger); a
+ * calendar event registered after its time is not backfilled and fires on its next slot to
+ * the employee's desk (queued when busy, held when the organization or the employee is
+ * paused, held silently when the master switch is off); ticket changes are noticed once;
+ * channel mentions reach desks and the chain stops at the limit; budgets warn, pause and
+ * resume (a zero budget being over before anything is spent); a ticket session the runner
+ * refuses leaves the ticket as it was; and every pass brings an employee whose company
+ * plugins fell behind the library back up to it.
+ */
+import fs from "node:fs/promises";
+import { wire } from "@prismshadow/penguin-core/kernel";
+import path from "node:path";
+import { beforeEach, describe, expect, it } from "vitest";
+import { parseOrgTriggerMessage, saveProjectConfig } from "@prismshadow/penguin-core";
+import type { OmniMessage } from "@prismshadow/penguin-core";
+import { openDatabase } from "../src/db/database.js";
+import { MembersRepo } from "../src/db/repos/members.js";
+import { OrgCacheRepo } from "../src/db/repos/organizations.js";
+import { ProjectsRepo } from "../src/db/repos/projects.js";
+import { SessionsRepo } from "../src/db/repos/sessions.js";
+import { UsersRepo } from "../src/db/repos/users.js";
+import { OrgStore } from "../src/organization/store.js";
+import { parseChannelConfig, serializeCalendarEvent } from "../src/organization/files.js";
+import { DEFAULT_CHANNEL_ID, ticketPath } from "../src/organization/paths.js";
+import { zonedDate } from "../src/organization/zoned.js";
+import type { ErrorRecordArgs } from "../src/runtime/error-recorder.js";
+import { DEFAULT_EMPLOYEE_PLUGINS } from "../src/runtime/organization/deps.js";
+import type { OrgDeps } from "../src/runtime/organization/deps.js";
+import { OrganizationScheduler } from "../src/runtime/organization/scheduler.js";
+import { OrganizationService } from "../src/runtime/organization/service.js";
+import { ProjectConfigService } from "../src/services/project-config-service.js";
+import type { UtilityCompletion } from "../src/services/project-config-service.js";
+import type { ServerEvent } from "../src/api/types.js";
+import { makeTempRoot } from "./helpers.js";
+
+const P = "p1";
+const ORG = "acme";
+const CEO = "acme_ceo";
+const HR = "acme_hr";
+const T0 = Date.parse("2026-09-01T01:00:00Z");
+const DAY = 86_400_000;
+/** The version the fake plugin library offers; an employee set behind it is what a pass fixes. */
+const LIBRARY_VERSION = "2026.09.14.1";
+
+/** The utility completion's three shapes, as the id proposals see them. */
+const NO_MODEL: UtilityCompletion = {
+ ok: false,
+ cause: "no_model",
+ error: "the Project names no default model",
+};
+const answered = (text: string): UtilityCompletion => ({ ok: true, text });
+const failed = (error: string): UtilityCompletion => ({ ok: false, cause: "failed", error });
+
+interface Started {
+ sessionId: string;
+ text: string;
+ queueIfBusy: boolean;
+}
+
+function textOf(input: OmniMessage[]): string {
+ const first = input[0] as { payload?: { text?: string } } | undefined;
+ return first?.payload?.text ?? "";
+}
+
+describe("organization runtime", () => {
+ let root: string;
+ let db: ReturnType<typeof openDatabase>;
+ let sessions: SessionsRepo;
+ let cache: OrgCacheRepo;
+ let store: OrgStore;
+ let nowMs: number;
+ let busy: Set<string>;
+ /** Set by a test to make every task start throw — a runner that refuses the work. */
+ let startFails: boolean;
+ let started: Started[];
+ let created: Array<{ projectId: string; agentId: string; workspace?: string; client: "org" }>;
+ let agentsCreated: Array<{ agentId: string; plugins: readonly string[] }>;
+ let briefs: Map<string, string>;
+ let costs: Map<string, number>;
+ let events: ServerEvent[];
+ let errors: ErrorRecordArgs[];
+ let companyMode: boolean;
+ /**
+ * The one-off utility completion behind semantic id proposals: the results it hands back in
+ * order, one per call, and every prompt it was given. An exhausted queue answers
+ * NO_MODEL — a Project with nothing configured is what "the model said nothing" means.
+ */
+ let completion: { answers: UtilityCompletion[]; prompts: string[] };
+ let deps: OrgDeps;
+ let scheduler: OrganizationScheduler;
+ let service: OrganizationService;
+ let seq: number;
+ /** The Agents the fake gateway says exist; a test deletes one to make its desk unopenable. */
+ let existingAgents: Set<string>;
+ /**
+ * The plugin library and the Agents' installed copies as the fake gateway answers them:
+ * `library` per plugin name, `installed` keyed `<agentId>:<plugin>` (a hire records the
+ * library's version, so an employee is current until a test sets its entry back),
+ * `updated` every update performed, and `failUpdates` the pairs whose update throws.
+ */
+ let plugins: {
+ library: Map<string, string>;
+ installed: Map<string, string>;
+ updated: Array<{ agentId: string; plugin: string }>;
+ failUpdates: Set<string>;
+ };
+
+ beforeEach(async () => {
+ root = await makeTempRoot();
+ await saveProjectConfig(root, P, {
+ default_model: { provider: "custom", model_id: "m-bench" },
+ models: [{ provider: "custom", model_id: "m-bench" }],
+ });
+ db = openDatabase(":memory:");
+ wire(UsersRepo, { db }).insert({
+ userId: "alice",
+ passwordHash: "x",
+ isAdmin: false,
+ passwordIsInitial: false,
+ displayName: null,
+ avatar: null,
+ createdAt: "2026-08-01T00:00:00Z",
+ });
+ const projects = wire(ProjectsRepo, { db });
+ projects.insert({ projectId: P, ownerUserId: "alice", createdAt: "2026-08-01T00:00:00Z" });
+ sessions = wire(SessionsRepo, { db });
+ cache = wire(OrgCacheRepo, { db });
+ store = new OrgStore(root);
+ nowMs = T0;
+ busy = new Set();
+ startFails = false;
+ started = [];
+ created = [];
+ agentsCreated = [];
+ briefs = new Map();
+ costs = new Map();
+ events = [];
+ errors = [];
+ companyMode = true;
+ completion = { answers: [], prompts: [] };
+ seq = 0;
+ existingAgents = new Set<string>();
+ plugins = {
+ library: new Map(DEFAULT_EMPLOYEE_PLUGINS.map((name) => [name, LIBRARY_VERSION])),
+ installed: new Map(),
+ updated: [],
+ failUpdates: new Set(),
+ };
+ deps = {
+ root,
+ store,
+ cache,
+ projects,
+ members: wire(MembersRepo, { db }),
+ sessions,
+ runner: {
+ statusOf: (id) => (busy.has(id) ? "running" : "idle"),
+ startTask: async (sessionId, input, opts) => {
+ if (startFails) throw new Error("the runner refused the task");
+ started.push({ sessionId, text: textOf(input), queueIfBusy: opts?.queueIfBusy === true });
+ return { sessionId, queued: busy.has(sessionId) };
+ },
+ },
+ sessionCreator: {
+ createSession: async (args) => {
+ seq++;
+ const sessionId = `session-2026-09-01-00-00-0${seq}-0000000${seq}`;
+ created.push({
+ projectId: args.projectId,
+ agentId: args.agentId,
+ ...(args.workspace !== undefined ? { workspace: args.workspace } : {}),
+ client: args.client,
+ });
+ const createdAt = new Date(nowMs).toISOString();
+ sessions.insert({
+ sessionId,
+ projectId: args.projectId,
+ agentId: args.agentId,
+ provider: args.provider ?? "custom",
+ modelId: args.modelId ?? "m-bench",
+ workspace: args.workspace ?? root,
+ approvalMode: args.approvalMode ?? "allow-all",
+ title: null,
+ // The real SessionService stores the caller's hint verbatim; a fake that wrote
+ // "web" here would pass the marker's own test.
+ client: args.client,
+ lastActiveAt: createdAt,
+ createdAt,
+ });
+ return { sessionId, workspace: args.workspace ?? root };
+ },
+ },
+ agents: {
+ exists: async (_p, agentId) => existingAgents.has(agentId),
+ create: async (_p, agentId, _name, _description, seeds) => {
+ existingAgents.add(agentId);
+ agentsCreated.push({ agentId, plugins: seeds });
+ // Creation installs the library's current content, so a fresh hire is never behind.
+ for (const name of seeds) {
+ const version = plugins.library.get(name);
+ if (version !== undefined) plugins.installed.set(`${agentId}:${name}`, version);
+ }
+ },
+ displayName: async (_p, agentId) => `Name of ${agentId}`,
+ writeAgentsMd: async (_p, agentId, content) => {
+ briefs.set(agentId, content);
+ },
+ pluginVersion: async (_p, agentId, plugin) => ({
+ installed: plugins.installed.get(`${agentId}:${plugin}`) ?? null,
+ library: plugins.library.get(plugin) ?? null,
+ }),
+ updatePlugin: async (_p, agentId, plugin) => {
+ if (plugins.failUpdates.has(`${agentId}:${plugin}`)) {
+ throw new Error(`plugin ${plugin} could not be written`);
+ }
+ const version = plugins.library.get(plugin);
+ if (version === undefined) throw new Error(`Plugin is not in the library: ${plugin}`);
+ plugins.installed.set(`${agentId}:${plugin}`, version);
+ plugins.updated.push({ agentId, plugin });
+ },
+ },
+ projectConfig: wire(ProjectConfigService, { paths: { root } }),
+ completeOnce: async (_p, prompt) => {
+ completion.prompts.push(prompt);
+ return completion.answers.shift() ?? NO_MODEL;
+ },
+ usage: {
+ costBySession: async (_p, ids) => ({
+ bySession: new Map(ids.filter((id) => costs.has(id)).map((id) => [id, costs.get(id)!])),
+ unpriced: false,
+ }),
+ dailyCostForSessions: async () => [],
+ },
+ errors: { record: (e) => void errors.push(e) },
+ notifyProject: (_p, event) => void events.push(event),
+ companyModeEnabled: () => companyMode,
+ now: () => nowMs,
+ log: () => {},
+ };
+ scheduler = new OrganizationScheduler(deps, { intervalMs: 1_000_000 });
+ service = new OrganizationService(deps, scheduler);
+ });
+
+ async function createOrg(): Promise<void> {
+ await service.create(
+ P,
+ {
+ orgId: ORG,
+ name: "Acme",
+ mission: "Build a plugin marketplace",
+ timezone: "Asia/Shanghai",
+ },
+ "alice",
+ );
+ }
+
+ const orgDir = (): string => store.dir(P, ORG);
+
+ it("keeps the knowledge base under handbook/: the index first, documents by path, the index undeletable", async () => {
+ await createOrg();
+ const index = await service.handbook(P, ORG);
+ expect(index).toContain("## Knowledge base");
+ expect(index).toContain("## Documents");
+
+ await service.writeHandbookFile(P, ORG, "decisions/2026-09-02-hire-plan.md", "# Hire plan\n");
+ await service.writeHandbookFile(P, ORG, "conventions.md", "# Conventions\n");
+ const listed = (await service.handbookFiles(P, ORG)).files.map((f) => f.path);
+ expect(listed).toEqual(["README.md", "conventions.md", "decisions/2026-09-02-hire-plan.md"]);
+ expect(await service.handbookFile(P, ORG, "decisions/2026-09-02-hire-plan.md")).toEqual({
+ path: "decisions/2026-09-02-hire-plan.md",
+ content: "# Hire plan\n",
+ });
+
+ await expect(service.handbookFile(P, ORG, "../org_config.toml")).rejects.toMatchObject({
+ status: 400,
+ });
+ await expect(service.writeHandbookFile(P, ORG, ".hidden.md", "x")).rejects.toMatchObject({
+ status: 400,
+ });
+ await expect(service.deleteHandbookFile(P, ORG, "README.md")).rejects.toMatchObject({
+ status: 400,
+ });
+ await expect(service.deleteHandbookFile(P, ORG, "missing.md")).rejects.toMatchObject({
+ status: 404,
+ });
+
+ await service.deleteHandbookFile(P, ORG, "decisions/2026-09-02-hire-plan.md");
+ await expect(fs.stat(path.join(orgDir(), "handbook", "decisions"))).rejects.toBeTruthy();
+ expect((await service.handbookFiles(P, ORG)).files.map((f) => f.path)).toEqual([
+ "README.md",
+ "conventions.md",
+ ]);
+ });
+
+ it("creation writes the files, the CEO with its plugins and brief, and opens the desk with an init run", async () => {
+ await createOrg();
+ const dir = orgDir();
+ for (const f of [
+ "org_config.toml",
+ "org_chart.yaml",
+ "handbook/README.md",
+ "desks.toml",
+ "calendar",
+ "tickets",
+ "channels",
+ "channels/default_channel/channel.toml",
+ "workspace",
+ ]) {
+ await expect(fs.stat(path.join(dir, f))).resolves.toBeTruthy();
+ }
+ // The all-hands channel is created with the organization and belongs to everyone.
+ const allChannel = parseChannelConfig(
+ DEFAULT_CHANNEL_ID,
+ await fs.readFile(path.join(dir, "channels", DEFAULT_CHANNEL_ID, "channel.toml"), "utf8"),
+ );
+ expect(allChannel).toMatchObject({
+ ok: true,
+ // The purpose is empty: the UI writes the all-hands line itself, in the reader's language.
+ value: {
+ name: "All hands",
+ purpose: "",
+ createdBy: "system",
+ everyone: true,
+ archived: false,
+ },
+ });
+ expect(agentsCreated).toEqual([
+ { agentId: CEO, plugins: ["agent-company", "agent-development"] },
+ ]);
+ expect(briefs.get(CEO)).toContain(`<app_data_dir>/organizations/${ORG}/`);
+ expect(created).toHaveLength(1);
+ // The shared root is nobody's desk: the CEO gets `ceo/`, made by the init dispatch.
+ expect(created[0]!.workspace).toBe(path.join(dir, "workspace", "ceo"));
+ expect((await fs.stat(path.join(dir, "workspace", "ceo"))).isDirectory()).toBe(true);
+ expect((await service.chart(P, ORG)).employees[0]!.workspace).toBe("ceo");
+ // The CEO is created with a budget, not unbounded: budgets accumulate along the
+ // reporting line, so this one number caps the whole company from the first minute.
+ expect((await service.chart(P, ORG)).employees).toMatchObject([{ agentId: CEO, budget: 100 }]);
+ expect(started).toHaveLength(1);
+ const parsed = parseOrgTriggerMessage(started[0]!.text);
+ expect(parsed?.origin.kind).toBe("init");
+ expect(parsed?.origin.org).toBe(ORG);
+ expect(parsed?.origin.budget).toBe("0.00 / 100.00 USD (0%)");
+ expect(parsed?.rest).toContain("Mission: Build a plugin marketplace");
+ // The board decides: the init run proposes and stops before hiring anything.
+ expect(parsed?.rest).toContain("END THIS RUN");
+ expect(parsed?.rest).toContain("@user:alice");
+ // The mission is English, so the organization works in English — its desk titles too.
+ expect(sessions.findById(started[0]!.sessionId)?.title).toBe(`Name of ${CEO}'s desk`);
+ expect(cache.ownerOfSession(started[0]!.sessionId)).toMatchObject({
+ orgId: ORG,
+ agentId: CEO,
+ kind: "desk",
+ });
+ expect(events.some((e) => e.type === "org_run" && e.kind === "init")).toBe(true);
+ const detail = await service.detail(P, ORG, "alice");
+ expect(detail.employeeCount).toBe(1);
+ expect(detail.ceoDeskSessionId).toBe(started[0]!.sessionId);
+ });
+
+ it("writes the CEO budget creation asked for, zero included", async () => {
+ await service.create(P, { orgId: ORG, mission: "Build it", ceoBudget: 25 }, "alice");
+ expect((await service.chart(P, ORG)).employees[0]).toMatchObject({ agentId: CEO, budget: 25 });
+ // Zero is a real budget (everything is already over it), not a request to be unbounded.
+ await service.create(P, { orgId: "zero", mission: "Build it", ceoBudget: 0 }, "alice");
+ expect((await service.chart(P, "zero")).employees[0]).toMatchObject({ budget: 0 });
+ });
+
+ it("uses the chosen shared workspace and model for desks and ticket sessions", async () => {
+ const shared = path.join(root, "company-ws");
+ await fs.mkdir(shared, { recursive: true });
+ await service.create(
+ P,
+ {
+ orgId: ORG,
+ mission: "Build it",
+ workspace: shared,
+ model: { provider: "custom", modelId: "m-bench" },
+ },
+ "alice",
+ );
+ expect(created[0]!.workspace).toBe(path.join(shared, "ceo"));
+ expect(sessions.findById(started[0]!.sessionId)?.modelId).toBe("m-bench");
+ const detail = await service.detail(P, ORG, "alice");
+ expect(detail.settings.workspace).toBe(shared);
+ expect(detail.settings.model).toEqual({ provider: "custom", modelId: "m-bench" });
+ // A sub-directory of the chosen root is what an employee's relative workspace resolves to.
+ await fs.mkdir(path.join(shared, "site"));
+ const item = await service.hire(P, ORG, {
+ newAgent: { agentId: HR },
+ title: "Dev",
+ reportsTo: CEO,
+ workspace: "site",
+ });
+ expect(item.resolvedWorkspace).toBe(path.join(shared, "site"));
+ await expect(
+ service.create(
+ P,
+ { orgId: "other", mission: "x", workspace: path.join(root, "missing") },
+ "alice",
+ ),
+ ).rejects.toMatchObject({ status: 400 });
+ await expect(
+ service.create(
+ P,
+ { orgId: "other", mission: "x", model: { provider: "custom", modelId: "nope" } },
+ "alice",
+ ),
+ ).rejects.toMatchObject({ status: 400 });
+ });
+
+ it("refuses a taken organization id and cleans up when the CEO cannot be created", async () => {
+ await createOrg();
+ await expect(createOrg()).rejects.toMatchObject({ status: 409, code: "org_exists" });
+ await expect(
+ service.create(P, { orgId: "bad id", mission: "x" }, "alice"),
+ ).rejects.toMatchObject({ code: "invalid_org_id" });
+ });
+
+ it("hires through the API, writes the chart and announces it in the all-hands channel", async () => {
+ await createOrg();
+ await fs.mkdir(path.join(orgDir(), "workspace", "people"));
+ const item = await service.hire(P, ORG, {
+ newAgent: { agentId: HR, name: "HR" },
+ title: "HR",
+ reportsTo: CEO,
+ workspace: "people",
+ budget: 10,
+ });
+ expect(item.agentId).toBe(HR);
+ expect(item.resolvedWorkspace).toBe(path.join(orgDir(), "workspace", "people"));
+ expect(agentsCreated.map((a) => a.agentId)).toEqual([CEO, HR]);
+ const chart = await service.chart(P, ORG);
+ expect(chart.employees.map((e) => e.agentId)).toEqual([CEO, HR]);
+ const allHands = await service.channelMessages(
+ P,
+ ORG,
+ { userId: "alice" },
+ DEFAULT_CHANNEL_ID,
+ {},
+ );
+ const joined = allHands.messages.find(
+ (m) => m.sender === "system" && m.text.includes("agent:acme_hr joined as HR"),
+ );
+ // The sentence for the file and the CLI, the structure for a client that renders it in
+ // the reader's language.
+ expect(joined?.notice).toEqual({
+ kind: "employee_joined",
+ params: { agent: `agent:${HR}`, title: "HR", reportsTo: `agent:${CEO}` },
+ });
+ await expect(
+ service.hire(P, ORG, { agentId: HR, title: "Again", reportsTo: CEO }),
+ ).rejects.toMatchObject({
+ code: "employee_exists",
+ });
+ await expect(
+ service.hire(P, ORG, { agentId: "ghost", title: "X", reportsTo: CEO }),
+ ).rejects.toMatchObject({
+ code: "agent_not_found",
+ });
+ });
+
+ it("hires with the company plugins plus the extra ones asked for, in order and without repeats", async () => {
+ await createOrg();
+ await service.hire(P, ORG, {
+ newAgent: { agentId: HR, plugins: ["web-design", "agent-company"] },
+ title: "Designer",
+ reportsTo: CEO,
+ });
+ // The extras add to the pair rather than replace it: the brief written at hire time tells
+ // the newcomer to follow the company-employee skill, and the pass that keeps plugins
+ // current installs nothing an employee does not already carry — so an employee hired
+ // without agent-company is one nothing repairs.
+ expect(agentsCreated.find((a) => a.agentId === HR)?.plugins).toEqual([
+ "agent-company",
+ "agent-development",
+ "web-design",
+ ]);
+ });
+
+ describe("settings", () => {
+ it("refuses a value the config parser would reject, rather than writing one that stops the organization", async () => {
+ await createOrg();
+ for (const req of [
+ { mentionChainLimit: 101 },
+ { mentionChainLimit: -1 },
+ { mentionChainLimit: 1.5 },
+ { budgetWarnRatio: 0 },
+ { budgetPauseRatio: 11 },
+ ]) {
+ await expect(service.patch(P, ORG, req, "alice")).rejects.toMatchObject({ status: 400 });
+ }
+ // The bounds themselves still pass, and the file stays readable.
+ expect(
+ await service.patch(P, ORG, { mentionChainLimit: 100, budgetPauseRatio: 10 }, "alice"),
+ ).toMatchObject({ mentionChainLimit: 100, budgetPauseRatio: 10 });
+ expect((await service.detail(P, ORG, "alice")).invalid).toBeUndefined();
+ });
+
+ it("repairs a config that no longer parses, and leaves a readable one's creator alone", async () => {
+ await createOrg();
+ const configPath = path.join(orgDir(), "org_config.toml");
+ // Parsable TOML the config parser refuses: the organization loads with every field
+ // defaulted, `created_by` empty among them, and its automation is held.
+ await fs.writeFile(configPath, 'name = "Acme"\nmission = 7\n', "utf8");
+ expect((await service.detail(P, ORG, "alice")).invalid).toContain("org_config.toml");
+
+ const repaired = await service.patch(P, ORG, { mission: "Build it" }, "bob");
+ // Written back with an empty `created_by` the file would not parse either, and the
+ // settings page would report success over an organization that is still stopped.
+ expect(repaired.createdBy).toBe("bob");
+ expect((await service.detail(P, ORG, "alice")).invalid).toBeUndefined();
+
+ const later = await service.patch(P, ORG, { mission: "Build it twice" }, "carol");
+ expect(later.createdBy).toBe("bob");
+ });
+ });
+
+ describe("employee workspaces", () => {
+ it("gives a hire with no workspace its own sub-directory, and still takes an explicit `.`", async () => {
+ await createOrg();
+ const item = await service.hire(P, ORG, {
+ newAgent: { agentId: HR },
+ title: "HR",
+ reportsTo: CEO,
+ });
+ expect(item.workspace).toBe(HR);
+ expect(item.resolvedWorkspace).toBe(path.join(orgDir(), "workspace", HR));
+ expect((await fs.stat(path.join(orgDir(), "workspace", HR))).isDirectory()).toBe(true);
+ const desk = await service.desk(P, ORG, HR, {});
+ expect(desk.workspace).toBe(path.join(orgDir(), "workspace", HR));
+ // The shared root is nobody's desk by default, but it is still assignable on request.
+ const asked = await service.hire(P, ORG, {
+ newAgent: { agentId: "acme_ops" },
+ title: "Ops",
+ reportsTo: CEO,
+ workspace: ".",
+ });
+ expect(asked.workspace).toBe(".");
+ expect(asked.resolvedWorkspace).toBe(path.join(orgDir(), "workspace"));
+ });
+
+ it("creates a relative sub-directory as the employee is hired, and stores one spelling of it", async () => {
+ await createOrg();
+ const item = await service.hire(P, ORG, {
+ newAgent: { agentId: HR },
+ title: "HR",
+ reportsTo: CEO,
+ workspace: "./hr/",
+ });
+ const dir = path.join(orgDir(), "workspace", "hr");
+ // The directory the CEO never created is there, and the chart holds the plain form.
+ expect((await fs.stat(dir)).isDirectory()).toBe(true);
+ expect(item.workspace).toBe("hr");
+ expect(item.resolvedWorkspace).toBe(dir);
+ expect(item.invalid).toBeUndefined();
+ // …and the desk opens in it, which is what `desk_unavailable` used to refuse.
+ const desk = await service.desk(P, ORG, HR, {});
+ expect(desk.workspace).toBe(dir);
+ });
+
+ it("refuses a spec that leaves the shared workspace, and an absolute path nobody created", async () => {
+ await createOrg();
+ await expect(
+ service.hire(P, ORG, {
+ newAgent: { agentId: HR },
+ title: "HR",
+ reportsTo: CEO,
+ workspace: "../outside",
+ }),
+ ).rejects.toMatchObject({ status: 400, code: "invalid_workspace" });
+ await expect(
+ service.hire(P, ORG, {
+ newAgent: { agentId: HR },
+ title: "HR",
+ reportsTo: CEO,
+ workspace: path.join(root, "nowhere"),
+ }),
+ ).rejects.toMatchObject({ status: 400, code: "invalid_workspace" });
+ // Nothing was written for either refusal.
+ expect((await service.chart(P, ORG)).employees.map((e) => e.agentId)).toEqual([CEO]);
+ await expect(fs.stat(path.join(orgDir(), "workspace", "outside"))).rejects.toBeTruthy();
+ });
+
+ it("creates the directory a hand-edited chart names, so the calendar still reaches that desk", async () => {
+ await createOrg();
+ await service.hire(P, ORG, { newAgent: { agentId: HR }, title: "HR", reportsTo: CEO });
+ // A hand edit, as a person or the CEO's file tools would leave it: a partition that
+ // exists only in the file. The chart lists it as usable, and the desk creates it.
+ await fs.writeFile(
+ path.join(orgDir(), "org_chart.yaml"),
+ [
+ "employees:",
+ ` - agent_id: ${CEO}`,
+ " title: CEO",
+ " reports_to: null",
+ " workspace: .",
+ ` - agent_id: ${HR}`,
+ " title: HR",
+ ` reports_to: ${CEO}`,
+ " workspace: people",
+ "",
+ ].join("\n"),
+ "utf8",
+ );
+ const hr = (await service.chart(P, ORG)).employees.find((e) => e.agentId === HR)!;
+ expect(hr.invalid).toBeUndefined();
+ expect(hr.resolvedWorkspace).toBe(path.join(orgDir(), "workspace", "people"));
+ const desk = await service.desk(P, ORG, HR, {});
+ expect(desk.workspace).toBe(path.join(orgDir(), "workspace", "people"));
+ expect((await fs.stat(path.join(orgDir(), "workspace", "people"))).isDirectory()).toBe(true);
+ });
+
+ it("reassigns a partition and creates the new one", async () => {
+ await createOrg();
+ await service.hire(P, ORG, { newAgent: { agentId: HR }, title: "HR", reportsTo: CEO });
+ const item = await service.patchEmployee(P, ORG, HR, { workspace: "./people" });
+ expect(item.workspace).toBe("people");
+ expect((await fs.stat(path.join(orgDir(), "workspace", "people"))).isDirectory()).toBe(true);
+ await expect(
+ service.patchEmployee(P, ORG, HR, { workspace: "../elsewhere" }),
+ ).rejects.toMatchObject({ status: 400, code: "invalid_workspace" });
+ });
+ });
+
+ describe("the working language", () => {
+ const ZH_MISSION = "做一个 DeepSeek Harness 插件市场,并靠首页置顶位盈利。";
+
+ it("follows the mission: a Chinese mission gives a Chinese handbook, brief and init run", async () => {
+ await service.create(P, { orgId: ORG, name: "插件市场", mission: ZH_MISSION }, "alice");
+ const settings = (await service.detail(P, ORG, "alice")).settings;
+ expect(settings.language).toBe("zh");
+ expect(await fs.readFile(path.join(orgDir(), "org_config.toml"), "utf8")).toContain(
+ 'language = "zh"',
+ );
+ const handbook = await service.handbook(P, ORG);
+ expect(handbook).toContain("## 工作语言");
+ expect(handbook).toContain("## 使命");
+ expect(handbook).toContain(ZH_MISSION);
+ // Paths, commands and field names stay ASCII whatever the language is.
+ expect(handbook).toContain("`org_chart.yaml`");
+ expect(handbook).toContain("penguin org ticket start <id>");
+ expect(briefs.get(CEO)).toContain("# 员工简介");
+ expect(briefs.get(CEO)).toContain(`<app_data_dir>/organizations/${ORG}/`);
+ const parsed = parseOrgTriggerMessage(started[0]!.text);
+ expect(parsed?.rest).toContain(`使命:${ZH_MISSION}`);
+ expect(parsed?.rest).toContain("penguin org ticket start <id>");
+ expect(sessions.findById(started[0]!.sessionId)?.title).toBe(`Name of ${CEO} 的工位`);
+ // Hires inherit it: the brief is written in the organization's language, not the request's.
+ await service.hire(P, ORG, { newAgent: { agentId: HR }, title: "人事", reportsTo: CEO });
+ expect(briefs.get(HR)).toContain("# 员工简介");
+ });
+
+ it("takes the request's language over the mission's, and PATCH changes it", async () => {
+ await service.create(P, { orgId: ORG, mission: ZH_MISSION, language: "en" }, "alice");
+ expect(await service.handbook(P, ORG)).toContain("## Working language");
+ const settings = await service.patch(P, ORG, { language: "zh" }, "alice");
+ expect(settings.language).toBe("zh");
+ expect(await fs.readFile(path.join(orgDir(), "org_config.toml"), "utf8")).toContain(
+ 'language = "zh"',
+ );
+ // The handbook is an intent file: a language change never rewrites what the CEO owns.
+ expect(await service.handbook(P, ORG)).toContain("## Working language");
+ });
+
+ it("says English when nothing was ever written, so an old organization still reports one", async () => {
+ await createOrg();
+ const raw = await fs.readFile(path.join(orgDir(), "org_config.toml"), "utf8");
+ await fs.writeFile(
+ path.join(orgDir(), "org_config.toml"),
+ raw.replace('language = "en"\n', ""),
+ "utf8",
+ );
+ expect((await service.detail(P, ORG, "alice")).settings.language).toBe("en");
+ });
+ });
+
+ describe("semantic id proposals", () => {
+ /** `co_org_<yyyymmdd>` / `ch_channel_<yyyymmdd>` for today, which is what a placeholder reads as. */
+ function placeholderFor(kind: "org" | "channel"): string {
+ const now = new Date();
+ const stamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}`;
+ return kind === "org" ? `co_org_${stamp}` : `ch_channel_${stamp}`;
+ }
+
+ it("takes the model's answer, names the ids already taken, and never returns one of them", async () => {
+ completion.answers = [answered("`research_paper_lab`\n")];
+ // The model answers the semantic core; the server puts the kind's prefix on it.
+ expect(await service.suggestId(P, { name: "科研论文公司", kind: "org" })).toEqual({
+ id: "co_research_paper_lab",
+ source: "model",
+ });
+ expect(completion.prompts[0]).toContain("科研论文公司");
+ completion.answers = [answered("site")];
+ expect(
+ await service.suggestId(P, { 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.");
+ // One ask each: a usable answer is never second-guessed.
+ expect(completion.prompts).toHaveLength(2);
+ expect(errors).toEqual([]);
+ });
+
+ it("asks a second time, with the format spelled out, when the first answer is not an id", async () => {
+ completion.answers = [answered("我建议叫「科研实验室」"), answered("research_lab")];
+ expect(await service.suggestId(P, { name: "科研公司", kind: "org" })).toEqual({
+ id: "co_research_lab",
+ source: "model",
+ });
+ expect(completion.prompts).toHaveLength(2);
+ expect(completion.prompts[0]).not.toContain("Answer with the identifier only");
+ expect(completion.prompts[1]).toContain("Answer with the identifier only");
+ expect(errors).toEqual([]);
+ });
+
+ it("falls back to the ASCII slug when neither answer is usable, and records why", async () => {
+ completion.answers = [answered("我建议叫「科研实验室」"), answered("还是叫科研实验室吧")];
+ expect(await service.suggestId(P, { name: "Plugin Marketplace", kind: "org" })).toEqual({
+ id: "co_plugin_marketplace",
+ source: "fallback",
+ });
+ expect(errors).toHaveLength(1);
+ expect(errors[0]).toMatchObject({ source: "organization", code: "id_suggest_failed" });
+ expect(String((errors[0]?.err as Error).message)).toContain("还是叫科研实验室吧");
+ });
+
+ it("does not repeat a request that failed outright, and records the provider's reason", async () => {
+ completion.answers = [failed("401 invalid api key")];
+ expect(await service.suggestId(P, { name: "Plugin Marketplace", kind: "org" })).toEqual({
+ id: "co_plugin_marketplace",
+ source: "fallback",
+ });
+ expect(completion.prompts).toHaveLength(1);
+ expect(String((errors[0]?.err as Error).message)).toContain("401 invalid api key");
+ });
+
+ it("answers a dated placeholder, never a failure, when neither the model nor the name can name it", async () => {
+ // The model answered twice and neither answer was an id.
+ completion.answers = [answered("科研实验室"), answered("实验室")];
+ expect(await service.suggestId(P, { name: "科研公司", kind: "org" })).toEqual({
+ id: placeholderFor("org"),
+ source: "placeholder",
+ reason: "unusable_answer",
+ });
+ // Nothing to ask: the Project names no default model.
+ completion.answers = [];
+ expect(await service.suggestId(P, { name: "市场推广", kind: "channel" })).toEqual({
+ id: placeholderFor("channel"),
+ source: "placeholder",
+ reason: "no_default_model",
+ });
+ // The request failed on the wire.
+ completion.answers = [failed("connect ETIMEDOUT")];
+ expect(await service.suggestId(P, { name: "科研公司", kind: "org" })).toEqual({
+ id: placeholderFor("org"),
+ source: "placeholder",
+ reason: "model_failed",
+ });
+ // A placeholder still avoids the ids already in use.
+ completion.answers = [];
+ expect(
+ await service.suggestId(P, {
+ name: "科研公司",
+ kind: "org",
+ taken: [placeholderFor("org")],
+ }),
+ ).toMatchObject({ id: `${placeholderFor("org")}_2`, source: "placeholder" });
+ });
+
+ it("says no_ascii when there is no model to ask at all", async () => {
+ const noModelService = new OrganizationService(
+ { ...deps, completeOnce: undefined },
+ scheduler,
+ );
+ expect(await noModelService.suggestId(P, { name: "科研公司", kind: "org" })).toEqual({
+ id: placeholderFor("org"),
+ source: "placeholder",
+ reason: "no_ascii",
+ });
+ });
+ });
+
+ describe("company mode's own sessions", () => {
+ it('stamps every desk and ticket session client: "org", and a reconcile pass marks one that is not', async () => {
+ await createOrg();
+ const ceoDesk = (await service.desk(P, ORG, CEO, {})).sessionId;
+ expect(created.at(-1)?.client).toBe("org");
+ expect(sessions.findById(ceoDesk)?.client).toBe("org");
+ const t = await service.createTicket(
+ P,
+ ORG,
+ { title: "Ship it", owner: `agent:${CEO}` },
+ { userId: "alice" },
+ );
+ const { sessionId: work } = await service.startTicket(
+ P,
+ ORG,
+ t.ticketId,
+ {},
+ { userId: "alice" },
+ );
+ expect(sessions.findById(work)?.client).toBe("org");
+
+ // What an organization that predates the marker looks like: its files still name the
+ // sessions, so the next reconcile pass stamps them.
+ db.prepare("UPDATE sessions SET client = NULL WHERE session_id IN (?, ?)").run(ceoDesk, work);
+ expect(sessions.findById(ceoDesk)?.client).toBeNull();
+ await scheduler.reconcile(P, ORG);
+ expect(sessions.findById(ceoDesk)?.client).toBe("org");
+ expect(sessions.findById(work)?.client).toBe("org");
+
+ // The stamp is the row's own, so an organization whose directory was removed by hand
+ // leaves it in place — which is the whole point: nothing else is left to say whose the
+ // sessions were.
+ await fs.rm(orgDir(), { recursive: true, force: true });
+ await scheduler.tickOnce();
+ expect(await service.list(P)).toEqual([]);
+ expect(sessions.findById(ceoDesk)?.client).toBe("org");
+ expect(sessions.findById(work)?.client).toBe("org");
+ });
+ });
+
+ describe("who starts a ticket session", () => {
+ it("an employee starts one only on the ticket it owns; a person on any", async () => {
+ await createOrg();
+ await service.hire(P, ORG, { newAgent: { agentId: HR }, title: "HR", reportsTo: CEO });
+ const ceoDesk = (await service.desk(P, ORG, CEO, {})).sessionId;
+ const hrDesk = (await service.desk(P, ORG, HR, {})).sessionId;
+ const t = await service.createTicket(
+ P,
+ ORG,
+ { title: "Ship it", owner: `agent:${HR}` },
+ { userId: "alice" },
+ );
+
+ // The CEO files and assigns; the owner's desk is what turns that into work.
+ await expect(
+ service.startTicket(P, ORG, t.ticketId, {}, { userId: "alice", sessionId: ceoDesk }),
+ ).rejects.toMatchObject({ status: 403, code: "not_ticket_owner" });
+
+ const own = await service.startTicket(
+ P,
+ ORG,
+ t.ticketId,
+ {},
+ { userId: "alice", sessionId: hrDesk },
+ );
+ expect(sessions.findById(own.sessionId)?.agentId).toBe(HR);
+
+ // The owner may enlist a colleague on its OWN ticket — how a request for help is answered.
+ const helper = await service.startTicket(
+ P,
+ ORG,
+ t.ticketId,
+ { agentId: CEO },
+ { userId: "alice", sessionId: hrDesk },
+ );
+ expect(sessions.findById(helper.sessionId)?.agentId).toBe(CEO);
+
+ // A person is not an employee of anything: the board may start any ticket.
+ const byPerson = await service.startTicket(P, ORG, t.ticketId, {}, { userId: "alice" });
+ expect(sessions.findById(byPerson.sessionId)?.agentId).toBe(HR);
+ });
+
+ it("an unowned ticket needs an owner before an employee may start it", async () => {
+ await createOrg();
+ const ceoDesk = (await service.desk(P, ORG, CEO, {})).sessionId;
+ const t = await service.createTicket(P, ORG, { title: "Unowned" }, { userId: "alice" });
+ await expect(
+ service.startTicket(
+ P,
+ ORG,
+ t.ticketId,
+ { agentId: CEO },
+ { userId: "alice", sessionId: ceoDesk },
+ ),
+ ).rejects.toMatchObject({ status: 403, code: "not_ticket_owner" });
+ const byPerson = await service.startTicket(
+ P,
+ ORG,
+ t.ticketId,
+ { agentId: CEO },
+ { userId: "alice" },
+ );
+ expect(sessions.findById(byPerson.sessionId)?.agentId).toBe(CEO);
+ });
+
+ it("leaves nothing on the ticket when the session cannot be started", async () => {
+ await createOrg();
+ const ceoDesk = (await service.desk(P, ORG, CEO, {})).sessionId;
+ const t = await service.createTicket(
+ P,
+ ORG,
+ { title: "Ship it", owner: `agent:${CEO}` },
+ { userId: "alice" },
+ );
+ startFails = true;
+ await expect(
+ service.startTicket(P, ORG, t.ticketId, {}, { userId: "alice", sessionId: ceoDesk }),
+ ).rejects.toMatchObject({ status: 409, code: "ticket_session_failed" });
+ // A session that never ran is not the ticket's: listed in `Sessions`, in the history or
+ // in the cache it would be counted by the spend and by the next session's `#n`, and a
+ // later chat in it would book its cost to this ticket and this employee.
+ const filed = await service.ticket(P, ORG, t.ticketId);
+ expect(filed.sessions).toEqual([]);
+ expect(filed.history.some((h) => h.action === "session_started")).toBe(false);
+ expect(cache.ticketSessions(P, ORG)).toEqual([]);
+ // So the retry is the ticket's first session, not its second.
+ startFails = false;
+ const retry = await service.startTicket(
+ P,
+ ORG,
+ t.ticketId,
+ {},
+ { userId: "alice", sessionId: ceoDesk },
+ );
+ expect((await service.ticket(P, ORG, t.ticketId)).sessions).toEqual([retry.sessionId]);
+ expect(sessions.findById(retry.sessionId)?.title).toBe("Ship it #1");
+ });
+ });
+
+ describe("the overview inbox", () => {
+ it("lists what names you, what is blocked and what closed this period", async () => {
+ await createOrg();
+ await service.hire(P, ORG, { newAgent: { agentId: HR }, title: "HR", reportsTo: CEO });
+ const alice = { userId: "alice" };
+
+ await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: "nothing to see here",
+ });
+ await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: "@user:alice the plan is ready",
+ });
+ await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: "@all standup at ten",
+ });
+
+ const blocked = await service.createTicket(
+ P,
+ ORG,
+ { title: "Blocked one", slug: "b-blocked", owner: `agent:${HR}` },
+ alice,
+ );
+ await service.blockTicket(
+ P,
+ ORG,
+ blocked.ticketId,
+ "waiting on the vendor",
+ undefined,
+ alice,
+ );
+ const closed = await service.createTicket(
+ P,
+ ORG,
+ { title: "Closed one", slug: "a-closed", owner: `agent:${HR}` },
+ alice,
+ );
+ await service.moveTicket(P, ORG, closed.ticketId, "done", undefined, alice);
+ const open = await service.createTicket(
+ P,
+ ORG,
+ { title: "Still open", slug: "c-open", owner: `agent:${HR}` },
+ alice,
+ );
+
+ const inbox = (await service.detail(P, ORG, "alice")).inbox!;
+ // Newest first, and only the lines that name this person (the ticket changes the
+ // scheduler writes name them too, so the assertion is over what a colleague wrote).
+ expect(inbox.mentions.filter((m) => m.sender !== "system").map((m) => m.text)).toEqual([
+ "@all standup at ten",
+ "@user:alice the plan is ready",
+ ]);
+ expect(inbox.mentions.map((m) => m.text)).not.toContain("nothing to see here");
+ for (const m of inbox.mentions) {
+ expect(m.mentions.includes("user:alice") || m.mentions.includes("all")).toBe(true);
+ }
+ expect(inbox.blockedTickets.map((t) => t.ticketId)).toEqual([blocked.ticketId]);
+ expect(inbox.blockedTickets[0]!.blocked).toBe("waiting on the vendor");
+ expect(inbox.doneTickets.map((t) => t.ticketId)).toEqual([closed.ticketId]);
+ expect(inbox.doneTickets[0]!.closedAt).toBe(new Date(nowMs).toISOString());
+ expect(inbox.doneTickets.map((t) => t.ticketId)).not.toContain(open.ticketId);
+ });
+
+ it("a ticket closed in an earlier period drops out; one closed by hand stays with no time", async () => {
+ await createOrg();
+ const alice = { userId: "alice" };
+ const early = await service.createTicket(
+ P,
+ ORG,
+ { title: "Closed in September", slug: "september" },
+ alice,
+ );
+ await service.moveTicket(P, ORG, early.ticketId, "done", undefined, alice);
+ // A ticket whose file was moved by hand carries no closing entry at all.
+ const byHand = await service.createTicket(
+ P,
+ ORG,
+ { title: "Moved by hand", slug: "by-hand" },
+ alice,
+ );
+ await service.moveTicket(P, ORG, byHand.ticketId, "done", undefined, alice);
+ const file = ticketPath(orgDir(), byHand.ticketId, "done");
+ const raw = await fs.readFile(file, "utf8");
+ await fs.writeFile(
+ file,
+ raw
+ .split("\n")
+ .filter((line) => !line.includes("action: moved"))
+ .join("\n"),
+ "utf8",
+ );
+
+ nowMs = T0 + 40 * DAY;
+ const inbox = (await service.detail(P, ORG, "alice")).inbox!;
+ const ids = inbox.doneTickets.map((t) => t.ticketId);
+ expect(ids).not.toContain(early.ticketId);
+ expect(ids).toContain(byHand.ticketId);
+ expect(
+ inbox.doneTickets.find((t) => t.ticketId === byHand.ticketId)?.closedAt,
+ ).toBeUndefined();
+ });
+ });
+
+ it("announces a departure with the manager the reports move to", async () => {
+ await createOrg();
+ await service.hire(P, ORG, { newAgent: { agentId: HR }, title: "HR", reportsTo: CEO });
+ await service.leave(P, ORG, HR);
+ const allHands = await service.channelMessages(
+ P,
+ ORG,
+ { userId: "alice" },
+ DEFAULT_CHANNEL_ID,
+ {},
+ );
+ const left = allHands.messages.find((m) => m.text.includes("left the organization"));
+ expect(left?.text).toBe(`agent:${HR} left the organization; reports now go to agent:${CEO}.`);
+ expect(left?.notice).toEqual({
+ kind: "employee_left",
+ params: { agent: `agent:${HR}`, reportsTo: `agent:${CEO}` },
+ });
+ });
+
+ describe("calendar", () => {
+ async function hireHr(): Promise<void> {
+ await service.hire(P, ORG, { newAgent: { agentId: HR }, title: "HR", reportsTo: CEO });
+ }
+
+ it("does not backfill a slot that passed before registration, then fires on the next one to the desk", async () => {
+ await createOrg();
+ await hireHr();
+ started.length = 0;
+ await store.writeCalendarEvent(
+ orgDir(),
+ HR,
+ "sweep",
+ serializeCalendarEvent({
+ prompt: "Sweep the board",
+ enabled: true,
+ startAt: new Date(T0 - DAY).toISOString(),
+ period: "1d",
+ }),
+ );
+ await scheduler.tickOnce();
+ expect(started).toHaveLength(0);
+ const list = await service.calendar(P, ORG);
+ expect(list.events[0]).toMatchObject({
+ agentId: HR,
+ name: "sweep",
+ status: "active",
+ paused: false,
+ });
+ expect(list.events[0]!.nextFireAt).toBe(new Date(T0 + DAY).toISOString());
+
+ nowMs = T0 + DAY + 1000;
+ await scheduler.tickOnce();
+ expect(started).toHaveLength(1);
+ const parsed = parseOrgTriggerMessage(started[0]!.text);
+ expect(parsed?.origin).toMatchObject({
+ kind: "event",
+ event: "sweep",
+ employee: `${HR} (HR, reports to ${CEO})`,
+ });
+ expect(parsed?.origin.budget).toBe("0.00 USD / unbounded");
+ expect(parsed?.rest).toBe("Sweep the board");
+ expect(started[0]!.queueIfBusy).toBe(true);
+ expect(cache.ownerOfSession(started[0]!.sessionId)).toMatchObject({
+ agentId: HR,
+ kind: "desk",
+ });
+ const after = await service.calendar(P, ORG);
+ expect(after.events[0]!.lastOutcome).toBe("fired");
+ // The same slot never fires twice.
+ await scheduler.tickOnce();
+ expect(started).toHaveLength(1);
+ });
+
+ it("queues behind a busy desk, holds while paused, and consumes silently with the switch off", async () => {
+ await createOrg();
+ await hireHr();
+ await store.writeCalendarEvent(
+ orgDir(),
+ HR,
+ "sweep",
+ serializeCalendarEvent({
+ prompt: "Sweep",
+ enabled: true,
+ startAt: new Date(T0).toISOString(),
+ period: "1d",
+ }),
+ );
+ await scheduler.tickOnce(); // baseline
+ started.length = 0;
+ // Open the desk so it can be busy.
+ const desk = await service.desk(P, ORG, HR, {});
+ busy.add(desk.sessionId);
+ nowMs = T0 + DAY + 1;
+ await scheduler.tickOnce();
+ expect(started).toHaveLength(1);
+ expect((await service.calendar(P, ORG)).events[0]!.lastOutcome).toBe("queued");
+ busy.clear();
+
+ await service.patch(P, ORG, { status: "paused" }, "alice");
+ nowMs = T0 + 2 * DAY + 1;
+ await scheduler.tickOnce();
+ expect(started).toHaveLength(1);
+ expect((await service.calendar(P, ORG)).events[0]!.lastOutcome).toBe("paused");
+ expect((await service.calendar(P, ORG)).events[0]!.paused).toBe(true);
+ await service.patch(P, ORG, { status: "active" }, "alice");
+
+ companyMode = false;
+ nowMs = T0 + 3 * DAY + 1;
+ await scheduler.tickOnce();
+ expect(started).toHaveLength(1);
+ companyMode = true;
+ // The slot consumed while the switch was off is not backfilled once it is on again.
+ await scheduler.tickOnce();
+ expect(started).toHaveLength(1);
+ nowMs = T0 + 4 * DAY + 1;
+ await scheduler.tickOnce();
+ expect(started).toHaveLength(2);
+ });
+
+ it("answers a write with the rota it collides with, and writes it anyway", async () => {
+ await createOrg();
+ await hireHr();
+ const fields = {
+ prompt: "Sweep",
+ enabled: true,
+ startAt: "2026-09-02T10:00:00+08:00",
+ period: "1d",
+ };
+ const first = await service.upsertCalendar(P, ORG, HR, "hr-audit", fields, { create: true });
+ expect(first.warnings).toBeUndefined();
+ const clash = await service.upsertCalendar(P, ORG, CEO, "board-sweep", fields, {
+ create: true,
+ });
+ expect(clash.warnings).toEqual([
+ `\`${HR}/hr-audit\` also fires at 10:00; give every employee its own minute.`,
+ ]);
+ // Advisory only: the event is stored exactly as asked.
+ expect((await service.calendar(P, ORG)).events.map((e) => e.name).sort()).toEqual([
+ "board-sweep",
+ "hr-audit",
+ ]);
+ const second = await service.upsertCalendar(
+ P,
+ ORG,
+ HR,
+ "extra-sweep",
+ { ...fields, startAt: new Date(nowMs).toISOString() },
+ { create: true },
+ );
+ expect(second.warnings).toEqual([
+ `\`${HR}\` already has a recurring event \`hr-audit\` with period 1d; one sweep per employee.`,
+ "A recurring event started at 'now' shares its minute with every other event started the same way; pick the role's hour.",
+ ]);
+ // Staggering it clears the advice on update.
+ const updated = await service.upsertCalendar(
+ P,
+ ORG,
+ CEO,
+ "board-sweep",
+ { ...fields, startAt: "2026-09-02T14:00:00+08:00" },
+ { create: false },
+ );
+ expect(updated.warnings).toBeUndefined();
+ });
+
+ it("reports an invalid file and one that belongs to nobody without firing", async () => {
+ await createOrg();
+ await store.writeCalendarEvent(orgDir(), CEO, "bad", 'prompt = ""\n');
+ await store.writeCalendarEvent(
+ orgDir(),
+ "stranger",
+ "sweep",
+ serializeCalendarEvent({ prompt: "x", enabled: true, startAt: new Date(T0).toISOString() }),
+ );
+ started.length = 0;
+ await scheduler.tickOnce();
+ expect(started).toHaveLength(0);
+ expect(errors.filter((e) => e.code === "org_calendar_invalid")).toHaveLength(2);
+ const list = await service.calendar(P, ORG);
+ expect(list.invalidFiles.map((f) => f.name).sort()).toEqual(["bad", "sweep"]);
+ });
+ });
+
+ describe("tickets", () => {
+ beforeEach(async () => {
+ await createOrg();
+ await service.hire(P, ORG, { newAgent: { agentId: HR }, title: "HR", reportsTo: CEO });
+ started.length = 0;
+ events.length = 0;
+ });
+
+ it("creates in proposed with an owner, queues the assignment, and opens ticket sessions that contribute", async () => {
+ const t = await service.createTicket(
+ P,
+ ORG,
+ { title: "Launch the site", goal: "Ship it", owner: `agent:${HR}`, priority: "P1" },
+ { userId: "alice" },
+ );
+ expect(t.ticketId).toMatch(/^2026-09-01-launch-the-site$/);
+ expect(t.status).toBe("proposed");
+ // Filed by alice for HR: the owner is the employee, and the history says who filed it.
+ expect(t.owner).toBe(`agent:${HR}`);
+ expect(t.notify).toEqual([`agent:${HR}`]);
+ expect(t.history.map((h) => [h.by, h.action, h.note ?? ""])).toEqual([
+ ["user:alice", "created", ""],
+ ["user:alice", "assigned", `agent:${HR}`],
+ ]);
+ await expect(
+ fs.stat(path.join(orgDir(), "tickets", "2026-09", "proposed", `${t.ticketId}.md`)),
+ ).resolves.toBeTruthy();
+ // Assignment at creation opens no desk and starts no run: it waits for the owner's sweep.
+ expect(started).toHaveLength(0);
+ await scheduler.tickOnce();
+ expect(started).toHaveLength(0);
+
+ const { sessionId } = await service.startTicket(
+ P,
+ ORG,
+ t.ticketId,
+ { message: "Start with the scaffold" },
+ { userId: "alice" },
+ );
+ const detail = await service.ticket(P, ORG, t.ticketId);
+ expect(detail.sessions).toEqual([sessionId]);
+ expect(sessions.findById(sessionId)?.title).toBe("Launch the site #1");
+ expect(cache.ownerOfSession(sessionId)).toMatchObject({ kind: "ticket", agentId: HR });
+ const work = started.find((s) => s.sessionId === sessionId);
+ expect(parseOrgTriggerMessage(work!.text)?.origin).toMatchObject({
+ kind: "ticket_work",
+ ticket: t.ticketId,
+ });
+ expect(work!.text).toContain("Note from the desk: Start with the scaffold");
+ expect(work!.text).toContain("---\ntitle: Launch the site\nstatus: proposed\n");
+ expect(detail.history.at(-1)).toMatchObject({ action: "session_started", note: sessionId });
+ // Where it stands, and the rule that makes its output findable by a colleague.
+ expect(work!.text).toContain(
+ `Workspace: ${path.join(orgDir(), "workspace", HR)} — the organization is at \`<app_data_dir>/organizations/${ORG}/\`.`,
+ );
+ expect(work!.text).toContain(
+ "Name every input you rely on and every deliverable you produce by its full path",
+ );
+
+ // A second session for the same ticket, and progress written from inside it.
+ const second = await service.startTicket(P, ORG, t.ticketId, {}, { userId: "alice" });
+ expect((await service.ticket(P, ORG, t.ticketId)).sessions).toEqual([
+ sessionId,
+ second.sessionId,
+ ]);
+ const withProgress = await service.progressTicket(P, ORG, t.ticketId, "half done", {
+ userId: "alice",
+ sessionId,
+ });
+ // The section is prose; who wrote it and when is the history entry beside it.
+ expect(withProgress.progress).toEqual(["half done"]);
+ expect(withProgress.history.at(-1)).toMatchObject({
+ by: `agent:${HR}`,
+ action: "progress",
+ note: "half done",
+ });
+ });
+
+ it("delivers queued changes in the next sweep, keeps them while paused, and empties the queue", async () => {
+ await store.writeCalendarEvent(
+ orgDir(),
+ HR,
+ "sweep",
+ serializeCalendarEvent({
+ prompt: "Sweep the board",
+ enabled: true,
+ startAt: new Date(T0).toISOString(),
+ period: "1d",
+ }),
+ );
+ await scheduler.tickOnce(); // registers the event and consumes the slot standing at T0
+ started.length = 0;
+
+ const t = await service.createTicket(
+ P,
+ ORG,
+ { title: "Launch the site", owner: `agent:${HR}`, notify: [`agent:${HR}`] },
+ { userId: "alice" },
+ );
+ await service.moveTicket(P, ORG, t.ticketId, "in_progress", undefined, { userId: "alice" });
+ await service.moveTicket(P, ORG, t.ticketId, "done", undefined, { userId: "alice" });
+ // An owner assigned and a ticket closed: two changes, no run at any desk.
+ expect(started).toHaveLength(0);
+
+ // A paused organization consumes the slot and keeps the queue for the sweep that fires.
+ await service.patch(P, ORG, { status: "paused" }, "alice");
+ nowMs = T0 + DAY + 1000;
+ await scheduler.tickOnce();
+ expect(started).toHaveLength(0);
+ expect((await service.calendar(P, ORG)).events[0]!.lastOutcome).toBe("paused");
+ await service.patch(P, ORG, { status: "active" }, "alice");
+
+ nowMs = T0 + 2 * DAY + 1000;
+ await scheduler.tickOnce();
+ expect(started).toHaveLength(1);
+ const parsed = parseOrgTriggerMessage(started[0]!.text);
+ expect(parsed?.origin).toMatchObject({ kind: "event", event: "sweep" });
+ expect(parsed?.rest).toBe(
+ [
+ "Sweep the board",
+ "",
+ "## Since your last sweep",
+ `- ${t.ticketId} (Launch the site): assigned to you`,
+ `- ${t.ticketId} (Launch the site): done`,
+ "",
+ 'Decide on each: start a ticket session (`penguin org ticket start <id> -m "…"`), verify and unblock, or leave it — do not do the work at your desk.',
+ ].join("\n"),
+ );
+
+ // Delivered once: the next sweep carries the event's own prompt and nothing else.
+ started.length = 0;
+ nowMs = T0 + 3 * DAY + 1000;
+ await scheduler.tickOnce();
+ expect(parseOrgTriggerMessage(started[0]!.text)?.rest).toBe("Sweep the board");
+ });
+
+ it("puts the queued changes back when the sweep cannot start", async () => {
+ await store.writeCalendarEvent(
+ store.dir(P, ORG),
+ HR,
+ "sweep",
+ serializeCalendarEvent({
+ prompt: "Sweep the board",
+ enabled: true,
+ startAt: new Date(T0).toISOString(),
+ period: "1d",
+ }),
+ );
+ await scheduler.tickOnce();
+ started.length = 0;
+ const t = await service.createTicket(
+ P,
+ ORG,
+ { title: "Write the FAQ", owner: `agent:${HR}` },
+ { userId: "alice" },
+ );
+ expect(started).toHaveLength(0);
+
+ // The Agent vanishes, so the desk cannot be opened: the slot fails and the change is kept.
+ existingAgents.delete(HR);
+ nowMs = T0 + DAY + 1000;
+ await scheduler.tickOnce();
+ expect(started).toHaveLength(0);
+ expect((await service.calendar(P, ORG)).events[0]!.lastOutcome).toBe("error");
+
+ existingAgents.add(HR);
+ nowMs = T0 + 2 * DAY + 1000;
+ await scheduler.tickOnce();
+ expect(started).toHaveLength(1);
+ expect(parseOrgTriggerMessage(started[0]!.text)?.rest).toContain(
+ `- ${t.ticketId} (Write the FAQ): assigned to you`,
+ );
+ });
+
+ it("drops an employee's undelivered changes when it leaves", async () => {
+ const t = await service.createTicket(
+ P,
+ ORG,
+ { title: "Write docs", owner: `agent:${HR}` },
+ { userId: "alice" },
+ );
+ await service.leave(P, ORG, HR);
+ expect(cache.takeDeskNotices(P, ORG, HR)).toEqual([]);
+ expect(t.owner).toBe(`agent:${HR}`);
+ });
+
+ it("moves between columns, queues done for Notify, and rejects need a reason", async () => {
+ const t = await service.createTicket(
+ P,
+ ORG,
+ { title: "Write docs", owner: `agent:${HR}`, notify: [`agent:${CEO}`] },
+ { userId: "alice" },
+ );
+ started.length = 0;
+ await service.moveTicket(P, ORG, t.ticketId, "in_progress", undefined, { userId: "alice" });
+ await expect(
+ fs.stat(path.join(orgDir(), "tickets", "2026-09", "in_progress", `${t.ticketId}.md`)),
+ ).resolves.toBeTruthy();
+ await expect(
+ fs.stat(path.join(orgDir(), "tickets", "2026-09", "proposed", `${t.ticketId}.md`)),
+ ).rejects.toBeTruthy();
+ await expect(
+ service.moveTicket(P, ORG, t.ticketId, "rejected", undefined, { userId: "alice" }),
+ ).rejects.toMatchObject({ status: 400 });
+ await service.moveTicket(P, ORG, t.ticketId, "done", undefined, { userId: "alice" });
+ // Notify = CEO and the owner HR: both are queued for their own next sweep. Neither is
+ // a run, and no line is written into the all-hands channel — the board is read from
+ // the board.
+ expect(started).toHaveLength(0);
+ expect(cache.takeDeskNotices(P, ORG, CEO).map((n) => [n.ticketId, n.change])).toEqual([
+ [t.ticketId, "done"],
+ ]);
+ const allHands = await service.channelMessages(
+ P,
+ ORG,
+ { userId: "alice" },
+ DEFAULT_CHANNEL_ID,
+ {},
+ );
+ expect(
+ allHands.messages.filter((m) => m.sender === "system" && m.text.includes(t.ticketId)),
+ ).toEqual([]);
+ expect(events.some((e) => e.type === "org_ticket" && e.change === "status:done")).toBe(true);
+ const board = await service.tickets(P, ORG);
+ expect(board.columns.done.map((x) => x.ticketId)).toEqual([t.ticketId]);
+ // The closing move is in the history, which is where the overview reads `closedAt`.
+ const closed = await service.ticket(P, ORG, t.ticketId);
+ expect(closed.history.at(-1)).toMatchObject({ action: "moved", note: "done" });
+ });
+
+ it("books the writing session onto the ticket, so a desk that did the work pays for it", async () => {
+ const t = await service.createTicket(
+ P,
+ ORG,
+ { title: "Fix the footer", owner: `agent:${HR}` },
+ { userId: "alice" },
+ );
+ const desk = await service.desk(P, ORG, HR, {});
+ const fromDesk = { userId: "alice", sessionId: desk.sessionId };
+
+ // A person's write books nothing: there is no session behind it.
+ await service.moveTicket(P, ORG, t.ticketId, "in_progress", undefined, { userId: "alice" });
+ expect((await service.ticket(P, ORG, t.ticketId)).sessions).toEqual([]);
+ // Management from a desk books nothing either: accepting, blocking and unblocking are
+ // decisions about the ticket, not work on it.
+ await service.moveTicket(P, ORG, t.ticketId, "proposed", undefined, fromDesk);
+ await service.moveTicket(P, ORG, t.ticketId, "in_progress", undefined, fromDesk);
+ await service.blockTicket(P, ORG, t.ticketId, "waiting for copy", undefined, fromDesk);
+ await service.unblockTicket(P, ORG, t.ticketId, fromDesk);
+ expect((await service.ticket(P, ORG, t.ticketId)).sessions).toEqual([]);
+
+ // Handing the work in claims it: the desk is booked from the move into review on.
+ const moved = await service.moveTicket(P, ORG, t.ticketId, "review", undefined, fromDesk);
+ expect(moved.sessions).toEqual([desk.sessionId]);
+ // Every other work write from the same session is the same contribution, booked once.
+ await service.progressTicket(P, ORG, t.ticketId, "footer replaced", fromDesk);
+ const after = await service.updateTicket(P, ORG, t.ticketId, { priority: "P1" }, fromDesk);
+ expect(after.sessions).toEqual([desk.sessionId]);
+ expect(cache.ticketSessions(P, ORG).map((r) => [r.ticketId, r.sessionId])).toEqual([
+ [t.ticketId, desk.sessionId],
+ ]);
+ // The desk's cost is now the ticket's cost too — that is what the booking is for.
+ costs.set(desk.sessionId, 4);
+ expect((await service.ticket(P, ORG, t.ticketId)).cost).toBe(4);
+ const finance = await service.finance(P, ORG);
+ expect(finance.tickets.find((x) => x.ticketId === t.ticketId)?.cost).toBe(4);
+ });
+
+ it("attaches only a session of an employee, so nothing spends where no budget can see it", async () => {
+ const t = await service.createTicket(
+ P,
+ ORG,
+ { title: "Fix the footer", owner: `agent:${HR}` },
+ { userId: "alice" },
+ );
+ const stranger = "session-2026-09-01-02-00-00-00000099";
+ const at = new Date(nowMs).toISOString();
+ sessions.insert({
+ sessionId: stranger,
+ projectId: P,
+ agentId: "outsider",
+ provider: "custom",
+ modelId: "m-bench",
+ workspace: root,
+ approvalMode: "allow-all",
+ title: null,
+ client: "web",
+ lastActiveAt: at,
+ createdAt: at,
+ });
+ // Spend is summed along the reporting line, so this session's cost would land on the
+ // ticket and in nobody's cumulative — past the CEO's cap and past warn and pause.
+ await expect(
+ service.attachTicket(P, ORG, t.ticketId, stranger, { userId: "alice" }),
+ ).rejects.toMatchObject({ status: 400, code: "not_employee_session" });
+ expect((await service.ticket(P, ORG, t.ticketId)).sessions).toEqual([]);
+
+ const desk = await service.desk(P, ORG, HR, {});
+ await service.attachTicket(P, ORG, t.ticketId, desk.sessionId, { userId: "alice" });
+ expect((await service.ticket(P, ORG, t.ticketId)).sessions).toEqual([desk.sessionId]);
+ });
+
+ it("refuses a parent that already sits under the ticket", async () => {
+ const by = { userId: "alice" };
+ const a = await service.createTicket(P, ORG, { title: "Launch the site" }, by);
+ const b = await service.createTicket(
+ P,
+ ORG,
+ { title: "Write the copy", parent: a.ticketId },
+ by,
+ );
+ // The cost roll-up memoizes after its recursion, so a two-ticket loop is not broken by
+ // the cache: it recurses to the depth bound and both tickets report many times the
+ // pair's real spend.
+ await expect(
+ service.updateTicket(P, ORG, a.ticketId, { parent: b.ticketId }, by),
+ ).rejects.toMatchObject({ status: 400 });
+ expect((await service.ticket(P, ORG, a.ticketId)).parent).toBeUndefined();
+
+ // A grandchild is refused the same way; re-parenting sideways is not a cycle.
+ const c = await service.createTicket(
+ P,
+ ORG,
+ { title: "Shoot the photos", parent: b.ticketId },
+ by,
+ );
+ await expect(
+ service.updateTicket(P, ORG, a.ticketId, { parent: c.ticketId }, by),
+ ).rejects.toMatchObject({ status: 400 });
+ await service.updateTicket(P, ORG, c.ticketId, { parent: a.ticketId }, by);
+ expect((await service.ticket(P, ORG, c.ticketId)).parent).toBe(a.ticketId);
+ });
+
+ it("files a ticket for another principal, and refuses one nobody holds", async () => {
+ const byEmployee = await service.createTicket(
+ P,
+ ORG,
+ { title: "Audit the calendar", owner: HR },
+ { userId: "alice" },
+ );
+ // A bare Agent id is the employee's principal; an employee owner is notified at its desk.
+ expect(byEmployee.owner).toBe(`agent:${HR}`);
+ expect(byEmployee.notify).toEqual([`agent:${HR}`]);
+ expect(byEmployee.history[0]).toMatchObject({ by: "user:alice", action: "created" });
+ const prefixed = await service.createTicket(
+ P,
+ ORG,
+ { title: "Audit again", owner: `agent:${CEO}` },
+ { userId: "alice" },
+ );
+ expect(prefixed.owner).toBe(`agent:${CEO}`);
+ // No owner named: the caller owns it, and a person is not @-mentioned for its own ticket.
+ const byUser = await service.createTicket(
+ P,
+ ORG,
+ { title: "Board request" },
+ { userId: "alice" },
+ );
+ expect(byUser.owner).toBe("user:alice");
+ expect(byUser.notify).toEqual([]);
+ expect(byUser.history).toEqual([
+ { at: new Date(nowMs).toISOString(), by: "user:alice", action: "created" },
+ ]);
+ for (const owner of ["ghost", `agent:ghost`, "user:mallory", "all"]) {
+ await expect(
+ service.createTicket(P, ORG, { title: "Nope", owner }, { userId: "alice" }),
+ ).rejects.toMatchObject({ status: 400 });
+ }
+ });
+
+ it("writes no channel line when a ticket closes, whoever Notify names", async () => {
+ const t = await service.createTicket(
+ P,
+ ORG,
+ { title: "Tell me", notify: ["user:alice"] },
+ { userId: "alice" },
+ );
+ await service.moveTicket(P, ORG, t.ticketId, "done", undefined, { userId: "alice" });
+ const allHands = await service.channelMessages(
+ P,
+ ORG,
+ { userId: "alice" },
+ DEFAULT_CHANNEL_ID,
+ {},
+ );
+ expect(
+ allHands.messages.filter((m) => m.sender === "system" && m.text.includes(t.ticketId)),
+ ).toEqual([]);
+ // The person reads it from the overview's inbox instead, which is built from the board.
+ const detail = await service.detail(P, ORG, "alice");
+ expect(detail.inbox?.doneTickets.map((x) => x.ticketId)).toEqual([t.ticketId]);
+ });
+
+ it("records the operator from the calling Agent id, over the calling session", async () => {
+ const t = await service.createTicket(
+ P,
+ ORG,
+ { title: "Trace the writer", owner: `agent:${HR}` },
+ { userId: "alice" },
+ );
+ const ceoDesk = await service.desk(P, ORG, CEO, {});
+ // The CEO's desk ran the command, but PENGUIN_AGENT_ID says HR: the narrower fact wins.
+ const withProgress = await service.progressTicket(P, ORG, t.ticketId, "looked at it", {
+ userId: "alice",
+ sessionId: ceoDesk.sessionId,
+ agentId: HR,
+ });
+ expect(withProgress.history.at(-1)).toMatchObject({ by: `agent:${HR}`, action: "progress" });
+ // An Agent id that names no employee is ignored; the session answers instead.
+ const again = await service.progressTicket(P, ORG, t.ticketId, "and again", {
+ userId: "alice",
+ sessionId: ceoDesk.sessionId,
+ agentId: "ghost",
+ });
+ expect(again.history.at(-1)).toMatchObject({ by: `agent:${CEO}`, action: "progress" });
+ });
+
+ it("names a ticket whose title carries no English through the Project's model", async () => {
+ completion.answers = [answered("launch-the-site")];
+ const t = await service.createTicket(P, ORG, { title: "上线站点" }, { userId: "alice" });
+ expect(t.ticketId).toBe("2026-09-01-launch-the-site");
+ // `slug` always wins, and is held to the same letters-only rule.
+ const explicit = await service.createTicket(
+ P,
+ ORG,
+ { title: "上线站点", slug: "second-site" },
+ { userId: "alice" },
+ );
+ expect(explicit.ticketId).toBe("2026-09-01-second-site");
+ await expect(
+ service.createTicket(P, ORG, { title: "x", slug: "site-2" }, { userId: "alice" }),
+ ).rejects.toMatchObject({ status: 400 });
+ // No usable answer from the model, twice: the caller is told to name it.
+ completion.answers = [answered("站点"), answered("站点")];
+ await expect(
+ service.createTicket(P, ORG, { title: "季度财报" }, { userId: "alice" }),
+ ).rejects.toMatchObject({ status: 400, code: "slug_required" });
+ // A taken id takes a letter, never a digit.
+ completion.answers = [answered("launch-the-site")];
+ const again = await service.createTicket(P, ORG, { title: "上线站点" }, { userId: "alice" });
+ expect(again.ticketId).toBe("2026-09-01-launch-the-site-b");
+ });
+
+ it("blocking notices the blocker and the owner's manager; closing the blocker tells the owner", async () => {
+ const blocker = await service.createTicket(
+ P,
+ ORG,
+ { title: "Buy the domain" },
+ { userId: "alice" },
+ );
+ const t = await service.createTicket(
+ P,
+ ORG,
+ { title: "Launch", owner: `agent:${HR}` },
+ { userId: "alice" },
+ );
+ started.length = 0;
+ // The assignment is already queued for HR; clear it so the later lines stand alone.
+ expect(cache.takeDeskNotices(P, ORG, HR).map((n) => n.change)).toEqual(["assigned"]);
+ await service.blockTicket(P, ORG, t.ticketId, "Waiting for the domain", blocker.ticketId, {
+ userId: "alice",
+ });
+ const detail = await service.ticket(P, ORG, t.ticketId);
+ expect(detail.blocked).toBe("Waiting for the domain");
+ expect(detail.blockedBy).toBe(blocker.ticketId);
+ // HR's manager is the CEO; the block waits in its queue rather than interrupting it.
+ expect(started).toHaveLength(0);
+ expect(cache.takeDeskNotices(P, ORG, CEO).map((n) => [n.ticketId, n.change])).toEqual([
+ [t.ticketId, "blocked"],
+ ]);
+ await service.moveTicket(P, ORG, blocker.ticketId, "done", undefined, { userId: "alice" });
+ expect(started).toHaveLength(0);
+ // The owner of the waiting ticket learns the blocker closed, in its own next sweep.
+ expect(cache.takeDeskNotices(P, ORG, HR).map((n) => [n.ticketId, n.change])).toEqual([
+ [t.ticketId, "blocker_closed"],
+ ]);
+ await service.unblockTicket(P, ORG, t.ticketId, { userId: "alice" });
+ expect((await service.ticket(P, ORG, t.ticketId)).blocked).toBeUndefined();
+ const board = await service.tickets(P, ORG);
+ expect(
+ board.columns.proposed.find((x) => x.ticketId === t.ticketId)?.blocked,
+ ).toBeUndefined();
+ });
+ });
+
+ describe("channel messages", () => {
+ beforeEach(async () => {
+ await createOrg();
+ await service.hire(P, ORG, { newAgent: { agentId: HR }, title: "HR", reportsTo: CEO });
+ started.length = 0;
+ });
+
+ it("delivers mentions to desks, records the rest, and stops the chain at the limit", async () => {
+ const m1 = await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: "@acme_hr welcome, and @nobody too",
+ });
+ expect(m1.sender).toBe("user:alice");
+ expect(m1.hop).toBe(0);
+ expect(m1.mentions).toEqual([`agent:${HR}`]);
+ expect(started).toHaveLength(1);
+ const first = parseOrgTriggerMessage(started[0]!.text);
+ expect(first?.origin).toMatchObject({ kind: "mention", message: `${m1.id} from user:alice` });
+ expect(first?.rest).toContain("welcome");
+ const hrDesk = started[0]!.sessionId;
+
+ // HR answers from its desk: hop 1, delivered to the CEO.
+ const m2 = await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: `@${CEO} done`,
+ sessionId: hrDesk,
+ });
+ expect(m2.sender).toBe(`agent:${HR}`);
+ expect(m2.hop).toBe(1);
+ expect(started).toHaveLength(2);
+ const ceoDesk = started[1]!.sessionId;
+ expect(cache.ownerOfSession(ceoDesk)?.agentId).toBe(CEO);
+
+ // CEO replies: hop 2, delivered to HR; HR replies: hop 3 = the limit, recorded only.
+ const m3 = await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: `@${HR} thanks`,
+ sessionId: ceoDesk,
+ });
+ expect(m3.hop).toBe(2);
+ expect(started).toHaveLength(3);
+ const m4 = await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: `@${CEO} anytime`,
+ sessionId: hrDesk,
+ });
+ expect(m4.hop).toBe(3);
+ expect(m4.mentions).toEqual([`agent:${CEO}`]);
+ expect(started).toHaveLength(3);
+
+ // A plain message reaches nobody; @all reaches everyone but the sender.
+ await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: "just noting",
+ });
+ expect(started).toHaveLength(3);
+ await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: "@all standup in 5",
+ });
+ expect(started).toHaveLength(5);
+
+ const allHands = await service.channelMessages(
+ P,
+ ORG,
+ { userId: "alice" },
+ DEFAULT_CHANNEL_ID,
+ {},
+ );
+ expect(allHands.messages.map((m) => m.id)).toContain(m1.id);
+ // Everything alice did not write is unread; the three lines she posted are not.
+ expect(allHands.messages.some((m) => m.sender === "user:alice")).toBe(true);
+ expect(allHands.unread).toBe(
+ allHands.messages.filter((m) => m.sender !== "user:alice").length,
+ );
+ await service.markRead(P, ORG, "alice", DEFAULT_CHANNEL_ID, allHands.messages.at(-1)!.id);
+ expect(
+ (await service.channelMessages(P, ORG, { userId: "alice" }, DEFAULT_CHANNEL_ID, {})).unread,
+ ).toBe(0);
+ });
+
+ it("the system's own lines and a paused organization deliver nothing", async () => {
+ await service.patch(P, ORG, { status: "paused" }, "alice");
+ await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: `@${HR} hello?`,
+ });
+ expect(started).toHaveLength(0);
+ });
+ });
+
+ describe("channels", () => {
+ const alice = { userId: "alice" };
+ let ceoDesk: string;
+ let hrDesk: string;
+ const asCeo = (): { userId: string; sessionId: string } => ({
+ userId: "alice",
+ sessionId: ceoDesk,
+ });
+ const asHr = (): { userId: string; sessionId: string } => ({
+ userId: "alice",
+ sessionId: hrDesk,
+ });
+
+ beforeEach(async () => {
+ await createOrg();
+ await service.hire(P, ORG, { newAgent: { agentId: HR }, title: "HR", reportsTo: CEO });
+ ceoDesk = (await service.desk(P, ORG, CEO, {})).sessionId;
+ hrDesk = (await service.desk(P, ORG, HR, {})).sessionId;
+ started.length = 0;
+ });
+
+ it("a new channel holds only its creator; the all-hands channel holds everyone", async () => {
+ const site = await service.createChannel(
+ P,
+ ORG,
+ { channelId: "site", name: "Site launch", purpose: "Ship the site" },
+ alice,
+ );
+ expect(site).toMatchObject({
+ channelId: "site",
+ name: "Site launch",
+ purpose: "Ship the site",
+ everyone: false,
+ archived: false,
+ createdBy: "user:alice",
+ memberCount: 1,
+ isMember: true,
+ });
+ expect((await service.channel(P, ORG, "site", alice)).members).toEqual([
+ { principal: "user:alice", name: "alice", kind: "user" },
+ ]);
+ const all = await service.channel(P, ORG, DEFAULT_CHANNEL_ID, alice);
+ expect(all.everyone).toBe(true);
+ expect(all.members.map((m) => m.principal).sort()).toEqual(
+ [`agent:${CEO}`, `agent:${HR}`, "user:alice"].sort(),
+ );
+ expect(all.members.find((m) => m.principal === `agent:${CEO}`)?.name).toBe(`Name of ${CEO}`);
+
+ await expect(
+ service.createChannel(P, ORG, { channelId: "site" }, alice),
+ ).rejects.toMatchObject({ status: 409, code: "channel_exists" });
+ await expect(
+ service.createChannel(P, ORG, { channelId: DEFAULT_CHANNEL_ID }, alice),
+ ).rejects.toMatchObject({ code: "channel_exists" });
+ await expect(
+ service.createChannel(P, ORG, { channelId: "Site" }, alice),
+ ).rejects.toMatchObject({ status: 400 });
+ await expect(service.channel(P, ORG, "missing", alice)).rejects.toMatchObject({
+ status: 404,
+ code: "channel_not_found",
+ });
+ });
+
+ it("an employee joins only by invitation; a person joins any channel itself", async () => {
+ await service.createChannel(P, ORG, { channelId: "site" }, asCeo());
+ expect(
+ (await service.channel(P, ORG, "site", asCeo())).members.map((m) => m.principal),
+ ).toEqual([`agent:${CEO}`]);
+ await expect(
+ service.addChannelMember(P, ORG, "site", `agent:${HR}`, asHr()),
+ ).rejects.toMatchObject({ status: 403, code: "not_a_member" });
+ await expect(service.channel(P, ORG, "site", asHr())).rejects.toMatchObject({
+ status: 403,
+ code: "not_a_member",
+ });
+
+ const joined = await service.addChannelMember(P, ORG, "site", "user:alice", alice);
+ expect(joined.members.map((m) => m.principal)).toEqual([`agent:${CEO}`, "user:alice"]);
+ const invited = await service.addChannelMember(P, ORG, "site", `agent:${HR}`, asCeo());
+ expect(invited.members.map((m) => m.principal)).toEqual([
+ `agent:${CEO}`,
+ "user:alice",
+ `agent:${HR}`,
+ ]);
+ expect(invited.memberCount).toBe(3);
+ // Inviting twice is the same membership, not an error.
+ expect(
+ (await service.addChannelMember(P, ORG, "site", `agent:${HR}`, asCeo())).memberCount,
+ ).toBe(3);
+
+ for (const principal of ["agent:ghost", "user:mallory", "all"]) {
+ await expect(
+ service.addChannelMember(P, ORG, "site", principal, alice),
+ ).rejects.toMatchObject({ status: 400, code: "invalid_principal" });
+ }
+ const lines = (await service.channelMessages(P, ORG, alice, "site", {})).messages;
+ expect(lines.map((m) => m.text)).toEqual([
+ `agent:${CEO} created the channel.`,
+ "user:alice joined the channel.",
+ `agent:${CEO} invited agent:${HR} to the channel.`,
+ ]);
+ expect(lines.map((m) => m.notice)).toEqual([
+ { kind: "channel_created", params: { by: `agent:${CEO}` } },
+ { kind: "channel_joined", params: { principal: "user:alice" } },
+ { kind: "channel_invited", params: { by: `agent:${CEO}`, principal: `agent:${HR}` } },
+ ]);
+ });
+
+ it("a member leaves; a person removes anyone; an employee removes only itself", async () => {
+ await service.createChannel(P, ORG, { channelId: "site" }, alice);
+ await service.addChannelMember(P, ORG, "site", `agent:${CEO}`, alice);
+ await service.addChannelMember(P, ORG, "site", `agent:${HR}`, alice);
+ await expect(
+ service.removeChannelMember(P, ORG, "site", `agent:${CEO}`, asHr()),
+ ).rejects.toMatchObject({ status: 403, code: "not_a_member" });
+
+ await service.removeChannelMember(P, ORG, "site", `agent:${HR}`, asHr());
+ expect(
+ (await service.channel(P, ORG, "site", alice)).members.map((m) => m.principal),
+ ).toEqual(["user:alice", `agent:${CEO}`]);
+ // A person removes anyone, and removing a non-member changes nothing.
+ await service.removeChannelMember(P, ORG, "site", `agent:${CEO}`, alice);
+ await service.removeChannelMember(P, ORG, "site", `agent:${CEO}`, alice);
+ expect(
+ (await service.channel(P, ORG, "site", alice)).members.map((m) => m.principal),
+ ).toEqual(["user:alice"]);
+ const texts = (await service.channelMessages(P, ORG, alice, "site", {})).messages.map(
+ (m) => m.text,
+ );
+ expect(texts).toContain(`agent:${HR} left the channel.`);
+ expect(
+ texts.filter((t) => t === `user:alice removed agent:${CEO} from the channel.`),
+ ).toHaveLength(1);
+ });
+
+ it("archiving is a person's call, and an archived channel takes no writes", async () => {
+ await service.createChannel(P, ORG, { channelId: "site" }, asCeo());
+ await expect(
+ service.patchChannel(P, ORG, "site", { archived: true }, asCeo()),
+ ).rejects.toMatchObject({ status: 403, code: "not_a_member" });
+ expect((await service.patchChannel(P, ORG, "site", { archived: true }, alice)).archived).toBe(
+ true,
+ );
+ await expect(
+ service.sendChannelMessage(P, ORG, "alice", "site", { text: "hi", sessionId: ceoDesk }),
+ ).rejects.toMatchObject({ status: 409, code: "channel_archived" });
+ await expect(
+ service.addChannelMember(P, ORG, "site", `agent:${HR}`, alice),
+ ).rejects.toMatchObject({ code: "channel_archived" });
+ await expect(
+ service.removeChannelMember(P, ORG, "site", `agent:${CEO}`, alice),
+ ).rejects.toMatchObject({ code: "channel_archived" });
+ await expect(
+ service.patchChannel(P, ORG, "site", { name: "Nope" }, alice),
+ ).rejects.toMatchObject({ code: "channel_archived" });
+ // Lifting the archive is the one edit it accepts.
+ expect(
+ (await service.patchChannel(P, ORG, "site", { archived: false }, alice)).archived,
+ ).toBe(false);
+ const renamed = await service.patchChannel(P, ORG, "site", { name: "Site" }, asCeo());
+ expect(renamed.name).toBe("Site");
+ const texts = (await service.channelMessages(P, ORG, alice, "site", {})).messages.map(
+ (m) => m.text,
+ );
+ expect(texts).toContain("user:alice archived the channel.");
+ expect(texts).toContain("user:alice unarchived the channel.");
+ });
+
+ it("the all-hands channel cannot be archived, joined or left", async () => {
+ for (const call of [
+ () => service.patchChannel(P, ORG, DEFAULT_CHANNEL_ID, { archived: true }, alice),
+ () => service.addChannelMember(P, ORG, DEFAULT_CHANNEL_ID, `agent:${HR}`, alice),
+ () => service.removeChannelMember(P, ORG, DEFAULT_CHANNEL_ID, "user:alice", alice),
+ ]) {
+ await expect(call()).rejects.toMatchObject({ status: 400, code: "all_hands_immutable" });
+ }
+ // Renaming it is allowed; the UI renders its own label for it anyway.
+ expect(
+ (await service.patchChannel(P, ORG, DEFAULT_CHANNEL_ID, { name: "Everyone" }, alice)).name,
+ ).toBe("Everyone");
+ });
+
+ it("delivers a mention inside the channel only, and refuses one that names an outsider", async () => {
+ await service.createChannel(P, ORG, { channelId: "site" }, alice);
+ await service.addChannelMember(P, ORG, "site", `agent:${CEO}`, alice);
+ started.length = 0;
+
+ await expect(
+ service.sendChannelMessage(P, ORG, "alice", "site", { text: "hello", sessionId: hrDesk }),
+ ).rejects.toMatchObject({ status: 403, code: "not_a_member" });
+ await expect(
+ service.sendChannelMessage(P, ORG, "alice", "site", { text: `@${HR} look at this` }),
+ ).rejects.toMatchObject({
+ status: 400,
+ code: "mention_not_member",
+ message: expect.stringContaining(`agent:${HR}`),
+ });
+ // Nothing was written and nobody was woken.
+ expect(
+ (await service.channelMessages(P, ORG, alice, "site", {})).messages.filter(
+ (m) => m.sender !== "system",
+ ),
+ ).toEqual([]);
+ expect(started).toHaveLength(0);
+
+ const msg = await service.sendChannelMessage(P, ORG, "alice", "site", {
+ text: "@all kickoff",
+ });
+ expect(started).toHaveLength(1);
+ expect(started[0]!.sessionId).toBe(ceoDesk);
+ const parsed = parseOrgTriggerMessage(started[0]!.text);
+ expect(parsed?.origin).toMatchObject({
+ kind: "mention",
+ channel: "site",
+ message: `${msg.id} from user:alice`,
+ });
+ expect(parsed?.rest).toContain("kickoff");
+ expect(
+ events.some(
+ (e) => e.type === "org_channel" && e.channelId === "site" && e.message.id === msg.id,
+ ),
+ ).toBe(true);
+
+ // The same `@all` in the all-hands channel is every employee.
+ started.length = 0;
+ await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: "@all standup",
+ });
+ expect(started.map((s) => s.sessionId).sort()).toEqual([ceoDesk, hrDesk].sort());
+ expect(parseOrgTriggerMessage(started[0]!.text)?.origin.channel).toBe(DEFAULT_CHANNEL_ID);
+ });
+
+ it("counts unread per channel and shows an employee only the channels it is in", async () => {
+ await service.createChannel(P, ORG, { channelId: "site" }, alice);
+ await service.addChannelMember(P, ORG, "site", `agent:${CEO}`, alice);
+ const ping = await service.sendChannelMessage(P, ORG, "alice", "site", {
+ text: "@user:alice ping",
+ sessionId: ceoDesk,
+ });
+ await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, { text: "plain line" });
+
+ const listed = await service.channels(P, ORG, alice);
+ expect(listed.channels.map((c) => c.channelId)).toEqual([DEFAULT_CHANNEL_ID, "site"]);
+ const byId = new Map(listed.channels.map((c) => [c.channelId, c]));
+ expect(byId.get("site")).toMatchObject({ isMember: true, memberCount: 2, mentionsMe: 1 });
+ expect(byId.get("site")!.lastMessageAt).toBe(ping.time);
+ expect(byId.get(DEFAULT_CHANNEL_ID)).toMatchObject({ mentionsMe: 0, memberCount: 3 });
+ expect(byId.get(DEFAULT_CHANNEL_ID)!.unread).toBeGreaterThan(0);
+
+ // Reading one channel leaves the other's cursor where it was.
+ const site = await service.channelMessages(P, ORG, alice, "site", {});
+ expect(site.channelId).toBe("site");
+ await service.markRead(P, ORG, "alice", "site", site.messages.at(-1)!.id);
+ const after = new Map(
+ (await service.channels(P, ORG, alice)).channels.map((c) => [c.channelId, c]),
+ );
+ expect(after.get("site")).toMatchObject({ unread: 0, mentionsMe: 0 });
+ expect(after.get(DEFAULT_CHANNEL_ID)!.unread).toBeGreaterThan(0);
+
+ expect((await service.channels(P, ORG, asHr())).channels.map((c) => c.channelId)).toEqual([
+ DEFAULT_CHANNEL_ID,
+ ]);
+ const ceoView = await service.channels(P, ORG, asCeo());
+ expect(ceoView.channels.map((c) => c.channelId)).toEqual([DEFAULT_CHANNEL_ID, "site"]);
+ // An employee has no read cursor of its own; it reads through its triggers.
+ expect(
+ ceoView.channels.every((c) => c.isMember && c.unread === 0 && c.mentionsMe === 0),
+ ).toBe(true);
+ await expect(service.channelMessages(P, ORG, asHr(), "site", {})).rejects.toMatchObject({
+ status: 403,
+ code: "not_a_member",
+ });
+ });
+
+ it("never counts a person's own lines as unread", async () => {
+ const seen = await service.channelMessages(P, ORG, alice, DEFAULT_CHANNEL_ID, {});
+ await service.markRead(P, ORG, "alice", DEFAULT_CHANNEL_ID, seen.messages.at(-1)!.id);
+ // Posting does not move the read cursor — only the read route does — so alice's own
+ // line would otherwise come back as a badge of one against herself.
+ await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: "posted from the CLI",
+ });
+ const mine = await service.channelMessages(P, ORG, alice, DEFAULT_CHANNEL_ID, {});
+ expect(mine.messages.at(-1)!.sender).toBe("user:alice");
+ expect(mine.unread).toBe(0);
+
+ // A colleague's line in the same place is unread, and names her.
+ await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: "@user:alice have a look",
+ sessionId: ceoDesk,
+ });
+ expect(await service.channelMessages(P, ORG, alice, DEFAULT_CHANNEL_ID, {})).toMatchObject({
+ unread: 1,
+ mentionsMe: 1,
+ });
+ const listed = new Map(
+ (await service.channels(P, ORG, alice)).channels.map((c) => [c.channelId, c]),
+ );
+ expect(listed.get(DEFAULT_CHANNEL_ID)).toMatchObject({ unread: 1, mentionsMe: 1 });
+ });
+
+ it("counts unread past the seven newest active days, stopping at the read cursor", async () => {
+ const read = await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: "day zero",
+ sessionId: ceoDesk,
+ });
+ await service.markRead(P, ORG, "alice", DEFAULT_CHANNEL_ID, read.id);
+ expect((await service.channelMessages(P, ORG, alice, DEFAULT_CHANNEL_ID, {})).unread).toBe(0);
+
+ // Nine more active days, each its own message file. Only days with messages have a
+ // file, so a count that stopped after the seven newest would lose the two oldest —
+ // and an organization left running for weeks is where that is the normal case.
+ for (let day = 1; day <= 9; day++) {
+ nowMs = T0 + day * DAY;
+ await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: `@user:alice day ${day}`,
+ sessionId: ceoDesk,
+ });
+ }
+ expect(await service.channelMessages(P, ORG, alice, DEFAULT_CHANNEL_ID, {})).toMatchObject({
+ unread: 9,
+ mentionsMe: 9,
+ });
+ const listed = new Map(
+ (await service.channels(P, ORG, alice)).channels.map((c) => [c.channelId, c]),
+ );
+ expect(listed.get(DEFAULT_CHANNEL_ID)).toMatchObject({ unread: 9, mentionsMe: 9 });
+ // And the overview's "mentions waiting" is the same walk.
+ expect((await service.detail(P, ORG, "alice")).pending.mentions).toBe(9);
+ });
+
+ it("ignores a stray entry under channels/ and reports a channel whose file does not parse", async () => {
+ // A directory without a channel.toml, and a plain file, are not channels.
+ await fs.writeFile(path.join(orgDir(), "channels", "notes.md"), "scratch\n", "utf8");
+ await fs.mkdir(path.join(orgDir(), "channels", "empty"), { recursive: true });
+ await fs.mkdir(path.join(orgDir(), "channels", "broken"), { recursive: true });
+ await fs.writeFile(
+ path.join(orgDir(), "channels", "broken", "channel.toml"),
+ 'name = "Broken"\n',
+ "utf8",
+ );
+ errors.length = 0;
+ await scheduler.tickOnce();
+ expect((await service.channels(P, ORG, alice)).channels.map((c) => c.channelId)).toEqual([
+ DEFAULT_CHANNEL_ID,
+ ]);
+ expect(errors.filter((e) => e.code === "org_channel_invalid")).toHaveLength(1);
+ await expect(service.channel(P, ORG, "broken", alice)).rejects.toMatchObject({
+ status: 404,
+ code: "channel_not_found",
+ });
+ });
+ });
+
+ describe("budgets", () => {
+ it("warns once, pauses the employee's calendar and its subordinates, and resumes when the budget is raised", async () => {
+ await createOrg();
+ await service.hire(P, ORG, {
+ newAgent: { agentId: HR },
+ title: "HR",
+ reportsTo: CEO,
+ budget: 10,
+ });
+ const desk = await service.desk(P, ORG, HR, {});
+ await store.writeCalendarEvent(
+ orgDir(),
+ HR,
+ "sweep",
+ serializeCalendarEvent({
+ prompt: "Sweep",
+ enabled: true,
+ startAt: new Date(T0).toISOString(),
+ period: "1d",
+ }),
+ );
+ await scheduler.tickOnce();
+ started.length = 0;
+ events.length = 0;
+
+ costs.set(desk.sessionId, 9);
+ await scheduler.tickOnce();
+ expect(
+ events.filter((e) => e.type === "org_budget").map((e) => (e as { state: string }).state),
+ ).toEqual(["warned"]);
+ await scheduler.tickOnce();
+ expect(events.filter((e) => e.type === "org_budget")).toHaveLength(1);
+ const finance = await service.finance(P, ORG);
+ const hr = finance.employees.find((e) => e.agentId === HR)!;
+ expect(hr).toMatchObject({ own: 9, cumulative: 9, budget: 10, warned: true, paused: false });
+ expect(finance.employees.find((e) => e.agentId === CEO)!.cumulative).toBe(9);
+ expect(finance.total).toBe(9);
+
+ costs.set(desk.sessionId, 11);
+ nowMs = T0 + DAY + 1;
+ await scheduler.tickOnce();
+ expect(
+ events.filter((e) => e.type === "org_budget").map((e) => (e as { state: string }).state),
+ ).toEqual(["warned", "paused"]);
+ expect(started).toHaveLength(0);
+ expect((await service.calendar(P, ORG)).events[0]).toMatchObject({
+ lastOutcome: "paused",
+ paused: true,
+ });
+ expect((await service.chart(P, ORG)).employees.find((e) => e.agentId === HR)!.state).toBe(
+ "paused",
+ );
+ // The warning went to the day it fired on, the pause to the next day's file.
+ const warned = await service.channelMessages(
+ P,
+ ORG,
+ { userId: "alice" },
+ DEFAULT_CHANNEL_ID,
+ {
+ date: zonedDate("Asia/Shanghai", T0),
+ },
+ );
+ expect(warned.messages.find((m) => m.text.startsWith("Budget warning"))?.notice).toEqual({
+ kind: "budget_warned",
+ params: {
+ agent: `agent:${HR}`,
+ period: "2026-09",
+ percent: "90",
+ cost: "9.00",
+ budget: "10.00",
+ },
+ });
+ const paused = await service.channelMessages(
+ P,
+ ORG,
+ { userId: "alice" },
+ DEFAULT_CHANNEL_ID,
+ {},
+ );
+ expect(paused.messages.find((m) => m.text.startsWith("Budget pause"))?.notice?.kind).toBe(
+ "budget_paused",
+ );
+
+ await service.patchEmployee(P, ORG, HR, { budget: 100 });
+ expect(
+ events.filter((e) => e.type === "org_budget").map((e) => (e as { state: string }).state),
+ ).toEqual(["warned", "paused", "resumed"]);
+ nowMs = T0 + 2 * DAY + 1;
+ await scheduler.tickOnce();
+ expect(started).toHaveLength(1);
+ expect(parseOrgTriggerMessage(started[0]!.text)?.origin.budget).toBe(
+ "11.00 / 100.00 USD (11%)",
+ );
+ });
+
+ it("enforces a zero budget, which nothing can be under", async () => {
+ await createOrg();
+ await service.hire(P, ORG, {
+ newAgent: { agentId: HR },
+ title: "HR",
+ reportsTo: CEO,
+ budget: 0,
+ });
+ await scheduler.tickOnce();
+ // Nothing was spent and the budget is already over: zero is a real budget, not a request
+ // to be unbounded, and it reads the 100% `budgetLine` reports for it. The pause is
+ // decided before the warning, and neither repeats on the next pass.
+ expect(
+ events.filter((e) => e.type === "org_budget").map((e) => (e as { state: string }).state),
+ ).toEqual(["paused", "warned"]);
+ expect((await service.chart(P, ORG)).employees.find((e) => e.agentId === HR)!.state).toBe(
+ "paused",
+ );
+ const finance = await service.finance(P, ORG);
+ expect(finance.employees.find((e) => e.agentId === HR)).toMatchObject({
+ own: 0,
+ budget: 0,
+ warned: true,
+ paused: true,
+ });
+ // The CEO's 100 is untouched, so the zero budget is the only one that tripped.
+ expect(finance.employees.find((e) => e.agentId === CEO)).toMatchObject({ paused: false });
+ });
+
+ it("reports the month asked for, and refuses a month that is not one", async () => {
+ await createOrg();
+ expect((await service.finance(P, ORG)).period).toBe("2026-09");
+ expect((await service.finance(P, ORG, "2026-08")).period).toBe("2026-08");
+ // A malformed month is a caller that skipped the route's check; answering it with the
+ // current month's figures would be the wrong month reported as the one asked for.
+ await expect(service.finance(P, ORG, "2026-13")).rejects.toThrow(/yyyy-mm/);
+ await expect(service.finance(P, ORG, "2026-00")).rejects.toThrow(/yyyy-mm/);
+ });
+
+ it("reports a ratio for a zero budget, so a paused row is never a meterless one", async () => {
+ await createOrg();
+ await service.hire(P, ORG, {
+ newAgent: { agentId: HR },
+ title: "HR",
+ reportsTo: CEO,
+ budget: 0,
+ });
+ const desk = await service.desk(P, ORG, HR, {});
+ costs.set(desk.sessionId, 3);
+ // Zero is a budget everything is already over, so the marks written against it and the
+ // meter the row carries have to agree: a `ratio` missing beside warned and paused is a
+ // paused employee the finance page cannot explain.
+ const at = new Date(nowMs).toISOString();
+ cache.markBudget(P, ORG, HR, "2026-09", { warnedAt: at, pausedAt: at });
+ expect((await service.finance(P, ORG)).employees.find((e) => e.agentId === HR)).toMatchObject(
+ { budget: 0, ratio: 1, warned: true, paused: true },
+ );
+
+ // The chart row reads the same convention, and a budget that is not zero is unchanged.
+ const chart = await service.chart(P, ORG);
+ expect(chart.employees.find((e) => e.agentId === HR)!.spend.ratio).toBe(1);
+ expect(chart.employees.find((e) => e.agentId === CEO)!.spend.ratio).toBe(0.03);
+
+ // So does the organization's own spend, measured against the CEO's budget.
+ await service.create(P, { orgId: "zero", mission: "Build it", ceoBudget: 0 }, "alice");
+ expect((await service.detail(P, "zero", "alice")).spend).toMatchObject({
+ budget: 0,
+ ratio: 1,
+ });
+ });
+ });
+
+ describe("desks and caches", () => {
+ it("renews a desk when the chart moves its workspace and keeps the old session counting", async () => {
+ await createOrg();
+ const first = await service.desk(P, ORG, CEO, {});
+ expect(first.created).toBe(false);
+ await fs.mkdir(path.join(orgDir(), "workspace", "hq"));
+ await service.patchEmployee(P, ORG, CEO, { workspace: "hq" });
+ const second = await service.desk(P, ORG, CEO, {});
+ expect(second.sessionId).not.toBe(first.sessionId);
+ expect(second.workspace).toBe(path.join(orgDir(), "workspace", "hq"));
+ const rows = cache.deskSessions(P, ORG);
+ expect(rows.map((r) => [r.sessionId, r.current])).toEqual([
+ [second.sessionId, true],
+ [first.sessionId, false],
+ ]);
+ const renewed = await service.desk(P, ORG, CEO, { renew: true });
+ expect(renewed.created).toBe(true);
+ expect(cache.deskSessions(P, ORG)).toHaveLength(3);
+ const list = await service.sessions(P, ORG);
+ expect(list.desks.map((d) => d.sessionId)).toEqual([renewed.sessionId]);
+ });
+
+ it("rebuilds the session caches from the files after they are dropped", async () => {
+ await createOrg();
+ const desk = await service.desk(P, ORG, CEO, {});
+ const t = await service.createTicket(
+ P,
+ ORG,
+ { title: "Cache me", owner: `agent:${CEO}` },
+ { userId: "alice" },
+ );
+ const { sessionId } = await service.startTicket(P, ORG, t.ticketId, {}, { userId: "alice" });
+ cache.deleteOrg(P, ORG);
+ expect(cache.ownerOfSession(desk.sessionId)).toBeNull();
+ await scheduler.tickOnce();
+ expect(cache.ownerOfSession(desk.sessionId)).toMatchObject({ kind: "desk", agentId: CEO });
+ expect(cache.ownerOfSession(sessionId)).toMatchObject({ kind: "ticket", agentId: CEO });
+ expect(service.orgIdOfSession(sessionId)).toBe(ORG);
+ });
+
+ it("maps a Project's organization sessions in one lookup, desks and ticket sessions alike", async () => {
+ await createOrg();
+ const desk = await service.desk(P, ORG, CEO, {});
+ const ticket = await service.createTicket(
+ P,
+ ORG,
+ { title: "Map me", owner: `agent:${CEO}` },
+ { userId: "alice" },
+ );
+ const { sessionId: work } = await service.startTicket(
+ P,
+ ORG,
+ ticket.ticketId,
+ {},
+ { userId: "alice" },
+ );
+ // What the session list stamps as SessionInfo.orgId: one map for the whole Project
+ // instead of a query per row.
+ const ids = cache.orgIdsOfProject(P);
+ expect(ids.get(desk.sessionId)).toBe(ORG);
+ expect(ids.get(work)).toBe(ORG);
+ expect(ids.has("session-2026-09-01-00-00-00-0000ffff")).toBe(false);
+ expect(cache.orgIdsOfProject("other_project").size).toBe(0);
+ });
+
+ it("opens the new employee's desk as it is hired, and starts no run for it", async () => {
+ await createOrg();
+ const runsAfterCreation = started.length;
+ const item = await service.hire(P, ORG, {
+ newAgent: { agentId: HR, name: "HR" },
+ title: "HR",
+ reportsTo: CEO,
+ });
+ // The hire's own response already names the desk: the sidebar's row carries a real
+ // Session id from the first read, rather than waiting for a trigger to open one.
+ const deskSessionId = item.desk?.sessionId;
+ expect(deskSessionId).toBeTruthy();
+ expect(sessions.findById(deskSessionId!)).toMatchObject({ agentId: HR, client: "org" });
+ expect(sessions.findById(deskSessionId!)?.title).toBe(`Name of ${HR}'s desk`);
+ expect(created.at(-1)).toMatchObject({
+ agentId: HR,
+ client: "org",
+ workspace: path.join(orgDir(), "workspace", HR),
+ });
+ // A desk is a Session, not a work run: hiring dispatches nothing to it.
+ expect(started).toHaveLength(runsAfterCreation);
+
+ const ledger = (await store.readDesks(orgDir())).parsed;
+ expect(ledger.ok && ledger.value[HR]?.sessionId).toBe(deskSessionId);
+ const listed = (await service.sessions(P, ORG)).desks.find((d) => d.agentId === HR);
+ expect(listed?.sessionId).toBe(deskSessionId);
+ expect(cache.ownerOfSession(deskSessionId!)).toMatchObject({ kind: "desk", agentId: HR });
+ // Opening it afterwards reuses it rather than opening a second one.
+ expect(await service.desk(P, ORG, HR, {})).toMatchObject({
+ sessionId: deskSessionId,
+ created: false,
+ });
+ });
+
+ it("provisions a desk the chart names but the ledger does not, and re-opens one whose session is gone", async () => {
+ await createOrg();
+ await service.hire(P, ORG, { newAgent: { agentId: HR }, title: "HR", reportsTo: CEO });
+ const hired = (await service.chart(P, ORG)).employees.find((e) => e.agentId === HR)!;
+
+ // An employee written into the chart by hand — the CEO's file tools, or a person — has
+ // no ledger entry at all. The pass opens its desk without any trigger.
+ const dev = "acme_dev";
+ existingAgents.add(dev);
+ await fs.writeFile(
+ path.join(orgDir(), "org_chart.yaml"),
+ [
+ "employees:",
+ ` - agent_id: ${CEO}`,
+ " title: CEO",
+ " reports_to: null",
+ " workspace: ceo",
+ ` - agent_id: ${HR}`,
+ " title: HR",
+ ` reports_to: ${CEO}`,
+ ` workspace: ${HR}`,
+ ` - agent_id: ${dev}`,
+ " title: Dev",
+ ` reports_to: ${CEO}`,
+ " workspace: dev",
+ "",
+ ].join("\n"),
+ "utf8",
+ );
+ const runs = started.length;
+ await scheduler.tickOnce();
+ const devDesk = (await service.sessions(P, ORG)).desks.find((d) => d.agentId === dev);
+ expect(sessions.findById(devDesk?.sessionId ?? "")).toMatchObject({
+ agentId: dev,
+ client: "org",
+ });
+ expect(started).toHaveLength(runs);
+
+ // A desk session deleted by hand (or with its Agent) leaves the ledger naming a Session
+ // the server cannot find — which is exactly what the row's messaging binding asks for,
+ // and what answered "Session does not exist". The pass opens a fresh one.
+ const gone = hired.desk!.sessionId;
+ sessions.deleteByAgent(P, HR);
+ expect(sessions.findById(gone)).toBeNull();
+ expect((await service.sessions(P, ORG)).desks.find((d) => d.agentId === HR)?.sessionId).toBe(
+ gone,
+ );
+ await scheduler.tickOnce();
+ const healed = (await service.sessions(P, ORG)).desks.find((d) => d.agentId === HR);
+ expect(healed?.sessionId).not.toBe(gone);
+ expect(sessions.findById(healed?.sessionId ?? "")).toMatchObject({ agentId: HR });
+ // Idempotent: a second pass finds every desk in place and opens nothing.
+ const openedSoFar = created.length;
+ await scheduler.tickOnce();
+ expect(created).toHaveLength(openedSoFar);
+ });
+
+ it("records a desk it cannot open and provisions the rest of the chart, paused or not", async () => {
+ await createOrg();
+ await service.hire(P, ORG, { newAgent: { agentId: HR }, title: "HR", reportsTo: CEO });
+ await service.patch(P, ORG, { status: "paused" }, "alice");
+
+ // Two employees with no desk: one whose Agent is gone (nothing can open it) and one
+ // that is fine. A paused organization fires no run, but a desk is not a run.
+ const ghost = "acme_ghost";
+ const dev = "acme_dev";
+ existingAgents.add(dev);
+ await fs.writeFile(
+ path.join(orgDir(), "org_chart.yaml"),
+ [
+ "employees:",
+ ` - agent_id: ${CEO}`,
+ " title: CEO",
+ " reports_to: null",
+ " workspace: ceo",
+ ` - agent_id: ${HR}`,
+ " title: HR",
+ ` reports_to: ${CEO}`,
+ ` workspace: ${HR}`,
+ ` - agent_id: ${ghost}`,
+ " title: Ghost",
+ ` reports_to: ${CEO}`,
+ " workspace: ghost",
+ ` - agent_id: ${dev}`,
+ " title: Dev",
+ ` reports_to: ${CEO}`,
+ " workspace: dev",
+ "",
+ ].join("\n"),
+ "utf8",
+ );
+ errors.length = 0;
+ await scheduler.tickOnce();
+ expect(errors.map((e) => e.code)).toContain("org_desk_unavailable");
+ expect(errors.some((e) => e.ctx?.agentId === ghost)).toBe(true);
+ const desks = (await service.sessions(P, ORG)).desks.map((d) => d.agentId);
+ expect(desks).toContain(dev);
+ expect(desks).not.toContain(ghost);
+ });
+
+ it("pausing keeps every desk session open, and nothing removes an organization", async () => {
+ await createOrg();
+ const desk = await service.desk(P, ORG, CEO, {});
+ // Pause is the whole lifecycle: the organization stays listed and its desk stays open.
+ await service.patch(P, ORG, { status: "paused" }, "alice");
+ expect((await service.list(P)).map((o) => o.status)).toEqual(["paused"]);
+ expect((await service.desk(P, ORG, CEO, {})).sessionId).toBe(desk.sessionId);
+ expect(await service.detail(P, ORG, "alice")).toMatchObject({
+ settings: { status: "paused" },
+ });
+ expect(await fs.stat(orgDir())).toBeTruthy();
+
+ // The only way one goes away is by hand, and it takes neither the Agent nor the session.
+ await fs.rm(orgDir(), { recursive: true, force: true });
+ await scheduler.tickOnce();
+ expect(await service.list(P)).toEqual([]);
+ expect(existingAgents.has(CEO)).toBe(true);
+ expect(sessions.findById(desk.sessionId)).not.toBeNull();
+ });
+ });
+
+ describe("employee plugins", () => {
+ const OLD = "2026-09-01.1";
+
+ async function orgWithHr(): Promise<void> {
+ await createOrg();
+ await service.hire(P, ORG, { newAgent: { agentId: HR }, title: "HR", reportsTo: CEO });
+ plugins.updated.length = 0;
+ errors.length = 0;
+ }
+
+ it("reinstalls a company plugin the library has moved past, and leaves the rest alone", async () => {
+ await orgWithHr();
+ plugins.installed.set(`${HR}:agent-company`, OLD);
+ await scheduler.tickOnce();
+ expect(plugins.updated).toEqual([{ agentId: HR, plugin: "agent-company" }]);
+ expect(plugins.installed.get(`${HR}:agent-company`)).toBe(LIBRARY_VERSION);
+ expect(errors).toEqual([]);
+ });
+
+ it("writes nothing while every employee is current", async () => {
+ await orgWithHr();
+ await scheduler.tickOnce();
+ expect(plugins.updated).toEqual([]);
+ // The same pass run twice stays a no-op: the comparison, not a one-shot flag, is what
+ // makes it idempotent.
+ await scheduler.tickOnce();
+ expect(plugins.updated).toEqual([]);
+ });
+
+ it("leaves a plugin the employee does not carry uninstalled", async () => {
+ await orgWithHr();
+ plugins.installed.delete(`${HR}:agent-development`);
+ await scheduler.tickOnce();
+ expect(plugins.updated).toEqual([]);
+ expect(plugins.installed.has(`${HR}:agent-development`)).toBe(false);
+ });
+
+ it("records a failed update and carries on with the rest of the pass", async () => {
+ await orgWithHr();
+ plugins.installed.set(`${HR}:agent-company`, OLD);
+ plugins.installed.set(`${CEO}:agent-company`, OLD);
+ plugins.failUpdates.add(`${CEO}:agent-company`);
+ await scheduler.tickOnce();
+ expect(plugins.updated).toEqual([{ agentId: HR, plugin: "agent-company" }]);
+ expect(plugins.installed.get(`${CEO}:agent-company`)).toBe(OLD);
+ expect(errors).toHaveLength(1);
+ expect(errors[0]).toMatchObject({
+ source: "organization",
+ code: "org_plugin_update_failed",
+ ctx: { projectId: P, agentId: CEO },
+ });
+ // Not fatal: the calendar and the caches behind it in the pass still ran.
+ expect(await service.list(P)).toHaveLength(1);
+ });
+ });
+});
diff --git a/packages/server/test/organization-scenario.test.ts b/packages/server/test/organization-scenario.test.ts
new file mode 100644
index 00000000..2e213c00
--- /dev/null
+++ b/packages/server/test/organization-scenario.test.ts
@@ -0,0 +1,435 @@
+/**
+ * The marketplace company, end to end on the runtime seams (SCN-004): one mission creates
+ * the organization and its CEO; the CEO hires HR, finance, a developer and a marketer,
+ * partitions the shared workspace, schedules everyone and files the first tickets; the
+ * calendar drives the desks; ticket sessions do the work and write back; review and done
+ * reach the right people — the board at once, an employee in its next sweep; finance rolls the spend up the reporting line and to the parent
+ * ticket. Every command an employee would run through `penguin org` hits the same service
+ * methods the routes call, attributed to the employee's session.
+ */
+import fs from "node:fs/promises";
+import path from "node:path";
+import { beforeEach, describe, expect, it } from "vitest";
+import { parseOrgTriggerMessage } from "@prismshadow/penguin-core";
+import { DEFAULT_CHANNEL_ID } from "../src/organization/paths.js";
+import { makeOrgHarness } from "./org-harness.js";
+import type { OrgHarness } from "./org-harness.js";
+
+const ORG = "marketplace";
+const CEO = "marketplace_ceo";
+const HR = "marketplace_hr";
+const FIN = "marketplace_finance";
+const DEV = "marketplace_dev";
+const MKT = "marketplace_marketing";
+const T0 = Date.parse("2026-09-01T01:00:00Z");
+const DAY = 86_400_000;
+const MISSION =
+ "Build a DeepSeek Harness plugin Marketplace, promote it on social media and SEO into the top three search results, and earn from paid featured slots on the home page.";
+
+describe("scenario: the DeepSeek Harness plugin Marketplace company", () => {
+ let h: OrgHarness;
+ const P = "p1";
+
+ const triggers = (): Array<{
+ sessionId: string;
+ origin: ReturnType<typeof parseOrgTriggerMessage>;
+ }> => h.started.map((s) => ({ sessionId: s.sessionId, origin: parseOrgTriggerMessage(s.text) }));
+
+ beforeEach(async () => {
+ h = await makeOrgHarness({ nowMs: T0 });
+ });
+
+ it("runs the company from the mission to the first paid slot", async () => {
+ const { service, scheduler, store } = h;
+
+ // 1. The board creates the organization with one sentence: only the CEO exists.
+ const detail = await service.create(
+ P,
+ { orgId: ORG, name: "Plugin Marketplace", mission: MISSION, timezone: "Asia/Shanghai" },
+ "alice",
+ );
+ expect(detail.employeeCount).toBe(1);
+ expect(h.agentsCreated.map((a) => a.agentId)).toEqual([CEO]);
+ const init = triggers()[0]!;
+ expect(init.origin?.origin.kind).toBe("init");
+ // The CEO starts with the default budget, which is the whole company's: the trigger
+ // block names it, so the proposal can be sized to it.
+ expect(init.origin?.origin.budget).toBe("0.00 / 100.00 USD (0%)");
+ expect(init.origin?.rest).toContain(MISSION);
+ const ceoDesk = init.sessionId;
+ const handbook = await service.handbook(P, ORG);
+ expect(handbook).toContain("Plugin Marketplace");
+ expect(handbook).toContain(MISSION);
+
+ // 2. The CEO (from its desk) confirms the mission with the board in the all-hands channel …
+ const m1 = await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: "@alice I read the mission as: marketplace site first, then SEO and social, revenue from featured slots. Correct?",
+ sessionId: ceoDesk,
+ });
+ expect(m1.sender).toBe(`agent:${CEO}`);
+ expect(m1.mentions).toEqual(["user:alice"]);
+ const board = await service.channelMessages(
+ P,
+ ORG,
+ { userId: "alice" },
+ DEFAULT_CHANNEL_ID,
+ {},
+ );
+ expect(board.mentionsMe).toBe(1);
+ await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: `@${CEO} Correct. Go.`,
+ });
+ expect(
+ triggers().filter((t) => t.origin?.origin.kind === "mention" && t.sessionId === ceoDesk),
+ ).toHaveLength(1);
+
+ // … hires HR and finance first, then the roles the mission needs, partitioning the workspace.
+ const dir = store.dir(P, ORG);
+ for (const sub of ["people", "finance", "site", "marketing"])
+ await fs.mkdir(path.join(dir, "workspace", sub));
+ await service.hire(P, ORG, {
+ newAgent: { agentId: HR },
+ title: "HR",
+ reportsTo: CEO,
+ workspace: "people",
+ budget: 20,
+ });
+ await service.hire(P, ORG, {
+ newAgent: { agentId: FIN },
+ title: "Finance",
+ reportsTo: CEO,
+ workspace: "finance",
+ budget: 20,
+ });
+ await service.hire(P, ORG, {
+ newAgent: { agentId: DEV },
+ title: "Developer",
+ reportsTo: CEO,
+ workspace: "site",
+ budget: 100,
+ duties: "Build and run the marketplace site",
+ });
+ await service.hire(P, ORG, {
+ newAgent: { agentId: MKT },
+ title: "Marketing",
+ reportsTo: CEO,
+ workspace: "marketing",
+ budget: 60,
+ duties: "SEO and social promotion",
+ });
+ await service.patchEmployee(P, ORG, CEO, { budget: 300 });
+ const chart = await service.chart(P, ORG);
+ expect(chart.employees.map((e) => e.agentId)).toEqual([CEO, HR, FIN, DEV, MKT]);
+ expect(chart.employees.every((e) => e.invalid === undefined)).toBe(true);
+ expect(h.agentsCreated.every((a) => a.plugins.includes("agent-company"))).toBe(true);
+ expect(h.briefs.get(DEV)).toContain("Duties: Build and run the marketplace site");
+
+ // 3. Everyone gets a daily sweep on the calendar.
+ for (const agentId of [CEO, HR, FIN, DEV, MKT]) {
+ await service.upsertCalendar(
+ P,
+ ORG,
+ agentId,
+ "daily-sweep",
+ {
+ prompt:
+ "Sweep the board: start your tickets, check running sessions, write back, report in your channels.",
+ enabled: true,
+ startAt: new Date(T0 + 60_000).toISOString(),
+ period: "1d",
+ },
+ { create: true },
+ );
+ }
+ expect((await service.calendar(P, ORG)).events).toHaveLength(5);
+
+ // 4. The mission becomes a ticket tree: one parent, one child per stream.
+ const ceoActor = { userId: "alice", sessionId: ceoDesk };
+ const runsBeforeTickets = h.started.length;
+ const parent = await service.createTicket(
+ P,
+ ORG,
+ { title: "Plugin Marketplace", goal: MISSION, owner: `agent:${CEO}`, priority: "P0" },
+ ceoActor,
+ );
+ expect(parent.owner).toBe(`agent:${CEO}`);
+ expect(parent.history[0]).toMatchObject({ by: `agent:${CEO}`, action: "created" });
+ const site = await service.createTicket(
+ P,
+ ORG,
+ {
+ title: "Build the marketplace site",
+ goal: "A site that lists DeepSeek Harness plugins with search and a featured row.",
+ acceptanceCriteria: "- lists plugins\n- search works\n- home page has a featured row",
+ owner: `agent:${DEV}`,
+ parent: parent.ticketId,
+ priority: "P1",
+ notify: [`agent:${CEO}`],
+ },
+ ceoActor,
+ );
+ const seo = await service.createTicket(
+ P,
+ ORG,
+ {
+ title: "SEO to the top three",
+ goal: "Rank in the top three for 'DeepSeek Harness plugins'.",
+ owner: `agent:${MKT}`,
+ parent: parent.ticketId,
+ priority: "P1",
+ },
+ ceoActor,
+ );
+ const social = await service.createTicket(
+ P,
+ ORG,
+ {
+ title: "Social media launch",
+ goal: "Announce the marketplace on the main channels.",
+ owner: `agent:${MKT}`,
+ parent: parent.ticketId,
+ },
+ ceoActor,
+ );
+ const slots = await service.createTicket(
+ P,
+ ORG,
+ {
+ title: "Paid featured slots",
+ goal: "Sell time-limited pinned slots on the home page.",
+ owner: `agent:${DEV}`,
+ parent: parent.ticketId,
+ priority: "P2",
+ },
+ ceoActor,
+ );
+ expect((await service.ticket(P, ORG, parent.ticketId)).children.sort()).toEqual(
+ [site.ticketId, seo.ticketId, social.ticketId, slots.ticketId].sort(),
+ );
+ // Filing the tree woke nobody: an assignment waits for the owner's next sweep.
+ expect(h.started).toHaveLength(runsBeforeTickets);
+ const devDesk = (await service.desk(P, ORG, DEV, {})).sessionId;
+ const mktDesk = (await service.desk(P, ORG, MKT, {})).sessionId;
+
+ // 5. The CEO accepts the streams; SEO waits on the site.
+ for (const t of [site, seo, social, slots])
+ await service.moveTicket(P, ORG, t.ticketId, "in_progress", undefined, ceoActor);
+ await service.blockTicket(
+ P,
+ ORG,
+ seo.ticketId,
+ "Nothing to index until the site is live",
+ site.ticketId,
+ { userId: "alice", sessionId: mktDesk },
+ );
+ expect((await service.ticket(P, ORG, seo.ticketId)).blockedBy).toBe(site.ticketId);
+ const board2 = await service.tickets(P, ORG);
+ expect(board2.columns.in_progress.map((t) => t.ticketId).sort()).toEqual(
+ [site.ticketId, seo.ticketId, social.ticketId, slots.ticketId].sort(),
+ );
+ expect(board2.columns.in_progress.find((t) => t.ticketId === seo.ticketId)?.blocked).toBe(
+ "Nothing to index until the site is live",
+ );
+
+ // 5b. The site stream gets its own channel: the CEO opens it and invites the developer,
+ // so the thread lives beside the all-hands channel instead of drowning it.
+ const siteChannel = await service.createChannel(
+ P,
+ ORG,
+ { channelId: "site", name: "Site launch", purpose: "Everything about shipping the site" },
+ ceoActor,
+ );
+ expect(siteChannel).toMatchObject({
+ createdBy: `agent:${CEO}`,
+ memberCount: 1,
+ everyone: false,
+ });
+ const withDev = await service.addChannelMember(P, ORG, "site", `agent:${DEV}`, ceoActor);
+ expect(withDev.members.map((m) => m.principal)).toEqual([`agent:${CEO}`, `agent:${DEV}`]);
+ // Marketing is not in it: a message naming it is refused before anything is written.
+ await expect(
+ service.sendChannelMessage(P, ORG, "alice", "site", {
+ text: `@${MKT} can you look at the copy?`,
+ sessionId: ceoDesk,
+ }),
+ ).rejects.toMatchObject({ status: 400, code: "mention_not_member" });
+ h.started.length = 0;
+ const kickoff = await service.sendChannelMessage(P, ORG, "alice", "site", {
+ text: `@${DEV} the site ticket is yours; talk to me here.`,
+ sessionId: ceoDesk,
+ });
+ const inChannel = triggers().filter((t) => t.origin?.origin.kind === "mention");
+ expect(inChannel).toHaveLength(1);
+ expect(inChannel[0]!.sessionId).toBe(devDesk);
+ expect(inChannel[0]!.origin?.origin).toMatchObject({
+ channel: "site",
+ message: `${kickoff.id} from agent:${CEO}`,
+ });
+ // The CEO says so once in the all-hands channel, where the board reads.
+ await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: "Opened the #site channel for the site stream; @alice you can follow it there.",
+ sessionId: ceoDesk,
+ });
+ const channels = await service.channels(P, ORG, { userId: "alice" });
+ expect(channels.channels.map((c) => c.channelId)).toEqual([DEFAULT_CHANNEL_ID, "site"]);
+ // The developer sees both; marketing only the all-hands channel.
+ expect(
+ (await service.channels(P, ORG, { userId: "alice", sessionId: devDesk })).channels.map(
+ (c) => c.channelId,
+ ),
+ ).toEqual([DEFAULT_CHANNEL_ID, "site"]);
+ expect(
+ (await service.channels(P, ORG, { userId: "alice", sessionId: mktDesk })).channels.map(
+ (c) => c.channelId,
+ ),
+ ).toEqual([DEFAULT_CHANNEL_ID]);
+
+ // 6. The calendar fires the next day: every desk gets its sweep with a budget line.
+ h.started.length = 0;
+ h.clock.nowMs = T0 + DAY + 120_000;
+ await scheduler.tickOnce();
+ const sweeps = triggers().filter((t) => t.origin?.origin.kind === "event");
+ expect(sweeps).toHaveLength(5);
+ expect(sweeps.map((t) => t.origin!.origin.event)).toEqual(Array(5).fill("daily-sweep"));
+ const devSweep = sweeps.find((t) => t.sessionId === devDesk)!;
+ expect(devSweep.origin!.origin.budget).toBe("0.00 / 100.00 USD (0%)");
+ // The sweep is where the ticket changes land: the developer's two assignments …
+ expect(devSweep.origin!.rest).toContain("## Since your last sweep");
+ expect(devSweep.origin!.rest).toContain(
+ `- ${site.ticketId} (Build the marketplace site): assigned to you`,
+ );
+ expect(devSweep.origin!.rest).toContain(
+ `- ${slots.ticketId} (Paid featured slots): assigned to you`,
+ );
+ // … and, for the CEO, the block the marketer put on the SEO ticket it manages.
+ expect(sweeps.find((t) => t.sessionId === ceoDesk)!.origin!.rest).toContain(
+ `- ${seo.ticketId} (SEO to the top three): blocked — "Nothing to index until the site is live" (by ${site.ticketId})`,
+ );
+
+ // 7. The developer's desk opens a ticket session for the site; the session works and writes back.
+ // The developer's OWN desk starts it: an employee may open a session only on a ticket it owns.
+ const { sessionId: siteWork } = await service.startTicket(
+ P,
+ ORG,
+ site.ticketId,
+ {
+ agentId: DEV,
+ message: "Start with a static site; featured row can be hard-coded for now.",
+ },
+ { userId: "alice", sessionId: devDesk },
+ );
+ expect(h.sessions.findById(siteWork)?.agentId).toBe(DEV);
+ expect(h.sessions.findById(siteWork)?.workspace).toBe(path.join(dir, "workspace", "site"));
+ const work = h.started.find((s) => s.sessionId === siteWork)!;
+ expect(parseOrgTriggerMessage(work.text)?.origin).toMatchObject({
+ kind: "ticket_work",
+ ticket: site.ticketId,
+ });
+ expect(work.text).toContain("- lists plugins");
+ const devWork = { userId: "alice", sessionId: siteWork };
+ await service.progressTicket(
+ P,
+ ORG,
+ site.ticketId,
+ "Scaffolded the site, plugin list renders from plugins.json",
+ devWork,
+ );
+ await service.progressTicket(
+ P,
+ ORG,
+ site.ticketId,
+ "Search and the featured row are in; running on the local environment",
+ devWork,
+ );
+ await service.moveTicket(P, ORG, site.ticketId, "review", undefined, devWork);
+ const siteDetail = await service.ticket(P, ORG, site.ticketId);
+ expect(siteDetail.status).toBe("review");
+ // The prose is the two sentences the developer's session wrote; who did what is history.
+ expect(siteDetail.progress).toHaveLength(2);
+ expect(siteDetail.history.map((h) => [h.by, h.action])).toEqual([
+ [`agent:${CEO}`, "created"],
+ [`agent:${CEO}`, "assigned"],
+ [`agent:${CEO}`, "moved"],
+ [`agent:${DEV}`, "session_started"],
+ [`agent:${DEV}`, "progress"],
+ [`agent:${DEV}`, "progress"],
+ [`agent:${DEV}`, "moved"],
+ ]);
+ // The CEO's desk accepted the ticket from inside its own session, but accepting is a
+ // decision, not work: only the developer's ticket session is booked as contributing.
+ expect(siteDetail.sessions).toEqual([siteWork]);
+
+ // 8. The CEO reviews and closes it: the developer is told, and the marketer learns its blocker closed.
+ h.started.length = 0;
+ await service.moveTicket(P, ORG, site.ticketId, "done", undefined, ceoActor);
+ // Closing it starts no run either: the CEO (on `Notify`) and the owner of the ticket
+ // that was waiting are queued, each for its own next sweep.
+ expect(h.started).toHaveLength(0);
+ expect(h.cache.takeDeskNotices(P, ORG, CEO).map((n) => [n.ticketId, n.change])).toEqual([
+ [site.ticketId, "done"],
+ ]);
+ expect(h.cache.takeDeskNotices(P, ORG, MKT).map((n) => [n.ticketId, n.change])).toEqual([
+ [seo.ticketId, "blocker_closed"],
+ ]);
+ await service.unblockTicket(P, ORG, seo.ticketId, { userId: "alice", sessionId: mktDesk });
+
+ // 9. Marketing works SEO and social from one session attached to both tickets; finance rolls it all up.
+ const { sessionId: mktWork } = await service.startTicket(
+ P,
+ ORG,
+ seo.ticketId,
+ { agentId: MKT },
+ { userId: "alice", sessionId: mktDesk },
+ );
+ await service.attachTicket(P, ORG, social.ticketId, mktWork, {
+ userId: "alice",
+ sessionId: mktDesk,
+ });
+ h.costs.set(siteWork, 40);
+ h.costs.set(mktWork, 30);
+ h.costs.set(devDesk, 2);
+ const finance = await service.finance(P, ORG);
+ const byId = new Map(finance.employees.map((e) => [e.agentId, e]));
+ expect(byId.get(DEV)).toMatchObject({ own: 42, cumulative: 42, budget: 100 });
+ expect(byId.get(MKT)).toMatchObject({ own: 30, cumulative: 30, budget: 60 });
+ expect(byId.get(CEO)).toMatchObject({ own: 0, cumulative: 72, budget: 300 });
+ expect(finance.total).toBe(72);
+ const ticketCost = new Map(finance.tickets.map((t) => [t.ticketId, t]));
+ expect(ticketCost.get(site.ticketId)?.cost).toBe(40);
+ // The shared marketing session is split between its two tickets; the parent rolls everything up.
+ expect(ticketCost.get(seo.ticketId)?.cost).toBe(15);
+ expect(ticketCost.get(social.ticketId)?.cost).toBe(15);
+ expect(ticketCost.get(parent.ticketId)?.rolledUp).toBe(70);
+
+ // 10. Revenue: the paid featured slots ship and the board is told.
+ const slotWork = await service.startTicket(
+ P,
+ ORG,
+ slots.ticketId,
+ { agentId: DEV },
+ { userId: "alice", sessionId: devDesk },
+ );
+ await service.progressTicket(
+ P,
+ ORG,
+ slots.ticketId,
+ "Pinned-slot checkout works; first slot sold for a week",
+ { userId: "alice", sessionId: slotWork.sessionId },
+ );
+ await service.moveTicket(P, ORG, slots.ticketId, "done", undefined, ceoActor);
+ await service.sendChannelMessage(P, ORG, "alice", DEFAULT_CHANNEL_ID, {
+ text: "@alice The site is live, SEO and social are running, and the first paid featured slot sold.",
+ sessionId: ceoDesk,
+ });
+ const overview = await service.detail(P, ORG, "alice");
+ expect(overview.board).toMatchObject({ done: 2, in_progress: 2, proposed: 1 });
+ expect(overview.employeeCount).toBe(5);
+ expect(overview.spend).toMatchObject({ cost: 72, budget: 300 });
+ expect(overview.pending.mentions).toBeGreaterThanOrEqual(1);
+ expect(overview.recentMessages.at(-1)?.text).toContain("first paid featured slot sold");
+
+ // Every automatic message went through the marker the frontend folds, never a bare prompt.
+ for (const s of h.started) expect(parseOrgTriggerMessage(s.text)).not.toBeNull();
+ expect(h.errors).toEqual([]);
+ });
+});
diff --git a/packages/server/test/organizations-routes.test.ts b/packages/server/test/organizations-routes.test.ts
new file mode 100644
index 00000000..19e8d6a3
--- /dev/null
+++ b/packages/server/test/organizations-routes.test.ts
@@ -0,0 +1,589 @@
+/**
+ * Organization routes over the real app: the admin master switch starts off, 404s the whole
+ * group while it is off, and is reported by /api/me and /api/admin/settings; Project
+ * authorization gates reads and writes (an outsider gets 404, a member may write), and no
+ * route deletes an organization; bodies are validated before the service is asked; and the
+ * calling session and employee ride write bodies as `sessionId` / `agentId` (a read's query
+ * string), but only from the control environment's API token — a signed-in member's claim is
+ * dropped. The service itself is a recording fake here — its semantics have their
+ * own suites — so no Agent is created and no session runs.
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import type { MeResponse, ServerSettingsResponse } from "../src/api/types.js";
+import type { OrganizationService } from "../src/runtime/organization/service.js";
+import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+type Call = { method: string; args: unknown[] };
+
+function fakeService(calls: Call[]): OrganizationService {
+ const handler: ProxyHandler<Record<string, unknown>> = {
+ get: (_target, method) => {
+ if (typeof method !== "string") return undefined;
+ return async (...args: unknown[]) => {
+ calls.push({ method, args });
+ switch (method) {
+ case "list":
+ return [];
+ case "detail":
+ case "create":
+ return { projectId: args[0], orgId: "acme", name: "Acme", employeeCount: 1 };
+ case "tickets":
+ return {
+ columns: { proposed: [], in_progress: [], review: [], done: [], rejected: [] },
+ invalidFiles: [],
+ };
+ case "channelMessages":
+ return {
+ channelId: args[3],
+ date: "2026-09-01",
+ days: [],
+ messages: [],
+ unread: 0,
+ mentionsMe: 0,
+ };
+ case "channels":
+ return { channels: [] };
+ case "channel":
+ case "createChannel":
+ case "patchChannel":
+ case "addChannelMember":
+ 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":
+ return {
+ files: [{ path: "README.md", size: 12, updatedAt: "2026-09-01T00:00:00.000Z" }],
+ };
+ case "handbookFile":
+ case "writeHandbookFile":
+ return { path: args[2], content: "# Doc" };
+ default:
+ return { ok: true, method };
+ }
+ };
+ },
+ };
+ return new Proxy({}, handler) as unknown as OrganizationService;
+}
+
+/**
+ * A write as a Session's subprocess would send it: the boot's local API token as a Bearer
+ * header and no cookie, which is what `controlEnv` hands the CLI (auth/api-token.ts).
+ */
+function fromSession(t: TestApp, apiPath: string, body: unknown) {
+ return t.app.request(apiPath, {
+ method: "POST",
+ headers: {
+ authorization: `Bearer ${t.deps.authService.localApiToken()}`,
+ "content-type": "application/json",
+ },
+ body: JSON.stringify(body),
+ });
+}
+
+describe("organization routes", () => {
+ let t: TestApp;
+ let calls: Call[];
+ let owner: ReturnType<typeof apiClient>;
+ let ownerProject: string;
+
+ beforeEach(async () => {
+ calls = [];
+ // The service is a recording fake: it goes in as a boot override, since the route
+ // group takes the one the module tree provides at creation.
+ t = await createTestApp({ orgService: fakeService(calls) });
+ // Company mode is off on a server nobody turned it on (its own test below): every case
+ // here is about what the routes do once an admin has enabled it.
+ t.deps.serverSettingsRepo.setCompanyMode(true);
+ const u = await provisionUser(t.app, "olivia");
+ owner = apiClient(t.app, u.cookie);
+ ownerProject = "olivia-default_project";
+ });
+
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ it("is off on a server whose admin never touched the switch", async () => {
+ const fresh = await createTestApp();
+ try {
+ const admin = await loginAdmin(fresh.app);
+ const settings = (await (
+ await apiClient(fresh.app, admin.cookie).get("/api/admin/settings")
+ ).json()) as ServerSettingsResponse;
+ expect(settings.settings.companyMode).toBe(false);
+ const u = await provisionUser(fresh.app, "olivia");
+ const api = apiClient(fresh.app, u.cookie);
+ const me = (await (await api.get("/api/me")).json()) as MeResponse;
+ expect(me.companyMode).toBe(false);
+ const res = await api.get("/api/projects/olivia-default_project/organizations");
+ expect(res.status).toBe(404);
+ } finally {
+ await fresh.cleanup();
+ }
+ });
+
+ it("answers 404 on every route while the admin switch is off, and /api/me reports it", async () => {
+ const admin = await loginAdmin(t.app);
+ const adminApi = apiClient(t.app, admin.cookie);
+ const before = (await (
+ await adminApi.get("/api/admin/settings")
+ ).json()) as ServerSettingsResponse;
+ expect(before.settings.companyMode).toBe(true);
+ const put = await adminApi.put("/api/admin/settings", { companyMode: false });
+ expect(put.status).toBe(200);
+ expect(((await put.json()) as ServerSettingsResponse).settings.companyMode).toBe(false);
+ const me = (await (await owner.get("/api/me")).json()) as MeResponse;
+ expect(me.companyMode).toBe(false);
+ const res = await owner.get(`/api/projects/${ownerProject}/organizations`);
+ expect(res.status).toBe(404);
+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe("company_mode_off");
+ expect(calls).toEqual([]);
+ await adminApi.put("/api/admin/settings", { companyMode: true });
+ expect((await owner.get(`/api/projects/${ownerProject}/organizations`)).status).toBe(200);
+ });
+
+ it("gates by Project access: outsiders 404, members read and write", async () => {
+ const stranger = apiClient(t.app, (await provisionUser(t.app, "stranger")).cookie);
+ expect((await stranger.get(`/api/projects/${ownerProject}/organizations`)).status).toBe(404);
+ expect(
+ (
+ await stranger.post(
+ `/api/projects/${ownerProject}/organizations/acme/channels/default_channel/messages`,
+ { text: "hi" },
+ )
+ ).status,
+ ).toBe(404);
+
+ const member = await provisionUser(t.app, "mia");
+ const grant = await owner.post(`/api/projects/${ownerProject}/members`, { userId: "mia" });
+ expect([200, 201]).toContain(grant.status);
+ const memberApi = apiClient(t.app, member.cookie);
+ expect((await memberApi.get(`/api/projects/${ownerProject}/organizations`)).status).toBe(200);
+ const send = await memberApi.post(
+ `/api/projects/${ownerProject}/organizations/acme/channels/default_channel/messages`,
+ { text: "hi @all" },
+ );
+ expect(send.status).toBe(201);
+ expect(calls.at(-1)).toMatchObject({
+ method: "sendChannelMessage",
+ args: [ownerProject, "acme", "mia", "default_channel", { text: "hi @all" }],
+ });
+ });
+
+ it("has no route that deletes an organization", async () => {
+ // Pause is the whole lifecycle. DELETE is not a route, so the Project's own owner gets 404
+ // and the service is never asked; pausing is a PATCH like any other setting.
+ expect((await owner.delete(`/api/projects/${ownerProject}/organizations/acme`)).status).toBe(
+ 404,
+ );
+ expect(calls).toEqual([]);
+ const patch = await owner.patch(`/api/projects/${ownerProject}/organizations/acme`, {
+ status: "paused",
+ });
+ expect(patch.status).toBe(200);
+ // The caller rides along: a settings write is the one repair for a config that stopped
+ // parsing, and the rewrite needs a `created_by` to put back into the file.
+ expect(calls.at(-1)).toMatchObject({
+ method: "patch",
+ args: [ownerProject, "acme", { status: "paused" }, "olivia"],
+ });
+ });
+
+ it("validates bodies before asking the service", async () => {
+ const base = `/api/projects/${ownerProject}/organizations`;
+ expect((await owner.post(base, { orgId: "acme" })).status).toBe(400); // mission missing
+ expect(
+ (await owner.post(`${base}/acme/tickets/not-an-id/move`, { status: "done" })).status,
+ ).toBe(400);
+ expect(
+ (await owner.post(`${base}/acme/tickets/2026-09-01-site/move`, { status: "flying" })).status,
+ ).toBe(400);
+ expect((await owner.post(`${base}/acme/employees`, { title: "HR" })).status).toBe(400); // reportsTo missing
+ // A calendar name the store would not list back is refused here, not written and then lost.
+ for (const name of ["bad name", "_daily", "a".repeat(65)]) {
+ expect(
+ (
+ await owner.post(`${base}/acme/calendar`, {
+ agentId: "acme_hr",
+ name,
+ prompt: "x",
+ enabled: true,
+ startAt: "now",
+ })
+ ).status,
+ ).toBe(400);
+ }
+ expect(
+ (await owner.get(`${base}/acme/channels/default_channel/messages?date=yesterday`)).status,
+ ).toBe(400);
+ expect((await owner.get(`${base}/acme/finance?period=2026-9`)).status).toBe(400);
+ // A month that is not a month: the service would answer it with the current month's spend.
+ expect((await owner.get(`${base}/acme/finance?period=2026-13`)).status).toBe(400);
+ expect((await owner.get(`${base}/acme/finance?period=2026-00`)).status).toBe(400);
+ expect(calls).toEqual([]);
+ const create = await owner.post(base, {
+ orgId: "acme",
+ mission: "Build a marketplace",
+ name: "Acme",
+ });
+ expect(create.status).toBe(201);
+ expect(calls.at(-1)).toMatchObject({
+ method: "create",
+ args: [
+ ownerProject,
+ { orgId: "acme", mission: "Build a marketplace", name: "Acme" },
+ "olivia",
+ ],
+ });
+ });
+
+ it("validates an id proposal and 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,
+ );
+ expect(
+ (await owner.post(base, { orgId: "acme", mission: "做一个市场", language: "zh" })).status,
+ ).toBe(201);
+ expect(calls.at(-1)).toMatchObject({
+ method: "create",
+ args: [ownerProject, { orgId: "acme", mission: "做一个市场", language: "zh" }, "olivia"],
+ });
+ expect((await owner.patch(`${base}/acme`, { language: "de" })).status).toBe(400);
+ expect((await owner.patch(`${base}/acme`, { language: "en" })).status).toBe(200);
+ expect(calls.at(-1)).toEqual({
+ method: "patch",
+ args: [ownerProject, "acme", { language: "en" }, "olivia"],
+ });
+ });
+
+ it("carries a ticket owner and slug through to the service, and validates them first", async () => {
+ const base = `/api/projects/${ownerProject}/organizations/acme`;
+ const created = await owner.post(`${base}/tickets`, {
+ title: "Audit the calendar",
+ goal: "One event per employee",
+ owner: "agent:acme_hr",
+ slug: "audit-the-calendar",
+ });
+ expect(created.status).toBe(201);
+ expect(calls.at(-1)).toMatchObject({
+ method: "createTicket",
+ args: [
+ ownerProject,
+ "acme",
+ {
+ title: "Audit the calendar",
+ goal: "One event per employee",
+ owner: "agent:acme_hr",
+ slug: "audit-the-calendar",
+ },
+ { userId: "olivia" },
+ ],
+ });
+ // An empty or oversized owner is no principal, so it never reaches the service.
+ calls.length = 0;
+ expect((await owner.post(`${base}/tickets`, { title: "T", owner: "" })).status).toBe(400);
+ expect(
+ (await owner.post(`${base}/tickets`, { title: "T", owner: "a".repeat(101) })).status,
+ ).toBe(400);
+ expect(calls).toEqual([]);
+ // An owner cannot be cleared: a ticket always has one, so `null` is refused as a shape.
+ expect((await owner.put(`${base}/tickets/2026-09-01-site`, { owner: null })).status).toBe(400);
+ });
+
+ it("routes handbook documents by their relative path and keeps the index", async () => {
+ const base = `/api/projects/${ownerProject}/organizations/acme/handbook`;
+ expect((await owner.get(`${base}/files`)).status).toBe(200);
+ expect(calls.at(-1)).toEqual({ method: "handbookFiles", args: [ownerProject, "acme"] });
+
+ const doc = "decisions/2026-09-02-hire-plan.md";
+ expect((await owner.get(`${base}/files/${doc}`)).status).toBe(200);
+ expect(calls.at(-1)).toEqual({ method: "handbookFile", args: [ownerProject, "acme", doc] });
+
+ const put = await owner.put(`${base}/files/${doc}`, { content: "# Hire plan" });
+ expect(put.status).toBe(200);
+ expect(calls.at(-1)).toEqual({
+ method: "writeHandbookFile",
+ args: [ownerProject, "acme", doc, "# Hire plan"],
+ });
+ expect((await owner.put(`${base}/files/${doc}`, {})).status).toBe(400); // content missing
+
+ expect((await owner.delete(`${base}/files/${doc}`)).status).toBe(204);
+ expect(calls.at(-1)).toEqual({
+ method: "deleteHandbookFile",
+ args: [ownerProject, "acme", doc],
+ });
+ });
+
+ it("routes the channel family and validates its bodies", async () => {
+ const base = `/api/projects/${ownerProject}/organizations/acme/channels`;
+ expect((await owner.get(base)).status).toBe(200);
+ expect(calls.at(-1)).toEqual({
+ method: "channels",
+ args: [ownerProject, "acme", { userId: "olivia" }],
+ });
+
+ const create = await owner.post(base, { channelId: "site", name: "Site", purpose: "Ship it" });
+ expect(create.status).toBe(201);
+ expect(calls.at(-1)).toEqual({
+ method: "createChannel",
+ args: [
+ ownerProject,
+ "acme",
+ { channelId: "site", name: "Site", purpose: "Ship it" },
+ { userId: "olivia" },
+ ],
+ });
+
+ expect((await owner.get(`${base}/site`)).status).toBe(200);
+ expect(calls.at(-1)).toEqual({
+ method: "channel",
+ args: [ownerProject, "acme", "site", { userId: "olivia" }],
+ });
+
+ const patch = await owner.patch(`${base}/site`, { name: "Site launch", archived: true });
+ expect(patch.status).toBe(200);
+ expect(calls.at(-1)).toEqual({
+ method: "patchChannel",
+ args: [
+ ownerProject,
+ "acme",
+ "site",
+ { name: "Site launch", archived: true },
+ { userId: "olivia" },
+ ],
+ });
+
+ const add = await owner.post(`${base}/site/members`, { principal: "agent:acme_dev" });
+ expect(add.status).toBe(201);
+ expect(calls.at(-1)).toEqual({
+ method: "addChannelMember",
+ args: [ownerProject, "acme", "site", "agent:acme_dev", { userId: "olivia" }],
+ });
+
+ const remove = await owner.delete(`${base}/site/members/agent:acme_dev`);
+ expect(remove.status).toBe(204);
+ expect(calls.at(-1)).toEqual({
+ method: "removeChannelMember",
+ args: [ownerProject, "acme", "site", "agent:acme_dev", { userId: "olivia" }],
+ });
+
+ // A path id no channel could carry names no channel, and neither reaches the service.
+ calls.length = 0;
+ expect((await owner.get(`${base}/Site`)).status).toBe(404);
+ expect((await owner.post(base, { channelId: "Site" })).status).toBe(400);
+ expect((await owner.post(base, { name: "no id" })).status).toBe(400);
+ expect((await owner.patch(`${base}/site`, { archived: "yes" })).status).toBe(400);
+ expect((await owner.post(`${base}/site/members`, { principal: "acme_dev" })).status).toBe(400);
+ expect((await owner.delete(`${base}/site/members/all`)).status).toBe(400);
+ expect(calls).toEqual([]);
+ });
+
+ it("carries the channel of the path through the message routes", async () => {
+ const base = `/api/projects/${ownerProject}/organizations/acme/channels`;
+ const all = await owner.get(`${base}/default_channel/messages`);
+ expect(all.status).toBe(200);
+ expect(calls.at(-1)).toEqual({
+ method: "channelMessages",
+ args: [ownerProject, "acme", { userId: "olivia" }, "default_channel", {}],
+ });
+ expect(
+ (await (await owner.get(`${base}/site/messages?date=2026-09-01`)).json()) as unknown,
+ ).toMatchObject({ channelId: "site" });
+ expect(calls.at(-1)).toEqual({
+ method: "channelMessages",
+ args: [ownerProject, "acme", { userId: "olivia" }, "site", { date: "2026-09-01" }],
+ });
+
+ expect((await owner.post(`${base}/site/messages`, { text: "hi" })).status).toBe(201);
+ expect(calls.at(-1)).toMatchObject({
+ method: "sendChannelMessage",
+ args: [ownerProject, "acme", "olivia", "site", { text: "hi" }],
+ });
+
+ expect((await owner.post(`${base}/site/read`, { upTo: "msg-1" })).status).toBe(204);
+ expect(calls.at(-1)).toEqual({
+ method: "markRead",
+ args: [ownerProject, "acme", "olivia", "site", "msg-1"],
+ });
+
+ // A path id no channel could carry names no channel; the bodies are validated too.
+ calls.length = 0;
+ expect((await owner.get(`${base}/Site/messages`)).status).toBe(404);
+ expect((await owner.post(`${base}/Site/messages`, { text: "hi" })).status).toBe(404);
+ expect((await owner.post(`${base}/site/messages`, {})).status).toBe(400);
+ expect((await owner.post(`${base}/site/read`, {})).status).toBe(400);
+ expect(calls).toEqual([]);
+ });
+
+ it("honours a read's sessionId only from the control environment", async () => {
+ const base = `/api/projects/${ownerProject}/organizations/acme/channels`;
+ expect([200, 201]).toContain(
+ (await owner.post(`/api/projects/${ownerProject}/members`, { userId: "admin" })).status,
+ );
+ const res = await t.app.request(`${base}?sessionId=session-desk&agentId=acme_dev`, {
+ headers: { authorization: `Bearer ${t.deps.authService.localApiToken()}` },
+ });
+ expect(res.status).toBe(200);
+ expect(calls.at(-1)).toEqual({
+ method: "channels",
+ args: [
+ ownerProject,
+ "acme",
+ { userId: "admin", sessionId: "session-desk", agentId: "acme_dev" },
+ ],
+ });
+ // The same claim over a cookie is dropped: a cookie proves a person, not a session.
+ expect((await owner.get(`${base}?sessionId=session-desk&agentId=acme_dev`)).status).toBe(200);
+ expect(calls.at(-1)).toEqual({
+ method: "channels",
+ args: [ownerProject, "acme", { userId: "olivia" }],
+ });
+ });
+
+ it("passes the calling session through write bodies so the file records the employee", async () => {
+ const base = `/api/projects/${ownerProject}/organizations/acme/tickets/2026-09-01-site`;
+ // The control environment's credential: the admin joins the Project the CLI writes to.
+ const grant = await owner.post(`/api/projects/${ownerProject}/members`, { userId: "admin" });
+ expect([200, 201]).toContain(grant.status);
+ const res = await fromSession(t, `${base}/progress`, {
+ text: "half done",
+ sessionId: "session-desk",
+ agentId: "acme_dev",
+ });
+ expect(res.status).toBe(200);
+ expect(calls.at(-1)).toMatchObject({
+ method: "progressTicket",
+ args: [
+ ownerProject,
+ "acme",
+ "2026-09-01-site",
+ "half done",
+ { userId: "admin", sessionId: "session-desk", agentId: "acme_dev" },
+ ],
+ });
+ const start = await owner.post(`${base}/start`, { agentId: "acme_dev", message: "go" });
+ expect(start.status).toBe(202);
+ expect(await start.json()).toEqual({ sessionId: "session-x" });
+ // Who asks rides along: only the ticket's owner (or a person) may start its sessions.
+ expect(calls.at(-1)).toMatchObject({
+ method: "startTicket",
+ args: [
+ ownerProject,
+ "acme",
+ "2026-09-01-site",
+ { agentId: "acme_dev", message: "go" },
+ { userId: "olivia" },
+ ],
+ });
+ // On `start`, the body's `agentId` is the employee the session RUNS AS, not the caller:
+ // the owner may enlist a colleague on its own ticket, so it never becomes the identity.
+ const startFromDesk = await fromSession(t, `${base}/start`, {
+ sessionId: "session-desk",
+ agentId: "acme_mkt",
+ });
+ expect(startFromDesk.status).toBe(202);
+ expect(calls.at(-1)).toMatchObject({
+ method: "startTicket",
+ args: [
+ ownerProject,
+ "acme",
+ "2026-09-01-site",
+ { agentId: "acme_mkt" },
+ { userId: "admin", sessionId: "session-desk" },
+ ],
+ });
+ const block = await owner.post(`${base}/block`, { reason: "waiting", by: "user:olivia" });
+ expect(block.status).toBe(200);
+ expect(calls.at(-1)).toMatchObject({
+ method: "blockTicket",
+ args: [
+ ownerProject,
+ "acme",
+ "2026-09-01-site",
+ "waiting",
+ "user:olivia",
+ { userId: "olivia" },
+ ],
+ });
+ const unblock = await owner.post(`${base}/unblock`);
+ expect(unblock.status).toBe(200);
+ expect(calls.at(-1)).toMatchObject({ method: "unblockTicket" });
+ });
+
+ it("drops a signed-in member's session id: the write cannot be attributed to that employee", async () => {
+ const base = `/api/projects/${ownerProject}/organizations/acme`;
+ const mallory = await provisionUser(t.app, "mallory");
+ expect([200, 201]).toContain(
+ (await owner.post(`/api/projects/${ownerProject}/members`, { userId: "mallory" })).status,
+ );
+ const memberApi = apiClient(t.app, mallory.cookie);
+
+ // The CEO desk session id is in the GET /:orgId response, so every member can quote it.
+ const posted = await memberApi.post(`${base}/channels/default_channel/messages`, {
+ text: "ship it",
+ sessionId: "session-ceo-desk",
+ });
+ expect(posted.status).toBe(201);
+ expect(calls.at(-1)?.args).toEqual([
+ ownerProject,
+ "acme",
+ "mallory",
+ "default_channel",
+ { text: "ship it" },
+ ]);
+
+ const progress = await memberApi.post(`${base}/tickets/2026-09-01-site/progress`, {
+ text: "done",
+ sessionId: "session-ceo-desk",
+ agentId: "acme_ceo",
+ });
+ expect(progress.status).toBe(200);
+ expect(calls.at(-1)?.args.at(-1)).toEqual({ userId: "mallory" });
+
+ // `attach` takes the Session to attach in the same field: it still arrives, as an argument
+ // rather than an identity — this is the Web App's attach button.
+ const attach = await memberApi.post(`${base}/tickets/2026-09-01-site/attach`, {
+ sessionId: "session-dev",
+ });
+ expect(attach.status).toBe(200);
+ expect(calls.at(-1)?.args).toEqual([
+ ownerProject,
+ "acme",
+ "2026-09-01-site",
+ "session-dev",
+ { userId: "mallory" },
+ ]);
+ });
+});
diff --git a/packages/server/test/semantic-id.test.ts b/packages/server/test/semantic-id.test.ts
new file mode 100644
index 00000000..06c04fb3
--- /dev/null
+++ b/packages/server/test/semantic-id.test.ts
@@ -0,0 +1,100 @@
+import { describe, expect, it } from "vitest";
+import {
+ fallbackSemanticId,
+ placeholderSemanticId,
+ prefixSemanticId,
+ sanitizeSuggestedId,
+ uniqueSemanticId,
+} from "../src/organization/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");
+ });
+
+ 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");
+ });
+
+ it("a one-character name is already long enough once prefixed", () => {
+ expect(fallbackSemanticId("x", "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");
+ });
+
+ it("yields null for a name with no ASCII letters or digits", () => {
+ expect(fallbackSemanticId("科研公司", "org")).toBeNull();
+ expect(fallbackSemanticId(" ", "org")).toBeNull();
+ expect(fallbackSemanticId("!!!", "channel")).toBeNull();
+ });
+
+ it("keeps the ASCII part of a mixed name", () => {
+ expect(fallbackSemanticId("科研 Lab 2", "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)}`);
+ });
+
+ 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");
+ // The bare core is not the id, so holding it takes nothing.
+ expect(fallbackSemanticId("Site", "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");
+ });
+});
+
+describe("uniqueSemanticId", () => {
+ it("keeps the suffix inside the length cap", () => {
+ const base = "b".repeat(64);
+ expect(uniqueSemanticId(base, [base])).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");
+ });
+
+ it("does not double a prefix the model added itself", () => {
+ expect(sanitizeSuggestedId("co_research_lab", "org")).toBe("co_research_lab");
+ });
+
+ it("returns null for an answer that carries no ASCII", () => {
+ expect(sanitizeSuggestedId("科研实验室", "org")).toBeNull();
+ });
+});
+
+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");
+ });
+
+ it("pads a single-digit month and day", () => {
+ expect(placeholderSemanticId("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",
+ );
+ });
+});
diff --git a/packages/server/test/session-index.test.ts b/packages/server/test/session-index.test.ts
index 9ddbcef4..394de94b 100644
--- a/packages/server/test/session-index.test.ts
+++ b/packages/server/test/session-index.test.ts
@@ -612,10 +612,55 @@ describe("session-index", () => {
expect(t.deps.sessionsRepo.findById(fromCli.session.sessionId)!.client).toBe("cli");
expect(t.deps.sessionsRepo.findById(fromWeb.session.sessionId)!.client).toBe("web");
expect((await api.post(base(), { client: "carrier-pigeon" })).status).toBe(400);
+ // "org" is the organization runtime's own marker: it calls SessionService directly, so
+ // no request may claim it and hide its Session from development mode's list.
+ expect((await api.post(base(), { client: "org" })).status).toBe(400);
const list = (await (await api.get(base())).json()) as SessionsResponse;
const ids = list.sessions.map((s) => s.sessionId);
expect(ids).toContain(fromCli.session.sessionId);
expect(ids).toContain(fromWeb.session.sessionId);
+ // The DTO carries the stamp, which is what the two modes' lists partition on.
+ expect(list.sessions.find((s) => s.sessionId === fromCli.session.sessionId)!.client).toBe(
+ "cli",
+ );
+ expect(fromWeb.session.client).toBe("web");
+ });
+
+ it("an organization's session carries client: 'org' through the list and the single GET", async () => {
+ const deskSession = "session-2026-07-03-09-00-00-0abc0002";
+ t.deps.sessionsRepo.insert({
+ sessionId: deskSession,
+ projectId,
+ agentId: "default_agent",
+ provider: "custom",
+ modelId: "m-desk",
+ workspace: "/tmp/w-desk",
+ approvalMode: "allow-all",
+ title: null,
+ client: "org",
+ createdAt: "2026-07-03T09:00:00.000Z",
+ lastActiveAt: "2026-07-03T09:00:00.000Z",
+ });
+ const list = (await (await api.get(base())).json()) as SessionsResponse;
+ expect(list.sessions.find((s) => s.sessionId === deskSession)!.client).toBe("org");
+ const one = (await (await api.get(`/api/sessions/${deskSession}`)).json()) as SessionResponse;
+ expect(one.session.client).toBe("org");
+ // A row that predates the column says nothing rather than claiming a client.
+ const legacyId = "session-2026-07-03-10-00-00-0abc0003";
+ t.deps.sessionsRepo.insert({
+ sessionId: legacyId,
+ projectId,
+ agentId: "default_agent",
+ provider: "custom",
+ modelId: "m-legacy",
+ workspace: "/tmp/w-legacy",
+ approvalMode: "allow-all",
+ title: null,
+ createdAt: "2026-07-03T10:00:00.000Z",
+ lastActiveAt: "2026-07-03T10:00:00.000Z",
+ });
+ const again = (await (await api.get(base())).json()) as SessionsResponse;
+ expect(again.sessions.find((s) => s.sessionId === legacyId)!.client).toBeUndefined();
});
it("legacy rows without a client marker stay visible by default (grandfathered as web)", async () => {
@@ -715,6 +760,43 @@ describe("session-index", () => {
expect(list.sessions[list.sessions.length - 1]!.sessionId).toBe(older);
});
+ it("orgId marks organization sessions on the list and the single GET; ordinary rows carry none", async () => {
+ await configureModels();
+ const create = async () =>
+ ((await (await api.post(base(), {})).json()) as SessionCreateResponse).session.sessionId;
+ const deskSession = await create();
+ const ticketSession = await create();
+ const plainSession = await create();
+ // The organization caches are the source: a desk row for the employee, a ticket row for
+ // a session contributing to one of the organization's tickets.
+ t.deps.orgCacheRepo.syncDeskSessions(projectId, "acme", [
+ { sessionId: deskSession, agentId: "acme_ceo", current: true },
+ ]);
+ t.deps.orgCacheRepo.addTicketSession(
+ projectId,
+ "acme",
+ "2026-09-02-site",
+ ticketSession,
+ "acme_dev",
+ );
+
+ const list = (await (await api.get(base())).json()) as SessionsResponse;
+ const orgIdOf = (sessionId: string) =>
+ list.sessions.find((s) => s.sessionId === sessionId)?.orgId;
+ expect(orgIdOf(deskSession)).toBe("acme");
+ expect(orgIdOf(ticketSession)).toBe("acme");
+ expect(orgIdOf(plainSession)).toBeUndefined();
+
+ for (const [sessionId, orgId] of [
+ [deskSession, "acme"],
+ [ticketSession, "acme"],
+ [plainSession, undefined],
+ ] as const) {
+ const got = (await (await api.get(`/api/sessions/${sessionId}`)).json()) as SessionResponse;
+ expect(got.session.orgId).toBe(orgId);
+ }
+ });
+
it("PATCH approval mode persists and reads back", async () => {
await configureModels();
const { session } = (await (await api.post(base(), {})).json()) as SessionCreateResponse;
diff --git a/packages/server/test/session-manager-human-input.test.ts b/packages/server/test/session-manager-human-input.test.ts
new file mode 100644
index 00000000..4ed6fb80
--- /dev/null
+++ b/packages/server/test/session-manager-human-input.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from "vitest";
+import { userText } from "@prismshadow/penguin-core";
+import { isHumanInput } from "../src/runtime/session-manager.js";
+
+describe("isHumanInput", () => {
+ it("is true for a person's message, with or without an explicit sender", () => {
+ expect(isHumanInput([userText("hello")])).toBe(true);
+ expect(isHumanInput([userText("hello", "user")])).toBe(true);
+ });
+
+ it("is false for anything the harness injected", () => {
+ expect(isHumanInput([userText("[org_trigger]…", "server")])).toBe(false);
+ expect(isHumanInput([userText("context", "harness")])).toBe(false);
+ expect(isHumanInput([userText("hello"), userText("context", "harness")])).toBe(false);
+ });
+});
diff --git a/packages/server/test/skills.test.ts b/packages/server/test/skills.test.ts
index 7bece58a..0bc598bb 100644
--- a/packages/server/test/skills.test.ts
+++ b/packages/server/test/skills.test.ts
@@ -76,6 +76,7 @@ describe("skills api", () => {
"office-productivity",
"software-development",
"ai-app-development",
+ "agent-company",
]);
for (const group of body.groups) {
expect(group.title.length).toBeGreaterThan(0);
diff --git a/packages/server/test/utility-completion.test.ts b/packages/server/test/utility-completion.test.ts
new file mode 100644
index 00000000..11803b77
--- /dev/null
+++ b/packages/server/test/utility-completion.test.ts
@@ -0,0 +1,180 @@
+/**
+ * The one-off utility completion behind semantic id proposals. It never throws and never
+ * reaches for a network here: the config it would run with and the collector that drains the
+ * stream are both pure, so the two things that decide whether an answer arrives — thinking
+ * off, and a budget the answer fits in after the thinking — are asserted directly, and every
+ * dead end is checked for carrying its reason rather than a bare "no answer".
+ */
+import fs from "node:fs/promises";
+import { wire } from "@prismshadow/penguin-core/kernel";
+import { describe, expect, it } from "vitest";
+import {
+ assistantText,
+ partialText,
+ partialThinking,
+ projectConfigPath,
+ projectDir,
+ thinkingMessage,
+ tokenUsage,
+ emptyTokenCounts,
+} from "@prismshadow/penguin-core";
+import type { LLMOutcome, OmniMessage } from "@prismshadow/penguin-core";
+import {
+ ProjectConfigService,
+ collectUtilityCompletion,
+ utilityCompletionConfig,
+} from "../src/services/project-config-service.js";
+import { makeTempRoot } from "./helpers.js";
+
+/** A stream shaped the way the real translator shapes one: partial fragments, then the complete backfill. */
+async function* streamOf(
+ messages: OmniMessage[],
+ outcome: LLMOutcome,
+): AsyncGenerator<OmniMessage, LLMOutcome> {
+ for (const m of messages) yield m;
+ return outcome;
+}
+
+describe("utilityCompletionConfig", () => {
+ it("turns thinking off and asks for the shared meta budget, not a budget the size of an id", () => {
+ const config = utilityCompletionConfig("m-bench", { api_key: "sk-1" });
+ expect(config.thinkingLevel).toBe("none");
+ expect(config.maxTokens).toBe(300);
+ expect(config.apiKey).toBe("sk-1");
+ expect(config.tools).toEqual([]);
+ });
+
+ it("still honours a per-model cap pinned below the budget, and the entry's protocol", () => {
+ const config = utilityCompletionConfig("m-bench", {
+ max_tokens: 128,
+ base_url: "https://example.test/v1",
+ // The pre-0.4.2 spelling is normalized like everywhere else.
+ client_type: "openai",
+ });
+ expect(config.maxTokens).toBe(128);
+ expect(config.baseUrl).toBe("https://example.test/v1");
+ expect(config.clientType).toBe("openai-chat");
+ });
+
+ it("never tightens to an uncapped entry's -1", () => {
+ expect(utilityCompletionConfig("m-bench", { max_tokens: -1 }).maxTokens).toBe(300);
+ });
+});
+
+describe("collectUtilityCompletion", () => {
+ it("returns the text of a model that thought first and answered second", async () => {
+ const result = await collectUtilityCompletion(
+ streamOf(
+ [
+ partialThinking("start"),
+ partialThinking("delta", "the name is Chinese, translate it"),
+ partialThinking("stop", "", "completed"),
+ thinkingMessage("the name is Chinese, translate it", "completed"),
+ partialText("start"),
+ partialText("delta", "research_paper"),
+ partialText("delta", "_lab"),
+ partialText("stop", "", "completed"),
+ assistantText("research_paper_lab", "completed"),
+ tokenUsage(emptyTokenCounts(), emptyTokenCounts()),
+ ],
+ { status: "completed" },
+ ),
+ );
+ // The complete backfill is counted once; the partial deltas that built it are not counted again.
+ expect(result).toEqual({ ok: true, text: "research_paper_lab" });
+ });
+
+ it("reports the provider's reason when the whole budget went to thinking", async () => {
+ const result = await collectUtilityCompletion(
+ streamOf(
+ [
+ partialThinking("start"),
+ partialThinking("delta", "let me consider every possible identifier"),
+ partialThinking("stop", "", "retryable"),
+ thinkingMessage("let me consider every possible identifier", "retryable"),
+ ],
+ {
+ status: "retryable",
+ errorCode: "malformed",
+ errorMessage:
+ 'OpenaiClient returned no content other than thinking (finish_reason="length").',
+ },
+ ),
+ );
+ expect(result).toEqual({
+ ok: false,
+ cause: "failed",
+ error: 'OpenaiClient returned no content other than thinking (finish_reason="length").',
+ });
+ });
+
+ it("falls back to the bare status when the outcome carries no message", async () => {
+ expect(await collectUtilityCompletion(streamOf([], { status: "aborted" }))).toEqual({
+ ok: false,
+ cause: "failed",
+ error: "aborted",
+ });
+ });
+
+ it("treats a whitespace-only answer as no answer", async () => {
+ const result = await collectUtilityCompletion(
+ streamOf([assistantText(" \n ", "completed")], { status: "completed" }),
+ );
+ expect(result).toEqual({ ok: false, cause: "failed", error: "completed" });
+ });
+});
+
+describe("completeOnce", () => {
+ it("says which way it fell through when the Project has nothing to run it on", async () => {
+ const root = await makeTempRoot();
+ const service = wire(ProjectConfigService, { paths: { root } });
+ // No `.project_config.toml` at all.
+ expect(await service.completeOnce("p1", "Name: Plugin Marketplace")).toEqual({
+ ok: false,
+ cause: "no_model",
+ error: "the Project names no default model",
+ });
+
+ await fs.mkdir(projectDir(root, "p1"), { recursive: true });
+ const file = projectConfigPath(root, "p1");
+ // A config that names no default model.
+ await fs.writeFile(file, '[[models]]\nprovider = "custom"\nmodel_id = "m-bench"\n', "utf8");
+ expect(await service.completeOnce("p1", "Name: Plugin Marketplace")).toMatchObject({
+ ok: false,
+ cause: "no_model",
+ });
+
+ // A default model whose entry is gone: there is nothing to build a client from, and a
+ // guess at the credential would be worse than no answer.
+ await fs.writeFile(
+ file,
+ '[default_model]\nprovider = "custom"\nmodel_id = "m-bench"\n',
+ "utf8",
+ );
+ expect(await service.completeOnce("p1", "Name: Plugin Marketplace")).toEqual({
+ ok: false,
+ cause: "no_model",
+ error: "the default model custom/m-bench has no entry in the Project config",
+ });
+ });
+
+ it("collapses a construction that throws into a reason instead of an exception", async () => {
+ const root = await makeTempRoot();
+ const service = wire(ProjectConfigService, { paths: { root } });
+ await fs.mkdir(projectDir(root, "p1"), { recursive: true });
+ // An entry whose model id no client can be routed from, and no protocol pinned: the SDK
+ // throws while building the client, before any network I/O.
+ await fs.writeFile(
+ projectConfigPath(root, "p1"),
+ '[default_model]\nprovider = "custom"\nmodel_id = "not-a-routable-model-xyz"\n\n' +
+ '[[models]]\nprovider = "custom"\nmodel_id = "not-a-routable-model-xyz"\n',
+ "utf8",
+ );
+ const result = await service.completeOnce("p1", "Name: Plugin Marketplace");
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.cause).toBe("failed");
+ expect(result.error).toContain("not-a-routable-model-xyz");
+ }
+ });
+});
diff --git a/packages/web/e2e/company.spec.mjs b/packages/web/e2e/company.spec.mjs
new file mode 100644
index 00000000..994f7a96
--- /dev/null
+++ b/packages/web/e2e/company.spec.mjs
@@ -0,0 +1,263 @@
+/**
+ * Company mode, end to end through the browser with the mock LLM: switch modes, create the
+ * marketplace organization from the switcher, land on the CEO's desk conversation (its
+ * initialization run is answered by the mock), find the CEO on the org chart and a ticket on
+ * the board, open a desk from the sidebar's 工位 group and another from the org chart, then
+ * work in the channels — post in the all-hands channel and see the mention reach the CEO's
+ * desk as an `[org_trigger]` work run, create a channel, invite the CEO into it, and post a
+ * mention there — and finally check that development mode lists none of the organization's
+ * own sessions. The desk row's run mark is checked on both sides of the initialization run:
+ * it turns itself off when the run ends, which no server event announces.
+ *
+ * Company mode is off on a fresh server, so the spec turns the admin master switch on through
+ * /api/admin/settings before it signs in as the board member — without it there is no mode
+ * switch to click and every organization route answers 404.
+ */
+import { test, expect, request } from "@playwright/test";
+import { ADMIN_ID, ADMIN_PASSWORD, login, provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+// Unique per run: the organization and the persisted work mode belong to the user, so a rerun
+// against the same data root must start from a fresh one.
+const U = `boardmember_${Date.now().toString(36)}`;
+const P = "password123";
+const ORG = "marketplace";
+// "slow text test" makes the mock stream its answer for ~8 s, so the page can be checked
+// while the CEO's initialization run is still in flight.
+const MISSION =
+ "slow text test: 做一个 DeepSeek Harness 插件 Marketplace,通过社交媒体和 SEO 把搜索排名做到前三,靠首页限时置顶曝光位盈利。";
+
+/** The admin master switch, off by default: turned on server-wide before the flow starts. */
+async function enableCompanyMode() {
+ const adminCtx = await request.newContext();
+ try {
+ await login(adminCtx, ADMIN_ID, ADMIN_PASSWORD);
+ const res = await adminCtx.put(`${BASE}/api/admin/settings`, { data: { companyMode: true } });
+ if (!res.ok()) {
+ throw new Error(`enable company mode failed: ${res.status()} ${await res.text()}`);
+ }
+ } finally {
+ await adminCtx.dispose();
+ }
+}
+
+test("company mode: create the organization, meet the CEO, see the board and the chat work", async ({
+ page,
+}) => {
+ test.setTimeout(120_000);
+ await enableCompanyMode();
+ await provisionAndLogin(page.request, U, P);
+ const project = (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0];
+ const projectId = project.projectId;
+ const api = (path) => `${BASE}/api/projects/${projectId}${path}`;
+
+ // A model that talks to the mock, so the CEO's desk can actually run its initialization.
+ const put = await page.request.put(api("/models"), {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ },
+ ],
+ },
+ });
+ expect(put.ok(), "put models").toBeTruthy();
+
+ await page.goto("/");
+ await expect(page.getByText("General Agent").first()).toBeVisible();
+
+ // The mode switch sits above the Project switcher; company mode shows the organization switcher.
+ const modeSwitch = page.getByRole("group", { name: "工作模式" });
+ await expect(modeSwitch).toBeVisible();
+ // The option's accessible name carries the beta tag as a suffix ("公司 · 内测版").
+ await modeSwitch.getByRole("button", { name: /^公司/ }).click();
+ await expect(page).toHaveURL(/\/org/);
+ // With no organization yet, the landing page offers creation directly (the switcher does too).
+ await page.getByRole("button", { name: "新建组织", exact: true }).first().click();
+
+ // The modal is a headed card; its fields are named by their labels (hint text included).
+ await expect(page.getByRole("heading", { name: "新建组织" })).toBeVisible();
+ await page.getByRole("textbox", { name: /^组织 id/ }).fill(ORG);
+ await page.getByRole("textbox", { name: /^显示名/ }).fill("Plugin Marketplace");
+ await page.getByRole("textbox", { name: /^使命/ }).fill(MISSION);
+ // The CEO's budget is the whole company's, and the dialog offers the default it would send.
+ await expect(page.getByRole("spinbutton", { name: /^CEO 预算/ })).toHaveValue("100");
+ await page.getByRole("button", { name: "创建", exact: true }).click();
+
+ // Creation opens the CEO's desk conversation: an ordinary chat page that renders while the
+ // initialization run is still streaming (the trigger banner and the live state appear at
+ // once, not after the run ends).
+ await expect(page).toHaveURL(/\/chat\/session-/, { timeout: 30_000 });
+ await expect(page.getByText(/由组织「marketplace」触发/).first()).toBeVisible({ timeout: 3_000 });
+ const detail = await (await page.request.get(api(`/organizations/${ORG}`))).json();
+ expect(detail.employeeCount).toBe(1);
+ expect(detail.ceoDeskSessionId).toBeTruthy();
+ expect(page.url()).toContain(detail.ceoDeskSessionId);
+ const agents = (await (await page.request.get(api("/agents"))).json()).agents;
+ expect(agents.some((a) => a.agentId === `${ORG}_ceo`)).toBe(true);
+
+ // The initialization run reached the desk as an [org_trigger] input the mock answered.
+ await expect
+ .poll(
+ async () => {
+ const res = await page.request.get(
+ `${BASE}/api/sessions/${detail.ceoDeskSessionId}/messages`,
+ );
+ const text = await res.text();
+ return text.includes("[org_trigger]") && text.includes("kind: init");
+ },
+ { timeout: 30_000 },
+ )
+ .toBe(true);
+
+ // The org chart shows the CEO by its display name.
+ await page.goto(`/org/${projectId}/${ORG}/chart`);
+ await expect(page.getByText("Plugin Marketplace CEO").first()).toBeVisible();
+
+ // The sidebar lists the organization itself under its channels: a 工位 row per employee.
+ // Opening one renders the ordinary conversation view with the company sidebar around it,
+ // and the sidebar marks the desk that is open.
+ const sidebar = page.getByRole("complementary");
+ const ceoDeskRow = sidebar.getByRole("button", { name: /Plugin Marketplace CEO 的工位/ });
+ await expect(sidebar.getByRole("button", { name: /^工位(/ })).toBeVisible();
+ await ceoDeskRow.click();
+ await expect(page).toHaveURL(new RegExp(`/chat/${detail.ceoDeskSessionId}$`));
+ await expect(page.getByText(/由组织「marketplace」触发/).first()).toBeVisible();
+ await expect(sidebar.getByRole("link", { name: /^全员频道/ })).toBeVisible();
+ await expect(ceoDeskRow).toHaveAttribute("aria-current", "true");
+
+ // The desk row's run mark is live. Nothing on the wire says a run ENDED — the organization's
+ // session snapshot is re-read when a run is dispatched and when a ticket moves, and neither
+ // happens here — so the row takes its state from the session list's own status. Once the
+ // mock's answer has landed the row says nothing at all, and the composer is back to taking
+ // an ordinary message rather than steering a run in flight.
+ await expect(page.getByText("chunk-40").first()).toBeVisible({ timeout: 30_000 });
+ await expect(ceoDeskRow).toHaveAttribute("aria-label", "Plugin Marketplace CEO 的工位");
+ await expect(page.getByPlaceholder(/输入消息/)).toBeEnabled();
+
+ // A desk opened from the org chart renders too: the routed Session is not in the
+ // development list at all, so the page has to resolve it by id (the batch-3 regression).
+ const hired = await page.request.post(api(`/organizations/${ORG}/employees`), {
+ data: {
+ newAgent: { agentId: `${ORG}_dev`, name: "Dana Dev" },
+ title: "站点工程师",
+ reportsTo: `${ORG}_ceo`,
+ duties: "把站点从零搭到上线",
+ },
+ });
+ expect(hired.ok(), "hire").toBeTruthy();
+ await page.goto(`/org/${projectId}/${ORG}/chart`);
+ // The card's face is inert; its kebab menu is the way into the desk session.
+ await page.getByRole("button", { name: "Dana Dev · 员工操作" }).click();
+ await page.getByRole("button", { name: "打开工位会话" }).click();
+ await expect(page).toHaveURL(/\/chat\/session-/);
+ await expect(page.getByText("Dana Dev 的工位").first()).toBeVisible();
+ await expect(sidebar.getByRole("button", { name: /Dana Dev 的工位/ })).toHaveAttribute(
+ "aria-current",
+ "true",
+ );
+
+ // A ticket filed against the CEO shows on the board in the proposed column.
+ const created = await page.request.post(api(`/organizations/${ORG}/tickets`), {
+ data: {
+ title: "Build the marketplace site",
+ goal: "A site that lists DeepSeek Harness plugins with search and a featured row.",
+ owner: `agent:${ORG}_ceo`,
+ priority: "P1",
+ },
+ });
+ expect(created.ok(), "create ticket").toBeTruthy();
+ const ticket = await created.json();
+ expect(ticket.status).toBe("proposed");
+ await page.goto(`/org/${projectId}/${ORG}/tickets`);
+ await expect(page.getByText("Build the marketplace site").first()).toBeVisible();
+
+ // An organization opens on its overview; its channels are the sidebar's own list, where
+ // development mode lists conversations, with the all-hands channel pinned at its top.
+ await page.goto(`/org/${projectId}/${ORG}`);
+ await expect(page).toHaveURL(/\/overview$/);
+ await page
+ .getByRole("link", { name: /^全员频道/ })
+ .first()
+ .click();
+ await expect(page).toHaveURL(/channels\/default_channel/);
+ await expect(page.getByRole("heading", { name: /全员频道/ })).toBeVisible();
+
+ // A mention typed in the all-hands channel lands on the CEO's desk as a mention work run.
+ const input = page.getByRole("textbox", { name: /输入消息/ });
+ await expect(input).toBeVisible();
+ await input.fill(`@${ORG}_ceo 先把站点搭起来,验收标准写在工单里。`);
+ await input.press("Enter");
+ await expect(page.getByText("先把站点搭起来").first()).toBeVisible();
+ await expect
+ .poll(
+ async () => {
+ const res = await page.request.get(
+ `${BASE}/api/sessions/${detail.ceoDeskSessionId}/messages`,
+ );
+ return (await res.text()).includes("kind: mention");
+ },
+ { timeout: 30_000 },
+ )
+ .toBe(true);
+
+ // A new channel: created from the channel list header's own "+", the dialog validates the
+ // id here, the sidebar gains a row, and the view opens on it.
+ await page.getByRole("button", { name: "新建频道", exact: true }).first().click();
+ await expect(page.getByRole("heading", { name: "新建频道" })).toBeVisible();
+ await page.getByRole("textbox", { name: /^频道 id/ }).fill("site");
+ await page.getByRole("textbox", { name: /^显示名/ }).fill("Site launch");
+ await page.getByRole("textbox", { name: /^主题/ }).fill("站点从零到上线的一切");
+ await page.getByRole("button", { name: "创建", exact: true }).click();
+ await expect(page).toHaveURL(/channels\/site/);
+ await expect(page.getByRole("heading", { name: /Site launch/ })).toBeVisible();
+ await expect(page.getByRole("link", { name: /^Site launch/ })).toBeVisible();
+
+ // Inviting the CEO: only then does an @ in this channel reach it (the server refuses a
+ // mention that leaves the channel's membership).
+ await page.getByRole("button", { name: "邀请", exact: true }).click();
+ // Scoped to the picker: the sidebar's 工位 group carries the CEO's name too.
+ const invite = page.getByRole("dialog", { name: "邀请到频道" });
+ await invite.getByRole("textbox", { name: "搜索员工或成员" }).fill("ceo");
+ await invite.getByRole("button", { name: /Plugin Marketplace CEO/ }).click();
+ await expect(page.getByText("已邀请").first()).toBeVisible();
+
+ // …and the mention posts, appears in this channel's stream, and reaches the desk.
+ const siteInput = page.getByRole("textbox", { name: /输入消息/ });
+ await siteInput.fill(`@${ORG}_ceo 站点频道成立,先出一版信息架构。`);
+ await siteInput.press("Enter");
+ await expect(page.getByText("站点频道成立").first()).toBeVisible();
+ const siteDay = await (
+ await page.request.get(api(`/organizations/${ORG}/channels/site/messages`))
+ ).json();
+ expect(siteDay.messages.some((m) => m.text.includes("站点频道成立"))).toBe(true);
+ expect(siteDay.messages.some((m) => m.mentions.includes(`agent:${ORG}_ceo`))).toBe(true);
+
+ // The overview reflects it all: one employee, one proposed ticket, the mission on screen.
+ await page.goto(`/org/${projectId}/${ORG}/overview`);
+ await expect(page.getByText("Plugin Marketplace").first()).toBeVisible();
+
+ // Switching back to development mode from an organization page takes effect at once: the
+ // development sidebar (with its new-chat entry) replaces the company one.
+ await page
+ .getByRole("group", { name: "工作模式" })
+ .getByRole("button", { name: "开发", exact: true })
+ .click();
+ await expect(page.getByRole("button", { name: "新建对话" }).first()).toBeVisible({
+ timeout: 5_000,
+ });
+ await expect(page).not.toHaveURL(/\/org\//);
+ // …and it lists the user's own conversations only: the organization's desks are the
+ // company sidebar's rows, and the old 「组织」 folder is gone with them.
+ await expect(sidebar.getByText("Dana Dev 的工位")).toHaveCount(0);
+ await expect(sidebar.getByRole("button", { name: /^组织(/ })).toHaveCount(0);
+ const overview = await (await page.request.get(api(`/organizations/${ORG}`))).json();
+ expect(overview.board.proposed).toBe(1);
+ expect(overview.openTickets).toBe(1);
+});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 0da79cec..af34bc76 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -13,16 +13,16 @@ import type {
AgentConfigUpdateRequest,
AgentCreateRequest,
AgentCreateResponse,
+ AgentHooksResponse,
AgentImportRequest,
AgentImportResponse,
AgentKernelUpdateResponse,
+ AgentPluginsInstallResponse,
AgentSchedulesConfigDto,
AgentSkillsConfigDto,
- AgentHooksResponse,
- AgentPluginsInstallResponse,
AgentSkillsResponse,
- AgentVaultConfigDto,
AgentsResponse,
+ AgentVaultConfigDto,
ApprovalDecisionRequest,
AuthLoginRequest,
AuthResponse,
@@ -36,6 +36,7 @@ import type {
CommandPolicyRuleDto,
DefaultModelResponse,
DefaultModelUpdateRequest,
+ DesktopUpdateStatusResponse,
DirectorySkillsResponse,
DirListResponse,
EndpointModelListRequest,
@@ -50,8 +51,8 @@ import type {
FilesWriteRequest,
GoalResponse,
InstallResponse,
+ MachinesResponse,
McpServerTestResponse,
- MeResponse,
MemberAddRequest,
MemberAddResponse,
MembersResponse,
@@ -61,6 +62,7 @@ import type {
MemoryImportResponse,
MemoryOverviewResponse,
MemoryScopeExport,
+ MeResponse,
MessagesResponse,
MessagingBindingsResponse,
MessagingChannel,
@@ -71,23 +73,74 @@ import type {
ModelOAuthStatusResponse,
ModelProtocolDetectRequest,
ModelProtocolDetectResponse,
- MachinesResponse,
ModelsResponse,
ModelsUpdateRequest,
ModelTestRequest,
ModelTestResponse,
ModelVisionDetectRequest,
ModelVisionDetectResponse,
+ OrganizationCreateRequest,
+ OrganizationDetail,
+ OrganizationPatchRequest,
+ OrganizationSettings,
+ OrganizationsResponse,
+ OrgCalendarResponse,
+ OrgCalendarUpsertRequest,
+ OrgCalendarWriteResponse,
+ OrgChannelCreateRequest,
+ OrgChannelDetail,
+ OrgChannelItem,
+ OrgChannelMemberRequest,
+ OrgChannelMessage,
+ OrgChannelMessageSendRequest,
+ OrgChannelMessagesResponse,
+ OrgChannelPatchRequest,
+ OrgChannelReadRequest,
+ OrgChannelsResponse,
+ OrgChartResponse,
+ OrgDeskResponse,
+ OrgEmployeeItem,
+ OrgEmployeePatchRequest,
+ OrgFinanceResponse,
+ OrgHandbookFileResponse,
+ OrgHandbookFilesResponse,
+ OrgHandbookResponse,
+ OrgHireRequest,
+ OrgSessionsResponse,
+ OrgTicketAttachRequest,
+ OrgTicketBlockRequest,
+ OrgTicketCreateRequest,
+ OrgTicketDetail,
+ OrgTicketMoveRequest,
+ OrgTicketProgressRequest,
+ OrgTicketsResponse,
+ OrgTicketStartRequest,
+ OrgTicketStartResponse,
+ OrgTicketUpdateRequest,
PasswordChangeRequest,
+ PluginFilesResponse,
+ PluginInstallRequest,
+ PluginLibraryResponse,
PrefsResponse,
ProjectCreateRequest,
ProjectCreateResponse,
+ ProjectsResponse,
ProjectUpdateRequest,
ProjectUpdateResponse,
- ProjectsResponse,
+ QQBindingPutRequest,
+ QQBindingResponse,
+ QQScanPollResponse,
+ QQScanStartResponse,
+ QQTestRequest,
+ QQTestResponse,
+ RecalledMessageResponse,
+ RestartResponse,
+ RetryNowResponse,
ScheduleItem,
SchedulesResponse,
ScheduleUpsertRequest,
+ SemanticIdSuggestRequest,
+ SemanticIdSuggestResponse,
ProxyProbeProvider,
ProxyProbeResponse,
ProxyProbeTargetsResponse,
@@ -100,27 +153,11 @@ import type {
SessionForkRequest,
SessionForkResponse,
SessionPatchRequest,
- SessionResponse,
SessionProcessesResponse,
+ SessionResponse,
SessionsResponse,
SessionTracesResponse,
SkillArchiveInstallRequest,
- PluginFilesResponse,
- PluginInstallRequest,
- PluginLibraryResponse,
- QQBindingPutRequest,
- QQBindingResponse,
- QQScanPollResponse,
- QQScanStartResponse,
- QQTestRequest,
- QQTestResponse,
- WeChatBindingPutRequest,
- WeChatBindingResponse,
- WeChatScanPollResponse,
- WeChatScanStartResponse,
- WeChatTestResponse,
- RecalledMessageResponse,
- RetryNowResponse,
SteerRequest,
SubagentMessageResponse,
TaskCreateRequest,
@@ -138,10 +175,8 @@ import type {
UpdateJobStatus,
UpdateProfileRequest,
UpdateProfileResponse,
- RestartResponse,
DesktopTrayPatch,
DesktopTrayStatusResponse,
- DesktopUpdateStatusResponse,
HookArchiveInstallRequest,
UsageErrorKind,
UsageErrorsClearResponse,
@@ -153,6 +188,11 @@ import type {
VaultResponse,
VaultUpdateRequest,
VersionResponse,
+ WeChatBindingPutRequest,
+ WeChatBindingResponse,
+ WeChatScanPollResponse,
+ WeChatScanStartResponse,
+ WeChatTestResponse,
WorkspaceFilesResponse,
WorkspaceSearchResponse,
ContributionsResponse,
@@ -1352,6 +1392,290 @@ export const desktopUpdateDownload = () =>
export const desktopUpdateInstall = () =>
apiFetch<void>("/api/desktop/update/install", { method: "POST", body: {} });
+// ---------------------------------------------------------------------------
+// Company mode: organizations (one wrapper per route of routes/organizations.ts)
+// ---------------------------------------------------------------------------
+
+/** Base path of one Project's organizations, or of one organization when `orgId` is given. */
+const orgBase = (projectId: string, orgId?: string) =>
+ `/api/projects/${encodeURIComponent(projectId)}/organizations${
+ orgId === undefined ? "" : `/${encodeURIComponent(orgId)}`
+ }`;
+
+export const listOrganizations = (projectId: string) =>
+ apiFetch<OrganizationsResponse>(orgBase(projectId));
+
+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. */
+export const suggestSemanticId = (projectId: string, body: SemanticIdSuggestRequest) =>
+ apiFetch<SemanticIdSuggestResponse>(`${orgBase(projectId)}/suggest-id`, { method: "POST", body });
+
+export const getOrganization = (projectId: string, orgId: string) =>
+ apiFetch<OrganizationDetail>(orgBase(projectId, orgId));
+
+export const patchOrganization = (
+ projectId: string,
+ orgId: string,
+ body: OrganizationPatchRequest,
+) => apiFetch<OrganizationSettings>(orgBase(projectId, orgId), { method: "PATCH", body });
+
+export const getOrgChart = (projectId: string, orgId: string) =>
+ apiFetch<OrgChartResponse>(`${orgBase(projectId, orgId)}/chart`);
+
+export const hireOrgEmployee = (projectId: string, orgId: string, body: OrgHireRequest) =>
+ apiFetch<OrgEmployeeItem>(`${orgBase(projectId, orgId)}/employees`, { method: "POST", body });
+
+export const patchOrgEmployee = (
+ projectId: string,
+ orgId: string,
+ agentId: string,
+ body: OrgEmployeePatchRequest,
+) =>
+ apiFetch<OrgEmployeeItem>(
+ `${orgBase(projectId, orgId)}/employees/${encodeURIComponent(agentId)}`,
+ { method: "PATCH", body },
+ );
+
+export const leaveOrganization = (projectId: string, orgId: string, agentId: string) =>
+ apiFetch<void>(`${orgBase(projectId, orgId)}/employees/${encodeURIComponent(agentId)}`, {
+ method: "DELETE",
+ });
+
+/** The employee's desk session, opened on demand (GET creates it when there is none). */
+export const getOrgDesk = (projectId: string, orgId: string, agentId: string) =>
+ apiFetch<OrgDeskResponse>(
+ `${orgBase(projectId, orgId)}/employees/${encodeURIComponent(agentId)}/desk`,
+ );
+
+/** A fresh desk session for the employee (the old one stays as an ordinary Session). */
+export const renewOrgDesk = (projectId: string, orgId: string, agentId: string) =>
+ apiFetch<OrgDeskResponse>(
+ `${orgBase(projectId, orgId)}/employees/${encodeURIComponent(agentId)}/desk`,
+ { method: "POST", body: {} },
+ );
+
+export const getOrgHandbook = (projectId: string, orgId: string) =>
+ apiFetch<OrgHandbookResponse>(`${orgBase(projectId, orgId)}/handbook`);
+
+export const putOrgHandbook = (projectId: string, orgId: string, content: string) =>
+ apiFetch<OrgHandbookResponse>(`${orgBase(projectId, orgId)}/handbook`, {
+ method: "PUT",
+ body: { content },
+ });
+
+/** A handbook file's URL: the path is relative to `handbook/`, so each segment is encoded and the `/` between them kept. */
+const handbookFileUrl = (projectId: string, orgId: string, path: string) =>
+ `${orgBase(projectId, orgId)}/handbook/files/${path.split("/").map(encodeURIComponent).join("/")}`;
+
+export const listOrgHandbookFiles = (projectId: string, orgId: string) =>
+ apiFetch<OrgHandbookFilesResponse>(`${orgBase(projectId, orgId)}/handbook/files`);
+
+export const getOrgHandbookFile = (projectId: string, orgId: string, path: string) =>
+ apiFetch<OrgHandbookFileResponse>(handbookFileUrl(projectId, orgId, path));
+
+export const putOrgHandbookFile = (
+ projectId: string,
+ orgId: string,
+ path: string,
+ content: string,
+) =>
+ apiFetch<OrgHandbookFileResponse>(handbookFileUrl(projectId, orgId, path), {
+ method: "PUT",
+ body: { content },
+ });
+
+export const deleteOrgHandbookFile = (projectId: string, orgId: string, path: string) =>
+ apiFetch<void>(handbookFileUrl(projectId, orgId, path), { method: "DELETE" });
+
+export const listOrgCalendar = (projectId: string, orgId: string) =>
+ apiFetch<OrgCalendarResponse>(`${orgBase(projectId, orgId)}/calendar`);
+
+export const createOrgCalendarEvent = (
+ projectId: string,
+ orgId: string,
+ body: OrgCalendarUpsertRequest & { agentId: string; name: string },
+) =>
+ apiFetch<OrgCalendarWriteResponse>(`${orgBase(projectId, orgId)}/calendar`, {
+ method: "POST",
+ body,
+ });
+
+export const updateOrgCalendarEvent = (
+ projectId: string,
+ orgId: string,
+ agentId: string,
+ name: string,
+ body: OrgCalendarUpsertRequest,
+) =>
+ apiFetch<OrgCalendarWriteResponse>(
+ `${orgBase(projectId, orgId)}/calendar/${encodeURIComponent(agentId)}/${encodeURIComponent(name)}`,
+ { method: "PUT", body },
+ );
+
+export const deleteOrgCalendarEvent = (
+ projectId: string,
+ orgId: string,
+ agentId: string,
+ name: string,
+) =>
+ apiFetch<void>(
+ `${orgBase(projectId, orgId)}/calendar/${encodeURIComponent(agentId)}/${encodeURIComponent(name)}`,
+ { method: "DELETE" },
+ );
+
+export const listOrgTickets = (projectId: string, orgId: string) =>
+ apiFetch<OrgTicketsResponse>(`${orgBase(projectId, orgId)}/tickets`);
+
+export const getOrgTicket = (projectId: string, orgId: string, ticketId: string) =>
+ apiFetch<OrgTicketDetail>(`${orgBase(projectId, orgId)}/tickets/${encodeURIComponent(ticketId)}`);
+
+export const createOrgTicket = (projectId: string, orgId: string, body: OrgTicketCreateRequest) =>
+ apiFetch<OrgTicketDetail>(`${orgBase(projectId, orgId)}/tickets`, { method: "POST", body });
+
+export const updateOrgTicket = (
+ projectId: string,
+ orgId: string,
+ ticketId: string,
+ body: OrgTicketUpdateRequest,
+) =>
+ apiFetch<OrgTicketDetail>(
+ `${orgBase(projectId, orgId)}/tickets/${encodeURIComponent(ticketId)}`,
+ { method: "PUT", body },
+ );
+
+/** `…/tickets/:ticketId/<action>` POST helper shared by the six ticket actions. */
+const ticketAction = <T>(
+ projectId: string,
+ orgId: string,
+ ticketId: string,
+ action: string,
+ body: unknown,
+) =>
+ apiFetch<T>(`${orgBase(projectId, orgId)}/tickets/${encodeURIComponent(ticketId)}/${action}`, {
+ method: "POST",
+ body,
+ });
+
+export const moveOrgTicket = (
+ projectId: string,
+ orgId: string,
+ ticketId: string,
+ body: OrgTicketMoveRequest,
+) => ticketAction<OrgTicketDetail>(projectId, orgId, ticketId, "move", body);
+
+export const blockOrgTicket = (
+ projectId: string,
+ orgId: string,
+ ticketId: string,
+ body: OrgTicketBlockRequest,
+) => ticketAction<OrgTicketDetail>(projectId, orgId, ticketId, "block", body);
+
+export const unblockOrgTicket = (projectId: string, orgId: string, ticketId: string) =>
+ ticketAction<OrgTicketDetail>(projectId, orgId, ticketId, "unblock", {});
+
+export const progressOrgTicket = (
+ projectId: string,
+ orgId: string,
+ ticketId: string,
+ body: OrgTicketProgressRequest,
+) => ticketAction<OrgTicketDetail>(projectId, orgId, ticketId, "progress", body);
+
+export const startOrgTicket = (
+ projectId: string,
+ orgId: string,
+ ticketId: string,
+ body: OrgTicketStartRequest = {},
+) => ticketAction<OrgTicketStartResponse>(projectId, orgId, ticketId, "start", body);
+
+export const attachOrgTicket = (
+ projectId: string,
+ orgId: string,
+ ticketId: string,
+ body: OrgTicketAttachRequest,
+) => ticketAction<OrgTicketDetail>(projectId, orgId, ticketId, "attach", body);
+
+const channelBase = (projectId: string, orgId: string, channelId: string) =>
+ `${orgBase(projectId, orgId)}/channels/${encodeURIComponent(channelId)}`;
+
+/** The organization's channels: the all-hands one first, then by name. */
+export const listOrgChannels = (projectId: string, orgId: string) =>
+ apiFetch<OrgChannelsResponse>(`${orgBase(projectId, orgId)}/channels`);
+
+export const createOrgChannel = (projectId: string, orgId: string, body: OrgChannelCreateRequest) =>
+ apiFetch<OrgChannelItem>(`${orgBase(projectId, orgId)}/channels`, { method: "POST", body });
+
+export const getOrgChannel = (projectId: string, orgId: string, channelId: string) =>
+ apiFetch<OrgChannelDetail>(channelBase(projectId, orgId, channelId));
+
+export const patchOrgChannel = (
+ projectId: string,
+ orgId: string,
+ channelId: string,
+ body: OrgChannelPatchRequest,
+) => apiFetch<OrgChannelItem>(channelBase(projectId, orgId, channelId), { method: "PATCH", body });
+
+export const addOrgChannelMember = (
+ projectId: string,
+ orgId: string,
+ channelId: string,
+ body: OrgChannelMemberRequest,
+) =>
+ apiFetch<OrgChannelDetail>(`${channelBase(projectId, orgId, channelId)}/members`, {
+ method: "POST",
+ body,
+ });
+
+/** Removes a member; `principal` is the literal `agent:<id>` / `user:<id>`, encoded into the path. */
+export const removeOrgChannelMember = (
+ projectId: string,
+ orgId: string,
+ channelId: string,
+ principal: string,
+) =>
+ apiFetch<void>(
+ `${channelBase(projectId, orgId, channelId)}/members/${encodeURIComponent(principal)}`,
+ { method: "DELETE" },
+ );
+
+/** One day of a channel (today in the organization's timezone when `date` is omitted). */
+export const getOrgChannelMessages = (
+ projectId: string,
+ orgId: string,
+ channelId: string,
+ date?: string,
+) =>
+ apiFetch<OrgChannelMessagesResponse>(`${channelBase(projectId, orgId, channelId)}/messages`, {
+ query: { date },
+ });
+
+export const sendOrgChannelMessage = (
+ projectId: string,
+ orgId: string,
+ channelId: string,
+ body: OrgChannelMessageSendRequest,
+) =>
+ apiFetch<OrgChannelMessage>(`${channelBase(projectId, orgId, channelId)}/messages`, {
+ method: "POST",
+ body,
+ });
+
+export const readOrgChannel = (
+ projectId: string,
+ orgId: string,
+ channelId: string,
+ body: OrgChannelReadRequest,
+) => apiFetch<void>(`${channelBase(projectId, orgId, channelId)}/read`, { method: "POST", body });
+
+/** Budget and spend for one `yyyy-mm` period (the current one when omitted). */
+export const getOrgFinance = (projectId: string, orgId: string, period?: string) =>
+ apiFetch<OrgFinanceResponse>(`${orgBase(projectId, orgId)}/finance`, {
+ query: { period },
+ });
+
+export const getOrgSessions = (projectId: string, orgId: string) =>
+ apiFetch<OrgSessionsResponse>(`${orgBase(projectId, orgId)}/sessions`);
// Desktop tray icon (desktop-shell sessions only) --------------------------------------
/** What the shell last pushed; `status` is null until that first push, which reads as on. */
diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsx
index ebfd9f4a..53105683 100644
--- a/packages/web/src/components/layout/app-layout.tsx
+++ b/packages/web/src/components/layout/app-layout.tsx
@@ -5,10 +5,10 @@
* All chrome uses solid backgrounds and avoids stacking contexts (frosted-glass/transform would trap overlay z-index).
*/
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
-import { NavLink, Outlet, useMatch, useNavigate } from "react-router";
+import { NavLink, Outlet, useLocation, useMatch, useNavigate } from "react-router";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
-import { latestConversation } from "../../lib/session-grouping";
+import { latestConversation, withoutOrgSessions } from "../../lib/session-grouping";
import { navNoteFor, useUpdateBadges } from "../../lib/use-update-badges";
import { useAuth } from "../../state/auth";
import { useProject } from "../../state/project";
@@ -20,7 +20,17 @@ import { GlyphIcon } from "../ui/glyph-icon";
import { Tooltip } from "../ui/tooltip";
import { UpdateDot } from "../ui/update-dot";
import { UserAvatar } from "../ui/user-avatar";
-import { CloseIcon, NAV_ICONS } from "../ui/icons";
+import { COMPANY_MODE_ICON, CloseIcon, NAV_ICONS } from "../ui/icons";
+import { useCompany } from "../../state/company";
+import { COMPANY_NAV_ICONS } from "../../features/company/company-nav-icons";
+import { ChannelRailRows } from "../../features/company/channel-sidebar";
+import { DeskRailRows } from "../../features/company/org-session-groups";
+import {
+ COMPANY_NAV_KEYS,
+ isOrgRoute,
+ orgPagePath,
+ parseOrgKey,
+} from "../../features/company/company-nav";
import { NEW_CHAT_ICON, Sidebar } from "./sidebar";
import { UserMenu } from "./user-menu";
import { DRAFT_SESSION_ID } from "../../features/chat/chat-page";
@@ -69,12 +79,27 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {
* every other badge here rides on a page entry, which is where its trail continues.
*/
const badges = useUpdateBadges();
+ const company = useCompany();
+ const location = useLocation();
+ /** Company mode: the organization's pages replace the development ones, and its channels follow them as rows. */
+ const inCompany = company.workMode === "company";
+ const navOrg = parseOrgKey(company.currentOrgKey ?? company.lastOrgKey);
+ /** Same two moves as the pinned sidebar's switch: company mode enters at /org; development mode only leaves an organization page. */
+ const toggleMode = () => {
+ const next = inCompany ? "dev" : "company";
+ company.setWorkMode(next);
+ if (next === "company") navigate("/org");
+ else if (isOrgRoute(location.pathname)) navigate("/chat");
+ };
+ const companyToggleLabel = inCompany
+ ? S.company.switchToDev
+ : `${S.company.switchToCompany} · ${S.company.beta}`;
const activeSessionId = useMatch("/chat/:sessionId")?.params.sessionId ?? null;
/** On some conversation (any non-draft /chat/:id): the "you are here" state of the last-conversation entry. */
const onConversation = activeSessionId !== null && activeSessionId !== DRAFT_SESSION_ID;
- /** The most recently active loaded conversation across the current Project (active/schedule only — archived and subagent rows are never auto-opened; the flat list is only ordered per Agent). */
- const lastSession = useMemo(() => latestConversation(sessions), [sessions]);
+ /** Newest loaded conversation across the current Project (active/schedule only — archived and subagent rows are never auto-opened; the flat list is only ordered per Agent). An organization's desk and ticket Sessions are never conversations of this list. */
+ const lastSession = useMemo(() => latestConversation(withoutOrgSessions(sessions)), [sessions]);
/** Mirrors Sidebar.openSession: the current Agent follows the opened Session's Agent. */
const openLastSession = () => {
@@ -94,13 +119,30 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {
/** Page entries (rail positions 3-7): same routes, same labels as the pinned nav.
Traces is not among them: reading a Trace happens in the chat toolbar's panel
switcher, which is the only place it happens. */
- const pages: ReadonlyArray<{ to: string; label: string; icon: string }> = [
- { to: "/agents", label: S.nav.agents, icon: NAV_ICONS.agents },
- { to: "/plugins", label: S.nav.plugins, icon: NAV_ICONS.plugins },
- { to: "/models", label: S.nav.models, icon: NAV_ICONS.models },
- { to: "/usage", label: S.nav.usage, icon: NAV_ICONS.usage },
- { to: "/benchmark", label: S.nav.benchmark, icon: NAV_ICONS.benchmark },
- ];
+ const pages: ReadonlyArray<{
+ key: string;
+ /** Where the entry leads — null while company mode has no organization, which renders it disabled. */
+ to: string | null;
+ label: string;
+ icon: string;
+ note: string | null;
+ }> = inCompany
+ ? COMPANY_NAV_KEYS.map((key) => ({
+ key,
+ // The six entries keep their places with no organization, disabled: a rail that
+ // empties itself reads as a broken shell rather than as an empty one.
+ to: navOrg === null ? null : orgPagePath(navOrg.projectId, navOrg.orgId, key),
+ label: S.nav.org[key],
+ icon: COMPANY_NAV_ICONS[key],
+ note: null,
+ }))
+ : [
+ { to: "/agents", label: S.nav.agents, icon: NAV_ICONS.agents },
+ { to: "/plugins", label: S.nav.plugins, icon: NAV_ICONS.plugins },
+ { to: "/models", label: S.nav.models, icon: NAV_ICONS.models },
+ { to: "/usage", label: S.nav.usage, icon: NAV_ICONS.usage },
+ { to: "/benchmark", label: S.nav.benchmark, icon: NAV_ICONS.benchmark },
+ ].map((item) => ({ ...item, key: item.to, note: navNoteFor(badges, item.to) }));
/**
* The rail's avatar hangs its menu off the rail's OUTER edge rather than over the rail:
@@ -153,6 +195,25 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {
<GlyphIcon d="M9 6l6 6-6 6M20 4v16" size={18} />
</button>
</Tooltip>
+ {/* The work-mode toggle, the rail's compact form of the sidebar's 开发 | 公司 switch:
+ one building glyph, pressed while in company mode, the tooltip naming the move a
+ click makes. Same availability rule as the switch. The move INTO company mode says
+ the mode is a beta — the rail has no room for the pill the expanded sidebar carries,
+ and the suffix belongs on the label that offers the mode, not on the one that leaves
+ it. */}
+ {company.available && (
+ <Tooltip label={companyToggleLabel} className="shrink-0">
+ <button
+ type="button"
+ aria-label={companyToggleLabel}
+ aria-pressed={inCompany}
+ onClick={toggleMode}
+ className={railItemClass(inCompany)}
+ >
+ <GlyphIcon d={COMPANY_MODE_ICON} size={18} />
+ </button>
+ </Tooltip>
+ )}
{/* The entries scroll as one block, like the pinned sidebar's nav + session list: the rail
keeps only the expand control and the account avatar at fixed height, so a window too
short for the icons scrolls them here instead of pushing them out of the rail and
@@ -179,27 +240,47 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {
<GlyphIcon d={HISTORY_ICON} size={18} />
</button>
</Tooltip>
- {/* 2. New chat: shows the same gray active fill while on the draft page (pinned-sidebar convention). */}
- <Tooltip label={S.chat.newSessionMenu}>
- <button
- type="button"
- aria-label={S.chat.newSessionMenu}
- onClick={newChat}
- className={railItemClass(activeSessionId === DRAFT_SESSION_ID)}
- >
- <GlyphIcon d={NEW_CHAT_ICON} size={18} />
- </button>
- </Tooltip>
+ {/* 2. New chat: shows the same gray active fill while on the draft page (pinned-sidebar
+ convention). Company mode leaves this slot empty — a channel is made rarely, from
+ the channel list's own header, and the rail carries no create control of its own. */}
+ {!inCompany && (
+ <Tooltip label={S.chat.newSessionMenu}>
+ <button
+ type="button"
+ aria-label={S.chat.newSessionMenu}
+ onClick={newChat}
+ className={railItemClass(activeSessionId === DRAFT_SESSION_ID)}
+ >
+ <GlyphIcon d={NEW_CHAT_ICON} size={18} />
+ </button>
+ </Tooltip>
+ )}
{/* 3-8. Page entries */}
{pages.map((item) => {
/* Four entries sit on a badge trail — Agents (an outdated kernel), Skills, Models and
the Cost Center. The dot itself is decorative: the tooltip and the accessible name
say what is waiting, and this rail's icons have no visible label, so they carry
both the entry's name and that sentence. */
- const note = navNoteFor(badges, item.to);
+ const note = item.note;
const label = note !== null ? `${item.label} · ${note}` : item.label;
+ if (item.to === null) {
+ /* Nowhere to go: the icon keeps its place, muted, with no hover fill and nothing
+ to click or tab to. The name still stands, so the row is readable. */
+ return (
+ <Tooltip key={item.key} label={label}>
+ <span
+ role="link"
+ aria-label={label}
+ aria-disabled="true"
+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-gray-300 dark:text-gray-700"
+ >
+ <GlyphIcon d={item.icon} size={18} />
+ </span>
+ </Tooltip>
+ );
+ }
return (
- <Tooltip key={item.to} label={label}>
+ <Tooltip key={item.key} label={label}>
<NavLink
to={item.to}
aria-label={label}
@@ -211,6 +292,18 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {
</Tooltip>
);
})}
+ {/* The organization's channels and then its desks, under the pages the way they sit
+ under the nav in the pinned sidebar. A hairline says where each run ends; a channel
+ row carries its own unread count and a desk its running dot, since a rail with no
+ labels must still say how much is waiting. */}
+ {inCompany && navOrg !== null && (
+ <>
+ <span aria-hidden className="my-0.5 h-px w-5 shrink-0 bg-gray-200 dark:bg-gray-800" />
+ <ChannelRailRows projectId={navOrg.projectId} orgId={navOrg.orgId} />
+ <span aria-hidden className="my-0.5 h-px w-5 shrink-0 bg-gray-200 dark:bg-gray-800" />
+ <DeskRailRows projectId={navOrg.projectId} orgId={navOrg.orgId} />
+ </>
+ )}
</nav>
{/* The account menu opens here, on the rail, instead of the avatar expanding the sidebar
first: appearance and System settings, the update row and signing out all stay one
@@ -280,6 +373,11 @@ export function AppLayout() {
// browser session, so a dot can be there on a fresh load instead of waiting for someone to
// open the sidebar menu. Every other anchor reads the same caches passively.
const badges = useUpdateBadges(true);
+ // The drawer holds the sidebar, so the hamburger is named after what the sidebar lists:
+ // conversations in development mode, channels in company mode.
+ const company = useCompany();
+ const drawerName =
+ company.workMode === "company" ? S.company.channels.drawerLabel : S.chat.sessionList;
const [drawerOpen, setDrawerOpen] = useState(false);
const [changePasswordOpen, setChangePasswordOpen] = useState(false);
// Initial-password banner dismissal: server-persisted per user (ui_prefs). null = prefs not
@@ -358,9 +456,7 @@ export function AppLayout() {
row's update entry). */}
<button
type="button"
- aria-label={
- badges.note !== null ? `${S.chat.sessionList} · ${badges.note}` : S.chat.sessionList
- }
+ aria-label={badges.note !== null ? `${drawerName} · ${badges.note}` : drawerName}
{...(badges.note !== null ? { title: badges.note } : {})}
onClick={() => setDrawerOpen(true)}
className="relative flex h-9 w-9 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index 61fc5b6e..39439d26 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -21,6 +21,13 @@
* icon buttons on hover/focus; the full set (pin, rename, archive, delete) opens as a
* context menu on right-click, Shift+F10, or a press-and-hold on touch
* -> bottom user row, which opens the shared account menu (user-menu.tsx).
+ * In company mode the shape holds but the objects change: the organization switcher stands
+ * where the Project switcher stands, "New channel" where "New chat" is, the organization's
+ * six pages in the nav group, and the channel list where the conversation list is, followed
+ * by the organization's own 工位 group — one row per employee
+ * (features/company/channel-sidebar.tsx, features/company/org-session-groups.tsx). The
+ * development list is the user's OWN conversations only: an organization's desk and ticket
+ * Sessions are filtered out of every group, bucket and folder here.
* Desktop keeps it pinned as the left column; mobile puts the whole thing in a drawer.
* New chats always enter draft state (/chat/new, route state specifies the Agent and optionally
* the Workspace): Model / Workspace / approval mode are all chosen on the draft input card, so
@@ -29,7 +36,7 @@
*/
import { useEffect, useMemo, useRef, useState } from "react";
import type { DragEvent as ReactDragEvent, ReactNode } from "react";
-import { NavLink, useMatch, useNavigate } from "react-router";
+import { NavLink, useLocation, useMatch, useNavigate } from "react-router";
import type {
SessionCategory,
SessionCategoryCounts,
@@ -53,6 +60,7 @@ import {
aggregateWorkspaceCounts,
aggregateWorkspaceLatest,
clampGroupPage,
+ countsWithoutOrgSessions,
completeWorkspaceGroups,
foldedShare,
groupPageCount,
@@ -65,7 +73,9 @@ import {
partitionSessions,
revealPlan,
sessionCategory,
+ splitDevelopmentList,
totalCategoryCounts,
+ withoutOrgSessions,
workspaceGroupKey,
workspaceLabel,
} from "../../lib/session-grouping";
@@ -173,6 +183,20 @@ import { navNoteFor, useUpdateBadges } from "../../lib/use-update-badges";
import { pendingScheduleSessions } from "../../features/schedules/schedule-panel-state";
import { useAgentSchedules } from "../../features/schedules/schedule-store";
import { ICON_SIZE } from "../../lib/icon-scale";
+import { Segmented } from "../ui/segmented";
+import { useCompany } from "../../state/company";
+import { NoOrganizationsSidebar, OrgSwitcher } from "../../features/company/org-switcher";
+import { BetaBadge } from "../../features/company/beta-badge";
+import { ChannelSidebar } from "../../features/company/channel-sidebar";
+import { OrgSessionGroups } from "../../features/company/org-session-groups";
+import { COMPANY_NAV_ICONS } from "../../features/company/company-nav-icons";
+import {
+ COMPANY_NAV_KEYS,
+ isOrgRoute,
+ orgPagePath,
+ parseOrgKey,
+} from "../../features/company/company-nav";
+import type { WorkMode } from "../../features/company/company-nav";
import { toneInk } from "../../lib/tone";
/** New-chat pencil (the pinned "New chat" button and the collapsed rail share it). */
@@ -358,6 +382,7 @@ export function Sidebar({
onCollapse?: () => void;
}) {
const navigate = useNavigate();
+ const location = useLocation();
const { user, sessionVia } = useAuth();
const { locale } = useLocale();
const {
@@ -370,10 +395,10 @@ export function Sidebar({
setCurrentAgentId,
} = useProject();
const {
- sessions,
- byAgent,
- countsByAgent,
- workspaceCountsByAgent,
+ sessions: allSessions,
+ byAgent: allByAgent,
+ countsByAgent: serverCountsByAgent,
+ workspaceCountsByAgent: serverWorkspaceCounts,
workspaceLatestByAgent,
isLoadedFor,
hasMoreFor,
@@ -390,6 +415,38 @@ export function Sidebar({
const [projectSettingsOpen, setProjectSettingsOpen] = useState(false);
/** The badges over the update and to-do trails (use-update-badges.ts); the avatar's dot follows the update flow's offer / restart states. */
const badges = useUpdateBadges();
+ const company = useCompany();
+ /** Company mode swaps the Project switcher, the page nav and the session list for their organization forms. */
+ const inCompany = company.workMode === "company";
+ /** The organization the company nav points at: the open one, else the one last opened (the switcher names the same). */
+ const navOrg = parseOrgKey(company.currentOrgKey ?? company.lastOrgKey);
+
+ /**
+ * The rows this list renders: the user's OWN conversations. An organization's desk and
+ * ticket Sessions (marked by `orgId`, or by the durable `client === "org"` stamp once the
+ * organization is gone) are driven by its scheduler and are reached as themselves in company
+ * mode — a desk from the 工位 group, a ticket session from its ticket — so they are
+ * filtered out here — once, at the source, or a
+ * dropped row would still conjure the Workspace group, Agent group or time bucket it belongs
+ * to. They are filtered whatever the company-mode switches say (see withoutOrgSessions):
+ * this list is the user's conversations, and a switch about the shell does not turn a
+ * scheduler's Session into one.
+ */
+ const devList = useMemo(() => splitDevelopmentList(allSessions), [allSessions]);
+ const sessions = devList.own;
+ const byAgent = useMemo(() => {
+ const map = new Map<string, SessionInfo[]>();
+ for (const [agentId, rows] of allByAgent) map.set(agentId, withoutOrgSessions(rows));
+ return map;
+ }, [allByAgent]);
+ // …and the server totals those rows are counted in, corrected the same way, so a group
+ // header never promises rows this list will not draw.
+ const { byAgent: countsByAgent, byWorkspace: workspaceCountsByAgent } = useMemo(
+ () =>
+ countsWithoutOrgSessions(serverCountsByAgent, serverWorkspaceCounts, devList.organization),
+ [serverCountsByAgent, serverWorkspaceCounts, devList],
+ );
+
const currentProjectId = currentProject?.projectId ?? null;
/** This Project's read markers; re-renders the rows whenever one is stamped. */
const sessionSeen = useSessionSeen(currentProjectId);
@@ -1262,6 +1319,18 @@ export function Sidebar({
go(`/chat/${s.sessionId}`);
};
+ /**
+ * The mode switch: company mode enters at `/org` (the organization last opened, else the
+ * first); development mode keeps whatever conversation is open and only leaves an
+ * organization page, which has no development form.
+ */
+ const switchMode = (mode: WorkMode) => {
+ if (mode === company.workMode) return;
+ company.setWorkMode(mode);
+ if (mode === "company") go("/org");
+ else if (isOrgRoute(location.pathname)) go("/chat");
+ };
+
/** agentId → display name (row hint tooltips in workspace mode). */
const agentNameById = useMemo(
() => new Map(agents.map((a) => [a.agentId, agentDisplayName(a)])),
@@ -1649,14 +1718,64 @@ export function Sidebar({
),
);
- /** Page entries of the collapsible nav group (智能体 → 评估中心, driven by the NAV_GROUP_KEYS manifest, minus the entries this user's role cannot reach). Always mounted — the collapse animates their height to zero and turns them inert. */
- const navItems: Array<{ to: string; label: string; icon: string }> = navKeysFor(
- user?.isAdmin === true,
- ).map((key) => ({ to: `/${key}`, label: S.nav[key], icon: NAV_ICONS[key] }));
+ /**
+ * Page entries of the collapsible nav group. Development mode: 智能体 → 评估中心, driven by
+ * the NAV_GROUP_KEYS manifest minus the entries this user's role cannot reach. Company
+ * mode: the organization's six pages (COMPANY_NAV_KEYS) — channels are not among them,
+ * they are the list below. Always mounted — the collapse animates their height to zero and
+ * turns them inert.
+ */
+ const navItems: Array<{
+ key: string;
+ /** Where the row leads — null for a row with nowhere to lead, which renders disabled. */
+ to: string | null;
+ label: string;
+ icon: string;
+ note: string | null;
+ }> = inCompany
+ ? COMPANY_NAV_KEYS.map((key) => ({
+ key,
+ // Company mode with no organization keeps its six rows and disables them: the pages
+ // exist, they just have no organization to show yet, and a nav that empties itself
+ // reads as a broken shell rather than as an empty one.
+ to: navOrg === null ? null : orgPagePath(navOrg.projectId, navOrg.orgId, key),
+ label: S.nav.org[key],
+ icon: COMPANY_NAV_ICONS[key],
+ note: null,
+ }))
+ : navKeysFor(user?.isAdmin === true).map((key) => ({
+ key,
+ to: `/${key}`,
+ label: S.nav[key],
+ icon: NAV_ICONS[key],
+ note: navNoteFor(badges, `/${key}`),
+ }));
return (
<div className="flex h-full w-full flex-col">
- {/* Project switcher (+ collapse sidebar) */}
+ {/* The work-mode switch, above the Project switcher: 开发 | 公司. Rendered only while
+ company mode is available (the admin master switch and the user's own switch both
+ on); the choice persists per user. The 内测版 tag rides on 公司 — the switch is the
+ one control that names the mode, so the mark stands on the word it qualifies rather
+ than somewhere inside the mode it describes. */}
+ {company.available && (
+ <div className="shrink-0 px-2 pt-2" role="group" aria-label={S.company.workMode}>
+ <Segmented
+ options={[
+ { value: "dev" as const, label: S.company.modeDev },
+ {
+ value: "company" as const,
+ label: S.company.modeCompany,
+ badge: { node: <BetaBadge />, name: S.company.beta },
+ },
+ ]}
+ value={company.workMode}
+ onChange={switchMode}
+ cols={2}
+ />
+ </div>
+ )}
+ {/* Project switcher (+ collapse sidebar); the organization switcher in company mode */}
<div className="flex shrink-0 items-center gap-1 px-2 pt-2">
{onCollapse && (
<button
@@ -1669,67 +1788,71 @@ export function Sidebar({
<Icon d="M15 6l-6 6 6 6M4 4v16" size={18} />
</button>
)}
- <Dropdown
- open={projectOpen}
- setOpen={setProjectOpen}
- className="min-w-0 flex-1"
- menuClass="left-0 right-0 top-full mt-1 origin-top"
- button={
- <button
- type="button"
- onClick={() => setProjectOpen(!projectOpen)}
- className="flex w-full items-center gap-1.5 rounded-md px-2 py-1.5 text-base font-semibold transition-colors duration-150 hover:bg-gray-200/70 dark:hover:bg-gray-800"
- >
- <span className="min-w-0 flex-1 truncate text-left">
- {currentProject ? projectDisplayName(currentProject) : S.common.loading}
- </span>
- <span className="text-gray-400">
- <ChevronDown />
- </span>
- </button>
- }
- >
- {projects.map((p) => (
- <button
- key={p.projectId}
- type="button"
- onClick={() => {
- setCurrentProjectId(p.projectId);
- setProjectOpen(false);
- }}
- className={`flex w-full items-center justify-between gap-2 px-3.5 py-2 text-left text-sm transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${
- p.projectId === currentProject?.projectId ? "font-semibold" : ""
- }`}
- >
- <span className="truncate">{projectDisplayName(p)}</span>
- <Badge tone="gray">{p.role}</Badge>
- </button>
- ))}
- <div className="mt-1.5 border-t border-gray-100 pt-1.5 dark:border-gray-800">
- <button
- type="button"
- className={menuItemClass}
- onClick={() => {
- setProjectOpen(false);
- setCreateProjectOpen(true);
- }}
- >
- + {S.project.create}
- </button>
- {currentProject && (
+ {inCompany ? (
+ <OrgSwitcher {...(onNavigate ? { onNavigate } : {})} />
+ ) : (
+ <Dropdown
+ open={projectOpen}
+ setOpen={setProjectOpen}
+ className="min-w-0 flex-1"
+ menuClass="left-0 right-0 top-full mt-1 origin-top"
+ button={
+ <button
+ type="button"
+ onClick={() => setProjectOpen(!projectOpen)}
+ className="flex w-full items-center gap-1.5 rounded-md px-2 py-1.5 text-base font-semibold transition-colors duration-150 hover:bg-gray-200/70 dark:hover:bg-gray-800"
+ >
+ <span className="min-w-0 flex-1 truncate text-left">
+ {currentProject ? projectDisplayName(currentProject) : S.common.loading}
+ </span>
+ <span className="text-gray-400">
+ <ChevronDown />
+ </span>
+ </button>
+ }
+ >
+ {projects.map((p) => (
+ <button
+ key={p.projectId}
+ type="button"
+ onClick={() => {
+ setCurrentProjectId(p.projectId);
+ setProjectOpen(false);
+ }}
+ className={`flex w-full items-center justify-between gap-2 px-3.5 py-2 text-left text-sm transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${
+ p.projectId === currentProject?.projectId ? "font-semibold" : ""
+ }`}
+ >
+ <span className="truncate">{projectDisplayName(p)}</span>
+ <Badge tone="gray">{p.role}</Badge>
+ </button>
+ ))}
+ <div className="mt-1.5 border-t border-gray-100 pt-1.5 dark:border-gray-800">
<button
type="button"
className={menuItemClass}
onClick={() => {
setProjectOpen(false);
- setProjectSettingsOpen(true);
+ setCreateProjectOpen(true);
}}
>
- {S.project.settings}
+ + {S.project.create}
</button>
- )}
- </div>
- </Dropdown>
+ {currentProject && (
+ <button
+ type="button"
+ className={menuItemClass}
+ onClick={() => {
+ setProjectOpen(false);
+ setProjectSettingsOpen(true);
+ }}
+ >
+ {S.project.settings}
+ </button>
+ )}
+ </div>
+ </Dropdown>
+ )}
</div>
{/* New chat: the only pinned entry besides the Project switcher above and the user row
@@ -1741,22 +1864,29 @@ export function Sidebar({
it, so a scrolled nav entry ended up flush against this pinned button, the two
labels touching. Outside the scroller the 8px stays put at every scroll offset —
the same text-to-text rhythm two adjacent nav rows have. */}
- <div className="shrink-0 px-2 pb-2 pt-2">
- <button
- type="button"
- onClick={() => newChat(defaultAgentId)}
- className={`flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-sm font-medium transition-colors duration-150 ${
- activeSessionId === DRAFT_SESSION_ID
- ? "bg-gray-200/70 text-gray-900 dark:bg-gray-800 dark:text-gray-100"
- : "text-gray-600 hover:bg-gray-200/50 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200"
- }`}
- >
- <span className="text-gray-500 dark:text-gray-400">
- <Icon d={NEW_CHAT_ICON} />
- </span>
- {S.chat.newSessionMenu}
- </button>
- </div>
+ {/* Company mode pins nothing here: a channel is made rarely, so "New channel" is the
+ channel list's own header action rather than a permanent row (channel-sidebar.tsx).
+ The slot still holds its 8px, which is the gap the scroll area below depends on. */}
+ {inCompany ? (
+ <div className="shrink-0 pb-2" />
+ ) : (
+ <div className="shrink-0 px-2 pb-2 pt-2">
+ <button
+ type="button"
+ onClick={() => newChat(defaultAgentId)}
+ className={`flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-sm font-medium transition-colors duration-150 ${
+ activeSessionId === DRAFT_SESSION_ID
+ ? "bg-gray-200/70 text-gray-900 dark:bg-gray-800 dark:text-gray-100"
+ : "text-gray-600 hover:bg-gray-200/50 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200"
+ }`}
+ >
+ <span className="text-gray-500 dark:text-gray-400">
+ <Icon d={NEW_CHAT_ICON} />
+ </span>
+ {S.chat.newSessionMenu}
+ </button>
+ </div>
+ )}
{/* Scroll area: the page nav and the session list scroll together, so the nav rides up
as the list is scrolled. It is the sidebar's only shrinkable block — with the nav
@@ -1798,10 +1928,27 @@ export function Sidebar({
label text (where it would float over whatever follows the word): at the
row's right edge, on the same inset as its horizontal padding, and vertically
centred on the row rather than on the line of text. */
- const note = navNoteFor(badges, item.to);
+ const note = item.note;
+ if (item.to === null) {
+ /* Nowhere to go: the row keeps its place and its glyph, muted, with no
+ hover fill and nothing to click or tab to. */
+ return (
+ <span
+ key={item.key}
+ role="link"
+ aria-disabled="true"
+ className="relative flex items-center gap-2 rounded-md px-2.5 py-1.5 text-sm text-gray-400 dark:text-gray-600"
+ >
+ <span className="text-gray-300 dark:text-gray-700">
+ <Icon d={item.icon} />
+ </span>
+ {item.label}
+ </span>
+ );
+ }
return (
<NavLink
- key={item.to}
+ key={item.key}
to={item.to}
onClick={() => onNavigate?.()}
{...(note !== null
@@ -1860,7 +2007,30 @@ export function Sidebar({
</button>
</nav>
- {/* Section header: list label + right-aligned controls (icon + tooltip family):
+ {inCompany ? (
+ navOrg !== null ? (
+ /* Company mode: the organization's channels, where development mode lists
+ conversations, and below them its 工位 group — one row per employee's desk. */
+ <>
+ <ChannelSidebar
+ projectId={navOrg.projectId}
+ orgId={navOrg.orgId}
+ {...(onNavigate ? { onNavigate } : {})}
+ />
+ <OrgSessionGroups
+ projectId={navOrg.projectId}
+ orgId={navOrg.orgId}
+ activeSessionId={activeSessionId}
+ {...(onNavigate ? { onNavigate } : {})}
+ />
+ </>
+ ) : (
+ /* No organization to list: the create block, not an empty channel list. */
+ <NoOrganizationsSidebar {...(onNavigate ? { onNavigate } : {})} />
+ )
+ ) : (
+ <>
+ {/* Section header: list label + right-aligned controls (icon + tooltip family):
search, list settings (grouping + sort radios — the old inline grouping
toggle relocated into this menu), and the mode-dependent create button (the
created object follows the grouping mode). The search is a mac-style
@@ -1869,135 +2039,135 @@ export function Sidebar({
takes the full width and the field inside grows leftward over the label's
place; the magnifier morphs from toggle button into the field's leading
glyph. No ruled separator at this boundary — see the nav toggle above. */}
- <div
- className={`mt-3 grid items-center px-1 pt-2 transition-[grid-template-columns] duration-200 ease-out ${
- searchOpen ? "grid-cols-[0fr_1fr]" : "grid-cols-[1fr_1fr]"
- }`}
- >
- <span
- className={`min-w-0 overflow-hidden whitespace-nowrap px-1 text-[11px] font-semibold uppercase tracking-wide text-gray-400 transition-opacity duration-200 dark:text-gray-500 ${
- searchOpen ? "opacity-0" : "opacity-100"
- }`}
- >
- {S.chat.sessionList}
- </span>
- <div className="flex min-w-0 items-center justify-end gap-0.5">
- {searchOpen ? (
- /* Expanded field: leading magnifier glyph + input + clear ×, one bordered
+ <div
+ className={`mt-3 grid items-center px-1 pt-2 transition-[grid-template-columns] duration-200 ease-out ${
+ searchOpen ? "grid-cols-[0fr_1fr]" : "grid-cols-[1fr_1fr]"
+ }`}
+ >
+ <span
+ className={`min-w-0 overflow-hidden whitespace-nowrap px-1 text-[11px] font-semibold uppercase tracking-wide text-gray-400 transition-opacity duration-200 dark:text-gray-500 ${
+ searchOpen ? "opacity-0" : "opacity-100"
+ }`}
+ >
+ {S.chat.sessionList}
+ </span>
+ <div className="flex min-w-0 items-center justify-end gap-0.5">
+ {searchOpen ? (
+ /* Expanded field: leading magnifier glyph + input + clear ×, one bordered
box filling the row (its width rides the column tween). Esc and × both
collapse it and drop the filter. */
- <div className="flex h-6 min-w-0 flex-1 items-center gap-1 rounded-md border border-gray-300 bg-white px-1.5 transition-colors duration-150 focus-within:border-gray-400 dark:border-gray-700 dark:bg-gray-900 dark:focus-within:border-gray-500">
- <span aria-hidden className="shrink-0 text-gray-400 dark:text-gray-500">
- <Icon d={SEARCH_ICON} size={12} />
- </span>
- <input
- autoFocus
- value={searchQuery}
- placeholder={S.chat.searchSessionsPlaceholder}
- aria-label={S.chat.searchSessions}
- {...noAutofill}
- onChange={(e) => setSearchQuery(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Escape") {
- e.stopPropagation();
- closeSearch();
- }
- }}
- className="min-w-0 flex-1 bg-transparent text-xs text-gray-700 placeholder:text-gray-400 focus:outline-none dark:text-gray-200 dark:placeholder:text-gray-500"
- />
- <button
- type="button"
- title={S.chat.searchClear}
- aria-label={S.chat.searchClear}
- onClick={closeSearch}
- className="flex h-4 w-4 shrink-0 items-center justify-center text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-300"
- >
- <Icon d={CLOSE_ICON} size={11} />
- </button>
- </div>
- ) : (
- <button
- type="button"
- title={S.chat.searchSessions}
- aria-label={S.chat.searchSessions}
- onClick={() => setSearchOpen(true)}
- className={headerControlClass(false)}
- >
- <Icon d={SEARCH_ICON} size={14} />
- </button>
- )}
- <Dropdown
- open={listSettingsOpen}
- setOpen={setListSettingsOpen}
- portal={{ direction: "down", align: "right" }}
- menuClass="w-40"
- button={
- <button
- type="button"
- title={S.chat.listSettings}
- aria-label={S.chat.listSettings}
- aria-haspopup="menu"
- aria-expanded={listSettingsOpen}
- onClick={() => setListSettingsOpen(!listSettingsOpen)}
- className={headerControlClass(listSettingsOpen)}
+ <div className="flex h-6 min-w-0 flex-1 items-center gap-1 rounded-md border border-gray-300 bg-white px-1.5 transition-colors duration-150 focus-within:border-gray-400 dark:border-gray-700 dark:bg-gray-900 dark:focus-within:border-gray-500">
+ <span aria-hidden className="shrink-0 text-gray-400 dark:text-gray-500">
+ <Icon d={SEARCH_ICON} size={12} />
+ </span>
+ <input
+ autoFocus
+ value={searchQuery}
+ placeholder={S.chat.searchSessionsPlaceholder}
+ aria-label={S.chat.searchSessions}
+ {...noAutofill}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ e.stopPropagation();
+ closeSearch();
+ }
+ }}
+ className="min-w-0 flex-1 bg-transparent text-xs text-gray-700 placeholder:text-gray-400 focus:outline-none dark:text-gray-200 dark:placeholder:text-gray-500"
+ />
+ <button
+ type="button"
+ title={S.chat.searchClear}
+ aria-label={S.chat.searchClear}
+ onClick={closeSearch}
+ className="flex h-4 w-4 shrink-0 items-center justify-center text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-300"
+ >
+ <Icon d={CLOSE_ICON} size={11} />
+ </button>
+ </div>
+ ) : (
+ <button
+ type="button"
+ title={S.chat.searchSessions}
+ aria-label={S.chat.searchSessions}
+ onClick={() => setSearchOpen(true)}
+ className={headerControlClass(false)}
+ >
+ <Icon d={SEARCH_ICON} size={14} />
+ </button>
+ )}
+ <Dropdown
+ open={listSettingsOpen}
+ setOpen={setListSettingsOpen}
+ portal={{ direction: "down", align: "right" }}
+ menuClass="w-40"
+ button={
+ <button
+ type="button"
+ title={S.chat.listSettings}
+ aria-label={S.chat.listSettings}
+ aria-haspopup="menu"
+ aria-expanded={listSettingsOpen}
+ onClick={() => setListSettingsOpen(!listSettingsOpen)}
+ className={headerControlClass(listSettingsOpen)}
+ >
+ <Icon d={SLIDERS_ICON} size={14} />
+ </button>
+ }
>
- <Icon d={SLIDERS_ICON} size={14} />
- </button>
- }
- >
- <p className={menuSectionClass}>{S.chat.groupModeSection}</p>
- <MenuRadioRow
- icon={GROUP_MODE_ICONS.workspace}
- label={S.chat.groupByWorkspace}
- checked={groupMode === "workspace"}
- onSelect={() => {
- setGroupMode("workspace");
- setListSettingsOpen(false);
- }}
- />
- <MenuRadioRow
- icon={GROUP_MODE_ICONS.agent}
- label={S.chat.groupByAgent}
- checked={groupMode === "agent"}
- onSelect={() => {
- setGroupMode("agent");
- setListSettingsOpen(false);
- }}
- />
- <MenuRadioRow
- icon={GROUP_MODE_ICONS.time}
- label={S.chat.groupByTime}
- checked={groupMode === "time"}
- onSelect={() => {
- setGroupMode("time");
- setListSettingsOpen(false);
- }}
- />
- <div className="my-1 border-t border-gray-100 dark:border-gray-800" />
- <p className={menuSectionClass}>{S.chat.sortModeSection}</p>
- {/* Manual order is offered only where a drag can actually happen (see canDrag). */}
- {canDrag && (
- <MenuRadioRow
- icon={SORT_MODE_ICONS.manual}
- label={S.chat.sortManual}
- checked={sortMode === "manual"}
- onSelect={() => {
- setSortMode("manual");
- setListSettingsOpen(false);
- }}
- />
- )}
- <MenuRadioRow
- icon={SORT_MODE_ICONS.recent}
- label={S.chat.sortRecent}
- checked={sortMode === "recent"}
- onSelect={() => {
- setSortMode("recent");
- setListSettingsOpen(false);
- }}
- />
- </Dropdown>
- {/* Mode-dependent create — 具体新建的对象按分组方式决定, the icon following
+ <p className={menuSectionClass}>{S.chat.groupModeSection}</p>
+ <MenuRadioRow
+ icon={GROUP_MODE_ICONS.workspace}
+ label={S.chat.groupByWorkspace}
+ checked={groupMode === "workspace"}
+ onSelect={() => {
+ setGroupMode("workspace");
+ setListSettingsOpen(false);
+ }}
+ />
+ <MenuRadioRow
+ icon={GROUP_MODE_ICONS.agent}
+ label={S.chat.groupByAgent}
+ checked={groupMode === "agent"}
+ onSelect={() => {
+ setGroupMode("agent");
+ setListSettingsOpen(false);
+ }}
+ />
+ <MenuRadioRow
+ icon={GROUP_MODE_ICONS.time}
+ label={S.chat.groupByTime}
+ checked={groupMode === "time"}
+ onSelect={() => {
+ setGroupMode("time");
+ setListSettingsOpen(false);
+ }}
+ />
+ <div className="my-1 border-t border-gray-100 dark:border-gray-800" />
+ <p className={menuSectionClass}>{S.chat.sortModeSection}</p>
+ {/* Manual order is offered only where a drag can actually happen (see canDrag). */}
+ {canDrag && (
+ <MenuRadioRow
+ icon={SORT_MODE_ICONS.manual}
+ label={S.chat.sortManual}
+ checked={sortMode === "manual"}
+ onSelect={() => {
+ setSortMode("manual");
+ setListSettingsOpen(false);
+ }}
+ />
+ )}
+ <MenuRadioRow
+ icon={SORT_MODE_ICONS.recent}
+ label={S.chat.sortRecent}
+ checked={sortMode === "recent"}
+ onSelect={() => {
+ setSortMode("recent");
+ setListSettingsOpen(false);
+ }}
+ />
+ </Dropdown>
+ {/* Mode-dependent create — 具体新建的对象按分组方式决定, the icon following
suit (folder+ / robot+, a bottom-right plus badge on the entity's glyph):
agent grouping opens the Agents page's existing create dialog (route
state); workspace grouping opens the SAME directory-browse menu the
@@ -2005,355 +2175,363 @@ export function Sidebar({
workspace group immediately, Sessions or not. Time buckets are not
something to create into, so that mode starts a plain new conversation
and wears the compose glyph without a plus badge. */}
- {newEntity === "agent" ? (
- <button
- type="button"
- title={newEntityLabel}
- aria-label={newEntityLabel}
- onClick={() => {
- navigate("/agents", { state: { create: true } });
- onNavigate?.();
- }}
- className={headerControlClass(false)}
- >
- <AddBadgeIcon base={NAV_ICONS.agents} />
- </button>
- ) : newEntity === "chat" ? (
- <button
- type="button"
- title={newEntityLabel}
- aria-label={newEntityLabel}
- onClick={() => newChat()}
- className={headerControlClass(false)}
- >
- <Icon d={NEW_CHAT_ICON} size={ICON_SIZE.iconButton} />
- </button>
- ) : (
- <WorkspaceSelect
- // Remount per Project: the picker browses lazily and caches the listing
- // for its lifetime, so a long-lived instance would show the PREVIOUS
- // Project's directories after a switch — and register that path into the
- // new Project's registry.
- key={currentProjectId ?? "no-project"}
- projectId={currentProjectId ?? ""}
- workspace=""
- onChange={addWorkspace}
- trigger={(open, toggle) => (
+ {newEntity === "agent" ? (
<button
type="button"
title={newEntityLabel}
aria-label={newEntityLabel}
- aria-expanded={open}
- onClick={toggle}
- className={headerControlClass(open)}
+ onClick={() => {
+ navigate("/agents", { state: { create: true } });
+ onNavigate?.();
+ }}
+ className={headerControlClass(false)}
>
- <AddBadgeIcon base={FOLDER_ICON} />
+ <AddBadgeIcon base={NAV_ICONS.agents} />
</button>
+ ) : newEntity === "chat" ? (
+ <button
+ type="button"
+ title={newEntityLabel}
+ aria-label={newEntityLabel}
+ onClick={() => newChat()}
+ className={headerControlClass(false)}
+ >
+ <Icon d={NEW_CHAT_ICON} size={ICON_SIZE.iconButton} />
+ </button>
+ ) : (
+ <WorkspaceSelect
+ // Remount per Project: the picker browses lazily and caches the listing
+ // for its lifetime, so a long-lived instance would show the PREVIOUS
+ // Project's directories after a switch — and register that path into the
+ // new Project's registry.
+ key={currentProjectId ?? "no-project"}
+ projectId={currentProjectId ?? ""}
+ workspace=""
+ onChange={addWorkspace}
+ trigger={(open, toggle) => (
+ <button
+ type="button"
+ title={newEntityLabel}
+ aria-label={newEntityLabel}
+ aria-expanded={open}
+ onClick={toggle}
+ className={headerControlClass(open)}
+ >
+ <AddBadgeIcon base={FOLDER_ICON} />
+ </button>
+ )}
+ />
)}
- />
- )}
- </div>
- </div>
+ </div>
+ </div>
- {/* Parked draft conversations (unsent new chats, newest first): pinned above both
+ {/* Parked draft conversations (unsent new chats, newest first): pinned above both
grouping modes — they belong to no Agent or Workspace until sent. Hidden
entirely while there are none; the search filter applies to their titles too. */}
- {shownDrafts.length > 0 && (
- <div className="pt-2.5">
- <GroupHeader
- open={searching || !collapsedGroups.has(DRAFTS_GROUP_KEY)}
- onToggle={() => toggleGroup(DRAFTS_GROUP_KEY)}
- icon={
- <span className="shrink-0 text-gray-400 dark:text-gray-500">
- <Icon d={NEW_CHAT_ICON} size={ICON_SIZE.groupHeaderGlyph} />
- </span>
- }
- label={S.chat.draftGroup}
- uppercase
- count={shownDrafts.length}
- />
- {(searching || !collapsedGroups.has(DRAFTS_GROUP_KEY)) && (
- <ul className="space-y-0.5">
- {shownDrafts.map((entry) => (
- <DraftRow
- key={entry.id}
- entry={entry}
- active={entry.id === activeSessionId}
- onOpen={() => go(`/chat/${entry.id}`)}
- onDelete={() => setDeletingDraft(entry)}
- />
- ))}
- </ul>
+ {shownDrafts.length > 0 && (
+ <div className="pt-2.5">
+ <GroupHeader
+ open={searching || !collapsedGroups.has(DRAFTS_GROUP_KEY)}
+ onToggle={() => toggleGroup(DRAFTS_GROUP_KEY)}
+ icon={
+ <span className="shrink-0 text-gray-400 dark:text-gray-500">
+ <Icon d={NEW_CHAT_ICON} size={ICON_SIZE.groupHeaderGlyph} />
+ </span>
+ }
+ label={S.chat.draftGroup}
+ uppercase
+ count={shownDrafts.length}
+ />
+ {(searching || !collapsedGroups.has(DRAFTS_GROUP_KEY)) && (
+ <ul className="space-y-0.5">
+ {shownDrafts.map((entry) => (
+ <DraftRow
+ key={entry.id}
+ entry={entry}
+ active={entry.id === activeSessionId}
+ onOpen={() => go(`/chat/${entry.id}`)}
+ onDelete={() => setDeletingDraft(entry)}
+ />
+ ))}
+ </ul>
+ )}
+ </div>
)}
- </div>
- )}
- {groupMode === "agent" ? (
- loading && agents.length === 0 ? (
- <SkeletonList rows={5} />
- ) : (
- // While searching: every group renders (paging bypassed), zero-match groups
- // hide, and the rest are forced open — a hit inside a collapsed group would
- // look like a missing result.
- groupsOnPage(orderedAgents).map((agent) => {
- const groupRows = filterRows(byAgent.get(agent.agentId) ?? []);
- if (searching && groupRows.length === 0) return null;
- const parts = partitionSessions(groupRows);
- /** Conversations folded inside a folder-only group; undefined = an ordinary group, with active rows of its own. */
- const foldedOnly = folderOnlyAgents.get(agent.agentId);
- const collapsed =
- !searching &&
- (foldedOnly === undefined
- ? collapsedGroups.has(agent.agentId)
- : !expandedFolderOnlyGroups.has(agent.agentId));
- const pinned = pinnedGroups.has(agent.agentId);
- const drag = groupDragProps(agent.agentId, agentGroupSequence);
- return (
- <GroupBlock key={agent.agentId} dropEdge={drag.dropEdge}>
- {/* Group header: collapse toggle (Agent name) + pin + new chat + Agent settings; also the group's drag handle. */}
- <GroupHeader
- {...drag.header}
- open={!collapsed}
- onToggle={() => toggleGroup(agent.agentId, foldedOnly !== undefined)}
- icon={
- <AgentAvatar
- id={agent.agentId}
- name={agentDisplayName(agent)}
- size={18}
- className="shrink-0 rounded"
+ {groupMode === "agent" ? (
+ loading && agents.length === 0 ? (
+ <SkeletonList rows={5} />
+ ) : (
+ // While searching: every group renders (paging bypassed), zero-match groups
+ // hide, and the rest are forced open — a hit inside a collapsed group would
+ // look like a missing result.
+ groupsOnPage(orderedAgents).map((agent) => {
+ const groupRows = filterRows(byAgent.get(agent.agentId) ?? []);
+ if (searching && groupRows.length === 0) return null;
+ const parts = partitionSessions(groupRows);
+ /** Conversations folded inside a folder-only group; undefined = an ordinary group, with active rows of its own. */
+ const foldedOnly = folderOnlyAgents.get(agent.agentId);
+ const collapsed =
+ !searching &&
+ (foldedOnly === undefined
+ ? collapsedGroups.has(agent.agentId)
+ : !expandedFolderOnlyGroups.has(agent.agentId));
+ const pinned = pinnedGroups.has(agent.agentId);
+ const drag = groupDragProps(agent.agentId, agentGroupSequence);
+ return (
+ <GroupBlock key={agent.agentId} dropEdge={drag.dropEdge}>
+ {/* Group header: collapse toggle (Agent name) + pin + new chat + Agent settings; also the group's drag handle. */}
+ <GroupHeader
+ {...drag.header}
+ open={!collapsed}
+ onToggle={() => toggleGroup(agent.agentId, foldedOnly !== undefined)}
+ icon={
+ <AgentAvatar
+ id={agent.agentId}
+ name={agentDisplayName(agent)}
+ size={18}
+ className="shrink-0 rounded"
+ />
+ }
+ label={agentDisplayName(agent)}
+ uppercase
+ {...(foldedOnly === undefined
+ ? {}
+ : {
+ // An Agent header carries no count otherwise; a folder-only one says
+ // what it holds, because everything it holds is behind its folders.
+ count: foldedOnly,
+ muted: true,
+ title: S.chat.folderOnlyGroup(foldedOnly),
+ })}
+ actions={
+ <>
+ <GroupPinButton
+ pinned={pinned}
+ onToggle={() => togglePin(agent.agentId)}
+ />
+ {/* New chat: enters draft state directly with this group's Agent (all options live on the draft input card) */}
+ <button
+ type="button"
+ title={S.chat.newSessionMenu}
+ aria-label={S.chat.newSessionMenu}
+ onClick={() => newChat(agent.agentId)}
+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ >
+ <Icon d="M12 5v14M5 12h14" size={ICON_SIZE.groupHeaderAction} />
+ </button>
+ <button
+ type="button"
+ title={S.agent.settings}
+ onClick={() => go(`/agents/${agent.agentId}`)}
+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ >
+ <Icon d={GEAR_ICON} size={ICON_SIZE.groupHeaderAction} />
+ </button>
+ </>
+ }
/>
- }
- label={agentDisplayName(agent)}
- uppercase
- {...(foldedOnly === undefined
- ? {}
- : {
- // An Agent header carries no count otherwise; a folder-only one says
- // what it holds, because everything it holds is behind its folders.
- count: foldedOnly,
- muted: true,
- title: S.chat.folderOnlyGroup(foldedOnly),
- })}
- actions={
- <>
- <GroupPinButton pinned={pinned} onToggle={() => togglePin(agent.agentId)} />
- {/* New chat: enters draft state directly with this group's Agent (all options live on the draft input card) */}
- <button
- type="button"
- title={S.chat.newSessionMenu}
- aria-label={S.chat.newSessionMenu}
- onClick={() => newChat(agent.agentId)}
- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"
- >
- <Icon d="M12 5v14M5 12h14" size={ICON_SIZE.groupHeaderAction} />
- </button>
- <button
- type="button"
- title={S.agent.settings}
- onClick={() => go(`/agents/${agent.agentId}`)}
- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"
- >
- <Icon d={GEAR_ICON} size={ICON_SIZE.groupHeaderAction} />
- </button>
- </>
- }
- />
- {collapsed
- ? null
- : renderGroupBody(
- agent.agentId,
- parts,
- false,
- countsByAgent.get(agent.agentId),
- () => [agent.agentId],
- )}
- </GroupBlock>
- );
- })
- )
- ) : null}
- {groupMode === "agent" ? groupPagerRow() : null}
- {groupMode !== "workspace" ? null : loading && sessions.length === 0 ? (
- <SkeletonList rows={5} />
- ) : orderedWorkspaceGroups.length === 0 && !searching ? (
- <p className="px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600">
- {S.chat.noSessions}
- </p>
- ) : (
- // Same search treatment as agent mode: paging bypassed, zero-match groups hidden, the rest forced open.
- groupsOnPage(orderedWorkspaceGroups).map((group) => {
- const groupRows = filterRows(group.sessions);
- if (searching && groupRows.length === 0) return null;
- const parts = partitionSessions(groupRows);
- /** Conversations folded inside a folder-only group; undefined = an ordinary group, with active rows of its own. */
- const foldedOnly = folderOnlyWorkspaceGroups.get(group.key);
- const collapsed =
- !searching &&
- (foldedOnly === undefined
- ? collapsedGroups.has(group.key)
- : !expandedFolderOnlyGroups.has(group.key));
- const pinned = pinnedGroups.has(group.key);
- /**
- * Header tooltip: the full Workspace path, or — for a folder-only group — the
- * sentence that says what the dimmed header and its count mean, which carries that
- * same path inside it.
- */
- const headerTitle =
- foldedOnly === undefined
- ? group.fullPath
- : S.chat.folderOnlyGroup(foldedOnly, group.fullPath ?? undefined);
- const drag = groupDragProps(group.key, workspaceGroupSequence);
- /** This group's exact server share (per-Workspace fold) and its per-category fetch fan-out. */
- const counts = workspaceGroupCounts.get(group.key);
- const contributingAgents = [...new Set(group.sessions.map((s) => s.agentId))];
- const agentsFor = (category: SessionCategory) => [
- ...new Set([...(counts?.agents[category] ?? []), ...contributingAgents]),
- ];
- return (
- <GroupBlock key={group.key} dropEdge={drag.dropEdge}>
- {/* Group header: collapse toggle (folder icon + directory basename + count, full
+ {collapsed
+ ? null
+ : renderGroupBody(
+ agent.agentId,
+ parts,
+ false,
+ countsByAgent.get(agent.agentId),
+ () => [agent.agentId],
+ )}
+ </GroupBlock>
+ );
+ })
+ )
+ ) : null}
+ {groupMode === "agent" ? groupPagerRow() : null}
+ {groupMode !== "workspace" ? null : loading && sessions.length === 0 ? (
+ <SkeletonList rows={5} />
+ ) : orderedWorkspaceGroups.length === 0 && !searching ? (
+ <p className="px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600">
+ {S.chat.noSessions}
+ </p>
+ ) : (
+ // Same search treatment as agent mode: paging bypassed, zero-match groups hidden, the rest forced open.
+ groupsOnPage(orderedWorkspaceGroups).map((group) => {
+ const groupRows = filterRows(group.sessions);
+ if (searching && groupRows.length === 0) return null;
+ const parts = partitionSessions(groupRows);
+ /** Conversations folded inside a folder-only group; undefined = an ordinary group, with active rows of its own. */
+ const foldedOnly = folderOnlyWorkspaceGroups.get(group.key);
+ const collapsed =
+ !searching &&
+ (foldedOnly === undefined
+ ? collapsedGroups.has(group.key)
+ : !expandedFolderOnlyGroups.has(group.key));
+ const pinned = pinnedGroups.has(group.key);
+ /**
+ * Header tooltip: the full Workspace path, or — for a folder-only group — the
+ * sentence that says what the dimmed header and its count mean, which carries that
+ * same path inside it.
+ */
+ const headerTitle =
+ foldedOnly === undefined
+ ? group.fullPath
+ : S.chat.folderOnlyGroup(foldedOnly, group.fullPath ?? undefined);
+ const drag = groupDragProps(group.key, workspaceGroupSequence);
+ /** This group's exact server share (per-Workspace fold) and its per-category fetch fan-out. */
+ const counts = workspaceGroupCounts.get(group.key);
+ const contributingAgents = [...new Set(group.sessions.map((s) => s.agentId))];
+ const agentsFor = (category: SessionCategory) => [
+ ...new Set([...(counts?.agents[category] ?? []), ...contributingAgents]),
+ ];
+ return (
+ <GroupBlock key={group.key} dropEdge={drag.dropEdge}>
+ {/* Group header: collapse toggle (folder icon + directory basename + count, full
path in the tooltip; the count = the group's active conversations only, exact
server share, loaded rows win a disagreement — the folders never feed it,
except in a folder-only group, where they are all there is to count) +
pin + new chat in this Workspace; also the group's drag handle. */}
- <GroupHeader
- {...drag.header}
- open={!collapsed}
- onToggle={() => toggleGroup(group.key, foldedOnly !== undefined)}
- icon={
- /* Folder opens and closes with the group */
- <span className="shrink-0 text-gray-400 dark:text-gray-500">
- <Icon
- d={collapsed ? FOLDER_ICON : FOLDER_OPEN_ICON}
- size={ICON_SIZE.groupHeaderGlyph}
- />
- </span>
- }
- label={group.temp ? S.chat.tempWorkspaces : group.label}
- count={
- foldedOnly !== undefined
- ? foldedOnly
- : searching
- ? parts.active.length
- : Math.max(counts?.totals.active ?? 0, parts.active.length)
- }
- muted={foldedOnly !== undefined}
- {...(headerTitle !== null ? { title: headerTitle } : {})}
- actions={
- <>
- <GroupPinButton pinned={pinned} onToggle={() => togglePin(group.key)} />
- {/* New chat in this Workspace: pre-fills the group's path in the draft ("" = temporary workspace); the Agent is the current one, falling back to default_agent */}
- <button
- type="button"
- title={S.chat.newSessionInWorkspace}
- aria-label={S.chat.newSessionInWorkspace}
- onClick={() => newChat(workspaceNewChatAgentId, group.fullPath ?? "")}
- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"
- >
- <Icon d="M12 5v14M5 12h14" size={ICON_SIZE.groupHeaderAction} />
- </button>
- {/* Manually-added (registry-backed) Workspaces only: rename-alias /
+ <GroupHeader
+ {...drag.header}
+ open={!collapsed}
+ onToggle={() => toggleGroup(group.key, foldedOnly !== undefined)}
+ icon={
+ /* Folder opens and closes with the group */
+ <span className="shrink-0 text-gray-400 dark:text-gray-500">
+ <Icon
+ d={collapsed ? FOLDER_ICON : FOLDER_OPEN_ICON}
+ size={ICON_SIZE.groupHeaderGlyph}
+ />
+ </span>
+ }
+ label={group.temp ? S.chat.tempWorkspaces : group.label}
+ count={
+ foldedOnly !== undefined
+ ? foldedOnly
+ : searching
+ ? parts.active.length
+ : Math.max(counts?.totals.active ?? 0, parts.active.length)
+ }
+ muted={foldedOnly !== undefined}
+ {...(headerTitle !== null ? { title: headerTitle } : {})}
+ actions={
+ <>
+ <GroupPinButton pinned={pinned} onToggle={() => togglePin(group.key)} />
+ {/* New chat in this Workspace: pre-fills the group's path in the draft ("" = temporary workspace); the Agent is the current one, falling back to default_agent */}
+ <button
+ type="button"
+ title={S.chat.newSessionInWorkspace}
+ aria-label={S.chat.newSessionInWorkspace}
+ onClick={() => newChat(workspaceNewChatAgentId, group.fullPath ?? "")}
+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ >
+ <Icon d="M12 5v14M5 12h14" size={ICON_SIZE.groupHeaderAction} />
+ </button>
+ {/* Manually-added (registry-backed) Workspaces only: rename-alias /
remove-from-sidebar overflow, to the right of the "+" (session-
derived groups have no registry entry for these to act on). */}
- {registeredPaths.has(group.key) && (
- <GroupOverflowMenu
- onRename={() => openRenameWorkspace(group.key)}
- onDelete={() =>
- setDeletingWorkspace({ path: group.key, label: group.label })
- }
- />
- )}
- </>
- }
- />
+ {registeredPaths.has(group.key) && (
+ <GroupOverflowMenu
+ onRename={() => openRenameWorkspace(group.key)}
+ onDelete={() =>
+ setDeletingWorkspace({ path: group.key, label: group.label })
+ }
+ />
+ )}
+ </>
+ }
+ />
- {/* A workspace group can span Agents: the group body fans folder loads and "More"
+ {/* A workspace group can span Agents: the group body fans folder loads and "More"
out per category to the Agents whose share of THIS group is non-zero (plus the
Agents already contributing loaded rows) — the active list and each folder
page independently. */}
- {collapsed
- ? null
- : renderGroupBody(group.key, parts, true, counts?.totals, agentsFor)}
- </GroupBlock>
- );
- })
- )}
- {groupMode === "workspace" ? groupPagerRow() : null}
+ {collapsed
+ ? null
+ : renderGroupBody(group.key, parts, true, counts?.totals, agentsFor)}
+ </GroupBlock>
+ );
+ })
+ )}
+ {groupMode === "workspace" ? groupPagerRow() : null}
- {/* Time mode: last day / last month / earlier, bucketed on each conversation's last
+ {/* Time mode: last day / last month / earlier, bucketed on each conversation's last
activity — the same stamp the rows' compact timestamps and the recency sort read,
so a row can never sit under a bucket its own timestamp contradicts. Empty buckets
are dropped, and there are at most three, so this mode never paginates its groups.
The buckets span every Agent and every Workspace: a bucket's "More" only reveals
further loaded rows, while fetching the next page and reaching the Subagents /
Scheduled / Archived rows happen once for the whole Project, below. */}
- {groupMode !== "time" || timeParts === null ? null : loading && sessions.length === 0 ? (
- <SkeletonList rows={5} />
- ) : (
- <>
- {timeGroups.map((group) => {
- const collapsed = !searching && collapsedGroups.has(group.key);
- return (
- <div key={group.key} className="pt-2.5">
- <GroupHeader
- open={!collapsed}
- onToggle={() => toggleGroup(group.key)}
- icon={
- <span className="shrink-0 text-gray-400 dark:text-gray-500">
- <Icon d={GROUP_MODE_ICONS.time} size={ICON_SIZE.groupHeaderGlyph} />
- </span>
- }
- label={S.chat.timeGroups[group.bucket]}
- uppercase
- count={group.sessions.length}
- />
- {collapsed
- ? null
- : renderGroupBody(
- group.key,
- bucketPartition(group.sessions),
- true,
- undefined,
- () => [],
- )}
- </div>
- );
- })}
+ {groupMode !== "time" || timeParts === null ? null : loading &&
+ sessions.length === 0 ? (
+ <SkeletonList rows={5} />
+ ) : (
+ <>
+ {timeGroups.map((group) => {
+ const collapsed = !searching && collapsedGroups.has(group.key);
+ return (
+ <div key={group.key} className="pt-2.5">
+ <GroupHeader
+ open={!collapsed}
+ onToggle={() => toggleGroup(group.key)}
+ icon={
+ <span className="shrink-0 text-gray-400 dark:text-gray-500">
+ <Icon d={GROUP_MODE_ICONS.time} size={ICON_SIZE.groupHeaderGlyph} />
+ </span>
+ }
+ label={S.chat.timeGroups[group.bucket]}
+ uppercase
+ count={group.sessions.length}
+ />
+ {collapsed
+ ? null
+ : renderGroupBody(
+ group.key,
+ bucketPartition(group.sessions),
+ true,
+ undefined,
+ () => [],
+ )}
+ </div>
+ );
+ })}
- {/* Empty only when the shared folders below are empty too (renderGroupBody's own
+ {/* Empty only when the shared folders below are empty too (renderGroupBody's own
rule): "no Sessions yet" over an "Archived (3)" row would contradict it. */}
- {timeGroups.length === 0 && !searching && timeFolders.every((f) => f === null) && (
- <p className="px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600">
- {S.chat.noSessions}
- </p>
- )}
+ {timeGroups.length === 0 && !searching && timeFolders.every((f) => f === null) && (
+ <p className="px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600">
+ {S.chat.noSessions}
+ </p>
+ )}
- {/* Whole-list paging: a fetched page lands in whichever bucket its rows' activity
+ {/* Whole-list paging: a fetched page lands in whichever bucket its rows' activity
puts them, so the row that pulls one belongs to the list, not to a bucket —
and its label says "conversations" where a bucket's says "more". */}
- {!searching &&
- timeParts.active.length < projectCounts.active &&
- timeMoreAgents.length > 0 && (
- <MoreRow
- label={S.chat.loadMoreSessions}
- ariaLabel={S.chat.loadMoreSessions}
- pending={pendingLoads.has(loadKey(TIME_FOLDERS_GROUP_KEY, "active"))}
- onClick={() => trackedLoadMore(TIME_FOLDERS_GROUP_KEY, "active", timeMoreAgents)}
- className="mt-1"
- />
- )}
+ {!searching &&
+ timeParts.active.length < projectCounts.active &&
+ timeMoreAgents.length > 0 && (
+ <MoreRow
+ label={S.chat.loadMoreSessions}
+ ariaLabel={S.chat.loadMoreSessions}
+ pending={pendingLoads.has(loadKey(TIME_FOLDERS_GROUP_KEY, "active"))}
+ onClick={() =>
+ trackedLoadMore(TIME_FOLDERS_GROUP_KEY, "active", timeMoreAgents)
+ }
+ className="mt-1"
+ />
+ )}
- {/* The shared, Project-wide folders (see timeFolders). */}
- <div className="pt-2.5">{timeFolders}</div>
- </>
- )}
+ {/* The shared, Project-wide folders (see timeFolders). */}
+ <div className="pt-2.5">{timeFolders}</div>
+ </>
+ )}
- {/* Quiet no-match line: the search is live and nothing — drafts included — hit. */}
- {searching && !hasSearchMatches && (
- <p className="px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600">
- {S.chat.searchNoMatches}
- </p>
+ {/* Quiet no-match line: the search is live and nothing — drafts included — hit. */}
+ {searching && !hasSearchMatches && (
+ <p className="px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600">
+ {S.chat.searchNoMatches}
+ </p>
+ )}
+ </>
)}
</div>
diff --git a/packages/web/src/components/ui/drawer.tsx b/packages/web/src/components/ui/drawer.tsx
index e58b1741..2efafaa0 100644
--- a/packages/web/src/components/ui/drawer.tsx
+++ b/packages/web/src/components/ui/drawer.tsx
@@ -1,10 +1,15 @@
/**
* Drawer component (for mobile nav/panels): overlay fades in + panel slides in from the side; Esc or clicking the overlay closes it.
* `side` determines the docking direction; the panel width defaults to 80vw, capped by widthClass.
+ *
+ * Escape goes through the shared esc-layer stack (see modal.tsx), so a dialog or menu opened
+ * from inside a drawer takes the first Escape alone: without that, one press would close the
+ * confirmation *and* the drawer under it, dropping the panel the user was working in.
*/
-import { useEffect } from "react";
+import { useEffect, useRef } from "react";
import type { ReactNode } from "react";
import { CloseButton } from "./icons";
+import { isTopEscLayer, popEscLayer, pushEscLayer } from "./modal";
export interface DrawerProps {
open: boolean;
@@ -17,14 +22,24 @@ export interface DrawerProps {
}
export function Drawer({ open, side = "left", title, onClose, children, widthClass }: DrawerProps) {
+ // Latest-callback ref, so the effect below re-runs ONLY on open/close: call sites pass an
+ // inline arrow for onClose, and re-running on its identity would pop and re-push this
+ // drawer's esc-layer on every render — jumping it back above a dialog opened inside it.
+ const onCloseRef = useRef(onClose);
+ onCloseRef.current = onClose;
+
useEffect(() => {
if (!open) return;
+ const layer = pushEscLayer();
const onKey = (e: KeyboardEvent) => {
- if (e.key === "Escape") onClose();
+ if (e.key === "Escape" && isTopEscLayer(layer)) onCloseRef.current();
};
window.addEventListener("keydown", onKey);
- return () => window.removeEventListener("keydown", onKey);
- }, [open, onClose]);
+ return () => {
+ window.removeEventListener("keydown", onKey);
+ popEscLayer(layer);
+ };
+ }, [open]);
if (!open) return null;
return (
diff --git a/packages/web/src/components/ui/file-tree.tsx b/packages/web/src/components/ui/file-tree.tsx
index af348538..ff9c9f61 100644
--- a/packages/web/src/components/ui/file-tree.tsx
+++ b/packages/web/src/components/ui/file-tree.tsx
@@ -17,6 +17,9 @@
* event over the whole tree (the Workspace panel's drag-and-drop, its context menu) resolves
* the row under the pointer.
*
+ * A row names itself from what it draws. `rowLabel` is the one way out, for a row whose visible
+ * text is not the whole of what it means — the handbook's pinned index.
+ *
* The rows stay one flat list; what nests is the drawing. An open directory's descendants go
* in a `role="group"` box whose height is animated, so a subtree grows out of its directory's
* row and shrinks back into it. Only the directory the caller says was just toggled animates,
@@ -67,6 +70,7 @@ export function FileTree<Row extends FileTreeRow>({
scrollTo = null,
toggled = null,
rowTitle,
+ rowLabel,
rowTrailing,
emptyLabel,
className = "",
@@ -89,6 +93,13 @@ export function FileTree<Row extends FileTreeRow>({
toggled?: TreeToggle | null;
/** A row's `title` tooltip; the path by default. */
rowTitle?: (row: Row) => string;
+ /**
+ * A row's accessible name, for the row whose visible text leaves out what the row means — the
+ * handbook's pinned index says on screen only a file name, and why it is pinned would
+ * otherwise live in the tooltip alone. Undefined (the default, and every ordinary row): the
+ * row names itself from what it draws.
+ */
+ rowLabel?: (row: Row) => string | undefined;
/** Trailing content on a row, after its name — the Workspace's file sizes. */
rowTrailing?: (row: Row) => ReactNode;
/** What an open directory holding nothing says in place of its children; omitted, it says nothing. */
@@ -224,6 +235,7 @@ export function FileTree<Row extends FileTreeRow>({
// resolve a row by this attribute, and neither may land on one that is on its way out.
{...(retained ? {} : { "data-tree-path": row.path, "data-tree-kind": row.kind })}
title={rowTitle?.(row) ?? row.path}
+ aria-label={rowLabel?.(row)}
{...(retained ? {} : { onClick: () => activate(row), onFocus: () => setFocused(row.path) })}
style={{ paddingLeft: TREE_PAD_PX + row.depth * TREE_INDENT_PX }}
className={`flex cursor-pointer select-none items-center gap-1.5 py-1 pr-2 text-sm outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-gray-400/60 ${
diff --git a/packages/web/src/components/ui/icons.tsx b/packages/web/src/components/ui/icons.tsx
index 1202fc98..59f87938 100644
--- a/packages/web/src/components/ui/icons.tsx
+++ b/packages/web/src/components/ui/icons.tsx
@@ -5,7 +5,7 @@
*/
import type { ButtonHTMLAttributes } from "react";
import { S } from "../../lib/strings";
-import { AGENT_GROUP_ICON } from "./group-list";
+import { AGENT_GROUP_ICON, CALENDAR_ICON } from "./group-list";
/** Downward caret on Select / OptionMenu / composer dropdown triggers. Color follows currentColor (callers add text-gray-400). */
export function ChevronDown({ size = 12, className = "" }: { size?: number; className?: string }) {
@@ -380,4 +380,23 @@ export const NAV_ICONS = {
"M7 4h10v5a5 5 0 0 1-10 0V4zM7 5H4v1a3 3 0 0 0 3 3m10-4h3v1a3 3 0 0 1-3 3M12 14v4m-4 0h8",
/** Terminal (a `>_` prompt in a window frame). */
terminal: "M3 5h18v14H3zM7 9l3 3-3 3M13 15h4",
+ /** Company mode's overview (lucide layout-dashboard: four tiles of two heights). */
+ orgOverview:
+ "M4 3h5a1 1 0 0 1 1 1v7a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1zM15 3h5a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1h-5a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1zM15 12h5a1 1 0 0 1 1 1v7a1 1 0 0 1-1 1h-5a1 1 0 0 1-1-1v-7a1 1 0 0 1 1-1zM4 16h5a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1v-3a1 1 0 0 1 1-1z",
+ /** The org chart (lucide network: one box over two, joined by a bus). */
+ orgChart: "M9 3h6v5H9zM2 16h6v5H2zM16 16h6v5h-6zM5 16v-3h14v3M12 13V8",
+ /** The organization calendar: the same calendar the sidebar's time grouping wears. */
+ orgCalendar: CALENDAR_ICON,
+ /** The ticket board (lucide square-kanban: three columns of unequal height in a frame). */
+ orgTickets:
+ "M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zM8 7v7M12 7v4M16 7v9",
+ /** Finance (lucide circle-dollar-sign). */
+ orgFinance:
+ "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8M12 18V6",
+ /** The handbook, the company's knowledge base (lucide book-open: two pages meeting at the spine). */
+ orgHandbook: "M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2zM22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z",
} as const;
+
+/** Company mode (lucide building-2: a tower with wings and windows), the settings rail, the sidebar's organization groups and the collapsed rail's toggle. */
+export const COMPANY_MODE_ICON =
+ "M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2M10 6h4M10 10h4M10 14h4M10 18h4";
diff --git a/packages/web/src/components/ui/segmented.tsx b/packages/web/src/components/ui/segmented.tsx
index 4c6dee87..eee946e7 100644
--- a/packages/web/src/components/ui/segmented.tsx
+++ b/packages/web/src/components/ui/segmented.tsx
@@ -1,11 +1,26 @@
-/** Segmented control (for 2- to 4-way choices like theme/language/messaging channel): small grayscale style. Shared by the sidebar user menu, the login page and the binding editor. */
+/**
+ * Segmented control (for 2- to 4-way choices like theme/language/messaging channel): small
+ * grayscale style. Shared by the sidebar user menu, the login page and the binding editor.
+ *
+ * An option may carry a `badge`: a mini tag pinned at the top-right of its label, for a mark that
+ * qualifies the choice itself rather than reporting a state — company mode's 内测版 tag on the
+ * work-mode switch. It is positioned out of flow, so neither an option's height nor the control's
+ * overall size moves when one appears, and it is hidden from the accessible name; the badge's
+ * `name` is what the option's name gains instead, as ` · <name>`.
+ */
+import type { ReactNode } from "react";
+
export function Segmented<T extends string>({
options,
value,
onChange,
cols = 3,
}: {
- options: ReadonlyArray<{ value: T; label: string }>;
+ options: ReadonlyArray<{
+ value: T;
+ label: string;
+ badge?: { node: ReactNode; name: string };
+ }>;
value: T;
onChange: (v: T) => void;
cols?: 2 | 3 | 4;
@@ -21,13 +36,27 @@ export function Segmented<T extends string>({
key={opt.value}
type="button"
onClick={() => onChange(opt.value)}
+ // An aria-label replaces every descendant in the accessible name, so it is only set
+ // where there is a badge to fold in — otherwise the label's own text is the name.
+ aria-label={opt.badge ? `${opt.label} · ${opt.badge.name}` : undefined}
className={`rounded px-1 py-1 text-xs transition-colors duration-150 ${
value === opt.value
? "bg-white font-medium text-gray-900 shadow-sm dark:bg-gray-600 dark:text-gray-100"
: "text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200"
}`}
>
- {opt.label}
+ {opt.badge ? (
+ <span className="relative inline-block">
+ {opt.label}
+ {/* `left-full` rather than a negative right offset: the tag hangs off the label's
+ right edge whatever it is wide, and never overlaps the word. */}
+ <span aria-hidden className="absolute -top-1.5 left-full">
+ {opt.badge.node}
+ </span>
+ </span>
+ ) : (
+ opt.label
+ )}
</button>
))}
</div>
diff --git a/packages/web/src/components/ui/session-row-menu.tsx b/packages/web/src/components/ui/session-row-menu.tsx
index de015dc9..0aaf296e 100644
--- a/packages/web/src/components/ui/session-row-menu.tsx
+++ b/packages/web/src/components/ui/session-row-menu.tsx
@@ -91,6 +91,14 @@ export function contextMenuActions(canPin: boolean): readonly SessionRowAction[]
: ["rename", "messaging", "archive", "copy", "delete"];
}
+/**
+ * A company desk row's menu (features/company/org-session-groups.tsx). A desk's title and its
+ * lifecycle belong to the organization — the employee names it, hiring and firing open and
+ * close it — so rename, archive, delete and pin are not its reader's to run. What is left is
+ * which Session this is and what it is bound to.
+ */
+export const DESK_ROW_ACTIONS: readonly SessionRowAction[] = ["copy", "messaging"];
+
export interface SessionRowMenuItem {
/** Label in the action's current state, and the icon-only buttons' accessible name. */
label: string;
diff --git a/packages/web/src/components/ui/toast.tsx b/packages/web/src/components/ui/toast.tsx
index 27d8fa79..7a4b8863 100644
--- a/packages/web/src/components/ui/toast.tsx
+++ b/packages/web/src/components/ui/toast.tsx
@@ -9,15 +9,16 @@
* interactive (clicking it dismisses immediately).
*
* Usage: call `toastSuccess("Saved")` / `toastInfo("Already up to date")` /
- * `toastError("Connection failed: ...")` from anywhere, no context needed — a
- * module-level store plus a single `<Toaster />` mounted at the app
- * root is all it takes.
+ * `toastAttention("Two desks share one minute")` / `toastError("Connection
+ * failed: ...")` from anywhere, no context needed — a module-level store plus a
+ * single `<Toaster />` mounted at the app root is all it takes.
*/
import { createPortal } from "react-dom";
import { useStore } from "zustand/react";
import { createStore } from "zustand/vanilla";
-type ToastKind = "success" | "error" | "info";
+/** `attention` is the advisory kind: the write went through, and something about it is worth a look. */
+type ToastKind = "success" | "error" | "info" | "attention";
interface ToastItem {
id: number;
@@ -27,8 +28,13 @@ interface ToastItem {
leaving?: boolean;
}
-/** Display duration: error messages are usually longer and more important to read, so give them more time; info sits in between. */
-const DURATION: Record<ToastKind, number> = { success: 2500, info: 4000, error: 6000 };
+/** Display duration: an error and an advisory both need reading, so they get the longest stay; info sits in between; a plain success is gone as soon as it is seen. */
+const DURATION: Record<ToastKind, number> = {
+ success: 2500,
+ info: 4000,
+ attention: 6000,
+ error: 6000,
+};
const toastStore = createStore<{ items: ToastItem[] }>(() => ({ items: [] }));
let nextId = 1;
@@ -58,6 +64,7 @@ function push(kind: ToastKind, text: string): void {
export const toastSuccess = (text: string): void => push("success", text);
export const toastError = (text: string): void => push("error", text);
export const toastInfo = (text: string): void => push("info", text);
+export const toastAttention = (text: string): void => push("attention", text);
const KIND_CLASS: Record<ToastKind, string> = {
success:
@@ -65,6 +72,8 @@ const KIND_CLASS: Record<ToastKind, string> = {
error:
"border-red-200 bg-red-50 text-red-800 dark:border-red-900 dark:bg-red-950 dark:text-red-200",
info: "border-sky-200 bg-sky-50 text-sky-800 dark:border-sky-900 dark:bg-sky-950 dark:text-sky-200",
+ attention:
+ "border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-200",
};
/** Toast container: mount once at the app root. */
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index bc4db3e9..6885753f 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -23,6 +23,7 @@ import type {
ApprovalMode,
ModelRefDto,
ModelsResponse,
+ SessionInfo,
SessionPatchRequest,
SessionProcessInfo,
SessionStatus,
@@ -41,7 +42,7 @@ import {
humanizeDurationLive,
humanizeTokens,
} from "../../lib/format";
-import { latestConversation } from "../../lib/session-grouping";
+import { latestConversation, withoutOrgSessions } from "../../lib/session-grouping";
import { sessionActivity, sessionBackgroundTasks } from "../../lib/session-activity";
import { noteSessionSeen } from "../../lib/session-seen";
import {
@@ -95,7 +96,7 @@ import { ChatDropRegion } from "./drop-zone";
import { ConversationOutline, OutlineMenuButton, useOutlineRailFit } from "./conversation-outline";
import { DraftView } from "./draft-view";
import { parkActiveDraft } from "./draft-sessions";
-import { sessionForProject, sessionProbeKey } from "./session-project";
+import { resolveRoutedSession, sessionForProject, sessionProbeKey } from "./session-project";
import { CHAT_DEFAULTS_CHANGED_EVENT, chatDefaultsChangedDetail } from "./chat-defaults-event";
import { advanceCostStat, applyUsageFetch, createCostStatHold } from "./header-stats";
import type { CostStatDisplay } from "./header-stats";
@@ -400,7 +401,14 @@ export function ChatPage() {
// below treats the two alike.
const parkedDraftId = parkedDraftIdOf(routeSessionId);
const draft = routeSessionId === DRAFT_SESSION_ID || parkedDraftId !== null;
- const selected = draft ? null : (sessions.find((s) => s.sessionId === routeSessionId) ?? null);
+ /**
+ * The row the direct lookup below produced, kept beside the list: the list is replaced by
+ * every reload, and a row that only a lookup knows about (an organization's desk, a
+ * deep-linked conversation past the fetched pages) would otherwise disappear from under
+ * the open conversation. See resolveRoutedSession.
+ */
+ const [fetchedSession, setFetchedSession] = useState<SessionInfo | null>(null);
+ const selected = draft ? null : resolveRoutedSession(routeSessionId, sessions, fetchedSession);
// New shells start in this conversation's Workspace — its files are what a terminal
// opened here is for. While drafting, the Workspace is the one picked in the draft and
// DraftView publishes it instead (a child effect runs before this one, so this must
@@ -546,10 +554,15 @@ export function ChatPage() {
// menu advises compacting first, since the change invalidates the model's cached
// context). It is still never written through to the Agent config (that stays draft-only).
const turnThinkingLevel = selected?.thinkingLevel ?? "";
+ // The Agent list may not carry this Session's Agent yet (an Agent an organization created
+ // moments ago): the probe below reloads the list, and this effect re-runs once it lands.
+ const selectedAgentKnown =
+ selectedAgentId !== null && agents.some((a) => a.agentId === selectedAgentId);
useEffect(() => {
- if (selectedSessionId && selectedAgentId) setCurrentAgentId(selectedAgentId);
+ if (selectedSessionId && selectedAgentId && selectedAgentKnown)
+ setCurrentAgentId(selectedAgentId);
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [selectedSessionId, selectedAgentId, setCurrentAgentId]);
+ }, [selectedSessionId, selectedAgentId, selectedAgentKnown, setCurrentAgentId]);
// Agents tab AUTO-OPEN (the one automatic tab action): the pure tracker
// (advancePanelTaskScope, unit-tested) brings the agents tab to the front on the CURRENT
@@ -697,8 +710,13 @@ export function ChatPage() {
(res) => {
if (cancelled) return;
const session = sessionForProject(res.session, projectId);
- if (session) addSession(session);
- else setProbeFailedKey(probeKey);
+ if (session) {
+ setFetchedSession(session);
+ addSession(session);
+ // A Session of an Agent the list has not loaded (company mode creates Agents
+ // server-side): fetch the list, or the page has no Agent to render under.
+ if (!agents.some((a) => a.agentId === session.agentId)) void reloadAgents();
+ } else setProbeFailedKey(probeKey);
},
() => {
if (!cancelled) setProbeFailedKey(probeKey);
@@ -732,7 +750,10 @@ export function ChatPage() {
if (selected !== null) return;
// A routed id missing from the paged list isn't gone until the direct lookup fails.
if (routeSessionPending) return;
- const last = latestConversation(sessions);
+ // An organization's desk or ticket Session is never auto-opened: landing in one by default
+ // would put the user inside a conversation the scheduler drives, and company mode's own
+ // groups are where it is reached.
+ const last = latestConversation(withoutOrgSessions(sessions));
navigate(last ? `/chat/${last.sessionId}` : `/chat/${DRAFT_SESSION_ID}`, { replace: true });
}, [sessionsLoading, draft, selected, routeSessionPending, sessions, navigate]);
diff --git a/packages/web/src/features/chat/input-history.ts b/packages/web/src/features/chat/input-history.ts
index a1e7f7a2..d95af8f3 100644
--- a/packages/web/src/features/chat/input-history.ts
+++ b/packages/web/src/features/chat/input-history.ts
@@ -55,7 +55,7 @@ export function buildInputHistory(items: readonly ChatItem[]): string[] {
if (item.sender === "harness") continue;
const parsed = parseUserMessageBody(item.text);
// Background completion notices are harness-written, never typed here either.
- if (!parsed || parsed.scheduled || parsed.backgroundDone) continue;
+ if (!parsed || parsed.scheduled || parsed.orgTrigger || parsed.backgroundDone) continue;
push(parsed.body);
} else if (item.kind === "user_steering") {
push(splitAttachments(item.text).text.trim());
diff --git a/packages/web/src/features/chat/md.tsx b/packages/web/src/features/chat/md.tsx
index c09b63b6..5cd2d5b9 100644
--- a/packages/web/src/features/chat/md.tsx
+++ b/packages/web/src/features/chat/md.tsx
@@ -15,11 +15,16 @@
* KaTeX is held back the same way, for the same reason: `streaming` swaps the rehype stage
* out, so a formula shows its own TeX source until the message settles and is typeset once
* (see NO_REHYPE_PLUGINS in lib/markdown-plugins.ts for the measurements).
+ *
+ * Two optional props open the renderer to a surface with its own nodes — the channel message
+ * body, which keeps `@mentions` as chips — without a second copy of the pipeline drifting from
+ * this one. They only ever ADD to the shared stage and to the maps below; nothing a surface
+ * passes can take the shared plugins away.
*/
import { isValidElement, memo } from "react";
import type { ComponentPropsWithoutRef, ReactNode } from "react";
import ReactMarkdown from "react-markdown";
-import type { Components, ExtraProps } from "react-markdown";
+import type { Components, ExtraProps, Options } from "react-markdown";
import { NO_REHYPE_PLUGINS, REHYPE_PLUGINS, REMARK_PLUGINS } from "../../lib/markdown-plugins";
import { CodeBlock } from "./code-block";
@@ -105,15 +110,34 @@ export const SETTLED_MD_COMPONENTS: Components = SETTLED_COMPONENTS;
export const Md = memo(function Md({
text,
streaming = false,
+ extraPlugins,
+ components,
}: {
text: string;
streaming?: boolean;
+ /**
+ * Remark plugins a surface adds to the shared stage, for a node of its own — the channel
+ * message body adds the pass that turns its `@mentions` into elements. They are appended to
+ * REMARK_PLUGINS rather than replacing it: a renderer that dropped the shared list would end
+ * bare URLs and typeset math differently from every other one, which is the drift
+ * markdown-plugins.ts exists to prevent.
+ */
+ extraPlugins?: NonNullable<Options["remarkPlugins"]>;
+ /**
+ * Element overrides merged over the two maps below, which keep `pre` and `a`. A module
+ * constant, for the same reason those are: react-markdown uses a component as the element
+ * *type*, so a fresh function per render remounts everything it renders.
+ */
+ components?: Components;
}) {
+ const base = streaming ? STREAMING_COMPONENTS : SETTLED_COMPONENTS;
return (
<ReactMarkdown
- remarkPlugins={REMARK_PLUGINS}
+ remarkPlugins={
+ extraPlugins === undefined ? REMARK_PLUGINS : [...REMARK_PLUGINS, ...extraPlugins]
+ }
rehypePlugins={streaming ? NO_REHYPE_PLUGINS : REHYPE_PLUGINS}
- components={streaming ? STREAMING_COMPONENTS : SETTLED_COMPONENTS}
+ components={components === undefined ? base : { ...base, ...components }}
>
{text}
</ReactMarkdown>
diff --git a/packages/web/src/features/chat/message-item.tsx b/packages/web/src/features/chat/message-item.tsx
index 24bfe707..c983c6f3 100644
--- a/packages/web/src/features/chat/message-item.tsx
+++ b/packages/web/src/features/chat/message-item.tsx
@@ -24,6 +24,8 @@ import { CompactionBanner } from "./compaction-banner";
import { McpConnectBanner } from "./mcp-connect-banner";
import { HandoffBanner, ModelSwitchBanner } from "./handoff-banner";
import { ScheduledBanner } from "./scheduled-banner";
+import { OrgTriggerBanner } from "./org-trigger-banner";
+import { parseOrgTriggerMessage } from "./org-trigger";
import { SkillsBanner } from "./skills-banner";
import { AttachedFilesBanner } from "./attached-files-banner";
import { BackgroundDoneBanner } from "./background-done-banner";
@@ -202,12 +204,18 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCo
// Source block for a chat opened by the /model switch: collapsed into a single-line switch notice, clickable to jump back to the source conversation.
const modelSwitch = parseModelSwitchMessage(item.text);
if (modelSwitch) return <ModelSwitchBanner origin={modelSwitch} />;
+ // Source block for an organization trigger (a desk or ticket session's work run):
+ // collapsed into a single-line notice like the scheduled banner, the trigger body
+ // rendered as usual. A message carries at most one origin block, so the chain simply
+ // continues on whatever this leaves.
+ const orgTrigger = parseOrgTriggerMessage(item.text);
+ const afterOrgTrigger = orgTrigger ? orgTrigger.rest : item.text;
// Source block for a scheduled-task trigger: collapsed into a single-line notice, with the task's prompt body rendered as usual (verbatim on the Trace page).
- const scheduled = parseScheduledMessage(item.text);
+ const scheduled = parseScheduledMessage(afterOrgTrigger);
// Source block for a skill invocation: parsing continues on scheduled's remaining body
// (scheduled -> skills, blocks stripped in a chain); a match collapses into a
// "using skill" banner, with the body rendered as usual.
- const afterScheduled = scheduled ? scheduled.rest : item.text;
+ const afterScheduled = scheduled ? scheduled.rest : afterOrgTrigger;
const skills = parseSkillsMessage(afterScheduled);
// Attachment row restoration (last in the chain — these lines trail the body rather than
// prefixing it): for models that don't support images, input images are written to disk
@@ -218,6 +226,7 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCo
const { text, images, files } = splitAttachments(skills ? skills.rest : afterScheduled);
return (
<>
+ {orgTrigger && <OrgTriggerBanner origin={orgTrigger.origin} />}
{scheduled && <ScheduledBanner origin={scheduled.origin} />}
{skills && <SkillsBanner names={skills.skills} />}
{text && (
diff --git a/packages/web/src/features/chat/model-select.tsx b/packages/web/src/features/chat/model-select.tsx
index 98d29175..d17a36a1 100644
--- a/packages/web/src/features/chat/model-select.tsx
+++ b/packages/web/src/features/chat/model-select.tsx
@@ -287,6 +287,9 @@ export function ModelMenuList({
* under the card's own `@container` query, menu right-aligned;
* - "form": the shared FormPicker (full-width Input/Select-styled trigger, menu left-aligned
* under the control), used by every dialog host.
+ *
+ * `emptyLabel` is for the one kind of host where an unpicked model is a decision and not a
+ * gap — the organization dialogs' "Project default"; see the prop.
*/
export function ModelSelect({
models,
@@ -295,6 +298,7 @@ export function ModelSelect({
onChange,
disabled,
variant = "pill",
+ emptyLabel,
}: {
models: ModelInfo[];
/** Currently selected (provider, modelId) pair; null = not yet chosen. */
@@ -304,12 +308,21 @@ export function ModelSelect({
disabled: boolean;
/** Trigger style: the composer's toolbar pill (default), or a dialog form control (see the header comment). */
variant?: "pill" | "form";
+ /**
+ * What the trigger reads while nothing is picked, for a host where "nothing" is itself a
+ * choice rather than an unfinished one — the organization dialogs, where an empty model
+ * means "follow the Project's default". The menu still offers models only, so such a host
+ * carries its own way back to the empty value; here the label is grayed as a placeholder
+ * and the provider logo is dropped, since no provider is being named.
+ */
+ emptyLabel?: string;
}) {
const [open, setOpen] = useState(false);
const current = models.find((m) => sameModelRef(m, value));
+ const unset = value === null && emptyLabel !== undefined;
// Display rule matches the model page's card: display name, or falls back to the upstream id (grouping is already conveyed by the provider logo).
- const label = current ? modelLabel(current) : (value?.modelId ?? "…");
- const logo = (
+ const label = current ? modelLabel(current) : (value?.modelId ?? emptyLabel ?? "…");
+ const logo = unset ? null : (
<ProviderLogo
provider={current?.provider ?? value?.provider ?? "custom"}
className="h-4 w-4 shrink-0"
@@ -335,6 +348,7 @@ export function ModelSelect({
setOpen={setOpen}
leading={logo}
label={label}
+ muted={unset}
title={`${S.chat.chooseModel}:${label}`}
ariaLabel={S.chat.chooseModel}
ariaHaspopup="listbox"
diff --git a/packages/web/src/features/chat/org-trigger-banner.tsx b/packages/web/src/features/chat/org-trigger-banner.tsx
new file mode 100644
index 00000000..a4e7adf8
--- /dev/null
+++ b/packages/web/src/features/chat/org-trigger-banner.tsx
@@ -0,0 +1,36 @@
+/**
+ * Origin hint for a message the organization scheduler sent (the `[org_trigger]` block): the
+ * block is not rendered verbatim; it folds into one line — which organization, what kind of
+ * trigger, the event / message / ticket it names, and the budget line — the same shape as the
+ * scheduled-task banner beside it. The trigger's body renders as usual below.
+ */
+import { S } from "../../lib/strings";
+import { formatDateTime } from "../../lib/format";
+import { Badge } from "../../components/ui/badge";
+import { summarizeOrgTrigger } from "./org-trigger";
+import type { OrgTriggerOrigin } from "./org-trigger";
+
+export function OrgTriggerBanner({ origin }: { origin: OrgTriggerOrigin }) {
+ const t = summarizeOrgTrigger(origin);
+ const kind = S.chat.orgTriggerKinds[t.kind] ?? t.kind;
+ return (
+ <p className="anim-msg my-2 flex w-fit flex-wrap items-center gap-2 rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-xs text-gray-600 dark:border-gray-800 dark:bg-gray-900 dark:text-gray-400">
+ <span>{S.chat.orgTriggerFrom(t.org)}</span>
+ <Badge tone="brand">{kind}</Badge>
+ {t.subject !== null && (
+ <span className="font-mono text-gray-700 dark:text-gray-300">
+ {t.subject}
+ {t.change !== null && ` · ${t.change}`}
+ </span>
+ )}
+ {t.firedAt !== null && (
+ <span className="text-gray-400 dark:text-gray-500">{formatDateTime(t.firedAt)}</span>
+ )}
+ {t.budget !== null && (
+ <span className="text-gray-400 dark:text-gray-500">
+ {S.chat.orgTriggerBudget(t.budget)}
+ </span>
+ )}
+ </p>
+ );
+}
diff --git a/packages/web/src/features/chat/org-trigger.ts b/packages/web/src/features/chat/org-trigger.ts
new file mode 100644
index 00000000..4ec1ffed
--- /dev/null
+++ b/packages/web/src/features/chat/org-trigger.ts
@@ -0,0 +1,50 @@
+/**
+ * The one-line summary of an `[org_trigger]` block (pure, unit tested): what the organization
+ * scheduler sent a desk or ticket session, reduced to the trigger's kind, the one fact that
+ * identifies it (the event, the chat message, the ticket and its change) and the budget line
+ * the scheduler wrote. The banner (org-trigger-banner.tsx) only localizes these.
+ */
+import type { OrgTriggerOrigin } from "@prismshadow/penguin-core/markers";
+
+export { parseOrgTriggerMessage } from "@prismshadow/penguin-core/markers";
+export type { OrgTriggerKind, OrgTriggerOrigin } from "@prismshadow/penguin-core/markers";
+
+export interface OrgTriggerSummary {
+ org: string;
+ kind: OrgTriggerOrigin["kind"];
+ /** The employee's agent id — the block writes `<id>` or `<id> (<title>, reports to <id>)`. */
+ agentId: string;
+ /** The kind-specific identifier: the event name, the message reference, the ticket id — null for `init`. */
+ subject: string | null;
+ /** A ticket notice's change (`assigned`, `blocked`, …); null otherwise. */
+ change: string | null;
+ /** The event's fire time (ISO 8601), for the event kind only. */
+ firedAt: string | null;
+ budget: string | null;
+}
+
+/** The agent id in front of an employee line's optional parenthesis. */
+export function orgTriggerAgentId(employee: string): string {
+ const at = employee.indexOf(" (");
+ return (at === -1 ? employee : employee.slice(0, at)).trim();
+}
+
+export function summarizeOrgTrigger(origin: OrgTriggerOrigin): OrgTriggerSummary {
+ const subject =
+ origin.kind === "event"
+ ? (origin.event ?? null)
+ : origin.kind === "mention"
+ ? (origin.message ?? null)
+ : origin.kind === "ticket_notice" || origin.kind === "ticket_work"
+ ? (origin.ticket ?? null)
+ : null;
+ return {
+ org: origin.org,
+ kind: origin.kind,
+ agentId: orgTriggerAgentId(origin.employee),
+ subject,
+ change: origin.kind === "ticket_notice" ? (origin.change ?? null) : null,
+ firedAt: origin.kind === "event" ? (origin.firedAt ?? null) : null,
+ budget: origin.budget ?? null,
+ };
+}
diff --git a/packages/web/src/features/chat/session-project.ts b/packages/web/src/features/chat/session-project.ts
index 29220182..9b24215d 100644
--- a/packages/web/src/features/chat/session-project.ts
+++ b/packages/web/src/features/chat/session-project.ts
@@ -1,5 +1,27 @@
import type { SessionInfo } from "@prismshadow/penguin-server/api";
+/**
+ * The Session the route names: the loaded list's row when it holds one, otherwise the row a
+ * direct lookup produced.
+ *
+ * Both halves are load-bearing. The list is paged, so a deep-linked conversation may sit
+ * beyond the fetched pages; and it is replaced wholesale by every reload, which drops a row
+ * that was merged in by such a lookup — an organization's desk, opened from the org chart,
+ * is exactly that row, and losing it again is what left the conversation behind the skeleton
+ * for good. The list row still WINS where it exists: it is the one the status and title
+ * events keep current.
+ */
+export function resolveRoutedSession(
+ sessionId: string | null,
+ sessions: readonly SessionInfo[],
+ fetched: SessionInfo | null,
+): SessionInfo | null {
+ if (sessionId === null) return null;
+ const row = sessions.find((s) => s.sessionId === sessionId);
+ if (row !== undefined) return row;
+ return fetched !== null && fetched.sessionId === sessionId ? fetched : null;
+}
+
/** Return a probed Session only when it belongs to the Project currently shown by the UI. */
export function sessionForProject(session: SessionInfo, projectId: string): SessionInfo | null {
return session.projectId === projectId ? session : null;
diff --git a/packages/web/src/features/chat/user-message-body.ts b/packages/web/src/features/chat/user-message-body.ts
index 3c6d89b1..ef11b519 100644
--- a/packages/web/src/features/chat/user-message-body.ts
+++ b/packages/web/src/features/chat/user-message-body.ts
@@ -1,7 +1,7 @@
/**
* Shared "what did the user actually write" extraction for a user_text item, mirroring
- * MessageItem's parse chain (handoff / model-switch → scheduled → skills → attachment
- * lines) without any rendering. Harness-injected inputs never reach this parse: both
+ * MessageItem's parse chain (handoff / model-switch → org trigger → scheduled → skills →
+ * attachment lines) without any rendering. Harness-injected inputs never reach this parse: both
* callers skip them on the item's `sender` stamp. Input history and the conversation outline both
* need this reduction, and each re-implementing the chain would drift from the renderer the
* moment a new protocol block is added — this module is the single non-rendering copy.
@@ -13,6 +13,7 @@ import {
parseScheduledMessage,
} from "./agent-handoff";
import { parseSkillsMessage } from "./skill-use";
+import { parseOrgTriggerMessage } from "./org-trigger";
import { splitAttachments } from "../../lib/attachments";
export interface UserMessageBody {
@@ -20,6 +21,8 @@ export interface UserMessageBody {
body: string;
/** True when the message was injected by a scheduled-task trigger rather than typed into the composer. */
scheduled: boolean;
+ /** True when the organization scheduler injected the message (an `[org_trigger]` block): a work run's input, never typed. */
+ orgTrigger?: boolean;
/**
* True when the message is a background completion notice ([background_task_done] block);
* `body` is then the harness-written report text after the block — a readable outline
@@ -41,12 +44,15 @@ export function parseUserMessageBody(raw: string): UserMessageBody | null {
if (backgroundDone) {
return { body: backgroundDone.rest.trim(), scheduled: false, backgroundDone: true };
}
- const scheduled = parseScheduledMessage(raw);
- const afterScheduled = scheduled ? scheduled.rest : raw;
+ const orgTrigger = parseOrgTriggerMessage(raw);
+ const afterOrgTrigger = orgTrigger ? orgTrigger.rest : raw;
+ const scheduled = parseScheduledMessage(afterOrgTrigger);
+ const afterScheduled = scheduled ? scheduled.rest : afterOrgTrigger;
const skills = parseSkillsMessage(afterScheduled);
const { text } = splitAttachments(skills ? skills.rest : afterScheduled);
return {
body: text.trim(),
scheduled: scheduled !== null,
+ ...(orgTrigger !== null ? { orgTrigger: true } : {}),
};
}
diff --git a/packages/web/src/features/company/beta-badge.tsx b/packages/web/src/features/company/beta-badge.tsx
new file mode 100644
index 00000000..13d59815
--- /dev/null
+++ b/packages/web/src/features/company/beta-badge.tsx
@@ -0,0 +1,69 @@
+/**
+ * Company mode says it is a beta, in the two shapes that fact takes in the shell.
+ *
+ * The tag — a mini 内测版 / Beta mark riding at the top-right of 「公司」 in the 开发 | 公司
+ * work-mode switch, which is the one control that names the mode itself and is in view on
+ * every page of both modes. A superscript rather than a `Badge`: it qualifies the word it
+ * sits on instead of reporting a state, so it must not read as a status mark, and at that
+ * size it must not push the switch's two options around either — segmented.tsx pins it out
+ * of flow and folds its text into the option's accessible name.
+ *
+ * The notice — the sentence a person gets the first time they switch this browser into the
+ * mode (state/company.tsx's `setWorkMode`), and the once-only decision behind it. The flag
+ * lives in localStorage rather than in the user's preferences because it is about this
+ * browser having shown a toast, not about the user: a second browser is a second first time,
+ * and a preferences round trip would decide it too late to toast on the click that caused it.
+ */
+import { S } from "../../lib/strings";
+
+/** The localStorage key remembering that this browser has shown the beta notice. */
+export const BETA_NOTICE_KEY = "penguin.companyBetaNoticeShown";
+
+/** Minimal storage surface (the subset of localStorage used here); tests inject an in-memory one. */
+export interface BetaNoticeStorage {
+ getItem(key: string): string | null;
+ setItem(key: string, value: string): void;
+}
+
+/**
+ * Whether the beta notice is still owed in this browser.
+ *
+ * Storage that is missing or refuses to answer (a Node test with no localStorage, a browser
+ * with site data blocked) means no notice rather than one on every switch: the sentence also
+ * stands under the admin's master switch and in the docs, so the cost of skipping the toast
+ * is smaller than the cost of repeating it forever.
+ */
+export function shouldShowBetaNotice(storage?: BetaNoticeStorage): boolean {
+ try {
+ return (storage ?? localStorage).getItem(BETA_NOTICE_KEY) !== "1";
+ } catch {
+ return false;
+ }
+}
+
+/** Remembers that the notice has been shown; a storage that refuses only costs a repeat. */
+export function markBetaNoticeShown(storage?: BetaNoticeStorage): void {
+ try {
+ (storage ?? localStorage).setItem(BETA_NOTICE_KEY, "1");
+ } catch {
+ /* best-effort persistence (quota limits / private browsing) */
+ }
+}
+
+/**
+ * The tag itself: the smallest legible rung, in the muted ink and border that keep it from
+ * reading as a status mark. The px size is deliberate — this is a superscript over a
+ * `text-xs` option, and there is no rung below `text-xs` to step down to. Its host hides it
+ * from the accessible name, so the tooltip is the only thing it says on its own, and it is a
+ * `title` because the switch it rides on carries no `Tooltip` of any kind.
+ */
+export function BetaBadge() {
+ return (
+ <span
+ title={S.company.betaTitle}
+ className="whitespace-nowrap rounded-sm border border-gray-300 px-0.5 py-px text-[9px] font-medium leading-none text-gray-500 dark:border-gray-600 dark:text-gray-400"
+ >
+ {S.company.beta}
+ </span>
+ );
+}
diff --git a/packages/web/src/features/company/budget-input.ts b/packages/web/src/features/company/budget-input.ts
new file mode 100644
index 00000000..c84f7dbe
--- /dev/null
+++ b/packages/web/src/features/company/budget-input.ts
@@ -0,0 +1,60 @@
+/**
+ * Budgets on screen versus budgets on the wire.
+ *
+ * A budget is a MONTHLY cap — one calendar month in the organization's timezone — and the
+ * server both stores it (in `org_chart.yaml`) and returns it in USD. The reader, though,
+ * chooses the currency this App writes money in (state/theme.ts), so a budget box speaks that
+ * currency and these helpers do the two conversions around it: what was typed becomes USD on
+ * save, and what is stored becomes the reader's currency when the box is filled in.
+ *
+ * The rate is the App's one fixed rate (USD_TO_CNY) and a stored amount is rounded to cents,
+ * so an amount typed in CNY and read back can land a fraction of a fen away from what was
+ * typed. That is why a box in CNY says underneath it what it is actually going to store.
+ */
+import { USD_TO_CNY } from "../../state/theme";
+import type { Currency } from "../../state/theme";
+import type { Strings } from "../../lib/strings";
+
+/** The symbol each currency writes its amounts with (the same two lib/format spells). */
+const CURRENCY_SYMBOL: Record<Currency, string> = { USD: "$", CNY: "¥" };
+
+/** Cents: the precision a stored budget is kept at, and what both directions round to. */
+function cents(value: number): number {
+ return Math.round(value * 100) / 100;
+}
+
+/**
+ * What a budget box holds, as the server stores it: null for an empty box (unbounded), the
+ * amount in USD otherwise.
+ *
+ * Text that is not a non-negative number also reads as an empty box. Every caller validates
+ * first (`isBudgetText`) and never reaches that branch — silently lifting a cap because of a
+ * typo is exactly what the validation is there to prevent.
+ */
+export function toStoredUsd(text: string, currency: Currency): number | null {
+ const t = text.trim();
+ if (t === "") return null;
+ const typed = Number(t);
+ if (!Number.isFinite(typed) || typed < 0) return null;
+ return cents(currency === "CNY" ? typed / USD_TO_CNY : typed);
+}
+
+/**
+ * The other direction: a stored USD amount as the text a box starts with, in the reader's
+ * currency. An unbounded budget starts the box empty.
+ */
+export function fromStoredUsd(usd: number | null | undefined, currency: Currency): string {
+ if (usd == null || !Number.isFinite(usd)) return "";
+ return String(cents(currency === "CNY" ? usd * USD_TO_CNY : usd));
+}
+
+/** True while a budget box holds something usable: empty (unbounded), or a non-negative number. */
+export function isBudgetText(text: string): boolean {
+ const t = text.trim();
+ return t === "" || Number(t) >= 0;
+}
+
+/** The unit that follows a budget box: the reader's currency, and the period the cap covers. */
+export function unitLabel(currency: Currency, strings: Strings): string {
+ return strings.company.budgetUnit(CURRENCY_SYMBOL[currency]);
+}
diff --git a/packages/web/src/features/company/calendar-geom.ts b/packages/web/src/features/company/calendar-geom.ts
new file mode 100644
index 00000000..14cfecf8
--- /dev/null
+++ b/packages/web/src/features/company/calendar-geom.ts
@@ -0,0 +1,319 @@
+/**
+ * The organization calendar's geometry (pure, unit tested in Node): the day grid of a month,
+ * the seven days of a week, the visible range of each view, stepping the anchor date, the
+ * expansion of each event's `startAt` / `period` / `endAt` into the instances that fall in a
+ * range, where an instance sits in a day column and which lane it takes when instances
+ * overlap, the cadence an event's `period` reads as in the legend, and how a legend entry
+ * draws under the employee filter. Everything is computed
+ * on local calendar days through the Date API's local accessors, so a test built with
+ * `new Date(y, m, d)` reads the same in every timezone.
+ */
+import type { OrgCalendarItem, OrgCalendarOutcome } from "@prismshadow/penguin-server/api";
+import { packToolLanes } from "../traces/lane-packing";
+
+export type CalendarView = "month" | "week" | "day";
+
+export const DAY_MS = 24 * 60 * 60 * 1000;
+
+const pad2 = (n: number): string => (n < 10 ? `0${n}` : `${n}`);
+
+/** `yyyy-mm-dd` of a local calendar day. */
+export function dayKey(ms: number): string {
+ const d = new Date(ms);
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
+}
+
+/** Local midnight of the day containing `ms`. */
+export function startOfDay(ms: number): number {
+ const d = new Date(ms);
+ return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
+}
+
+/** `n` calendar days after the day containing `ms`, at local midnight (DST-safe: built from calendar parts, not by adding 24h). */
+export function addDays(ms: number, n: number): number {
+ const d = new Date(ms);
+ return new Date(d.getFullYear(), d.getMonth(), d.getDate() + n).getTime();
+}
+
+/** Local midnight of the Monday on or before `ms` (the week starts on Monday, as the weekday labels do). */
+export function startOfWeek(ms: number): number {
+ const d = new Date(startOfDay(ms));
+ // getDay: 0 = Sunday. Monday-based offset: Sunday counts as the sixth day of its week.
+ const offset = (d.getDay() + 6) % 7;
+ return addDays(d.getTime(), -offset);
+}
+
+export interface GridDay {
+ key: string;
+ dayStartMs: number;
+ /** Whether the day belongs to the month on display (leading and trailing days of the grid do not). */
+ inMonth: boolean;
+}
+
+/**
+ * Monday-based rows of seven days covering the month of `anchorMs`: as many rows as the month
+ * needs (four to six), so a month never trails a whole row of the next one.
+ */
+export function monthGrid(anchorMs: number): GridDay[][] {
+ const a = new Date(anchorMs);
+ const first = new Date(a.getFullYear(), a.getMonth(), 1).getTime();
+ const month = a.getMonth();
+ const daysInMonth = new Date(a.getFullYear(), a.getMonth() + 1, 0).getDate();
+ const lead = (new Date(first).getDay() + 6) % 7;
+ const rowCount = Math.ceil((lead + daysInMonth) / 7);
+ let cursor = startOfWeek(first);
+ const rows: GridDay[][] = [];
+ for (let r = 0; r < rowCount; r++) {
+ const row: GridDay[] = [];
+ for (let c = 0; c < 7; c++) {
+ row.push({
+ key: dayKey(cursor),
+ dayStartMs: cursor,
+ inMonth: new Date(cursor).getMonth() === month,
+ });
+ cursor = addDays(cursor, 1);
+ }
+ rows.push(row);
+ }
+ return rows;
+}
+
+/** The seven days of the week containing `anchorMs`, Monday first. */
+export function weekDays(anchorMs: number): GridDay[] {
+ const start = startOfWeek(anchorMs);
+ return Array.from({ length: 7 }, (_, i) => {
+ const dayStartMs = addDays(start, i);
+ return { key: dayKey(dayStartMs), dayStartMs, inMonth: true };
+ });
+}
+
+/** The visible range of a view around its anchor: `[startMs, endMs)`. */
+export function viewRange(
+ anchorMs: number,
+ view: CalendarView,
+): { startMs: number; endMs: number } {
+ if (view === "day") {
+ const startMs = startOfDay(anchorMs);
+ return { startMs, endMs: addDays(startMs, 1) };
+ }
+ if (view === "week") {
+ const startMs = startOfWeek(anchorMs);
+ return { startMs, endMs: addDays(startMs, 7) };
+ }
+ const grid = monthGrid(anchorMs);
+ const startMs = grid[0]![0]!.dayStartMs;
+ return { startMs, endMs: addDays(grid[grid.length - 1]![6]!.dayStartMs, 1) };
+}
+
+/** The anchor one step (`delta` of ±1) forward or back in a view: a day, a week, or a calendar month (clamped to the target month's length). */
+export function shiftAnchor(anchorMs: number, view: CalendarView, delta: number): number {
+ if (view === "day") return addDays(anchorMs, delta);
+ if (view === "week") return addDays(anchorMs, 7 * delta);
+ const d = new Date(anchorMs);
+ const first = new Date(d.getFullYear(), d.getMonth() + delta, 1);
+ const lastDay = new Date(first.getFullYear(), first.getMonth() + 1, 0).getDate();
+ return new Date(first.getFullYear(), first.getMonth(), Math.min(d.getDate(), lastDay)).getTime();
+}
+
+/** A fixed interval in `30m` / `12h` / `7d` form as milliseconds; null when it is not one (the server's parsePeriod rule). */
+export function parsePeriodMs(raw: string | undefined): number | null {
+ if (raw === undefined) return null;
+ const m = /^(\d+)([mhd])$/.exec(raw.trim());
+ if (!m) return null;
+ const n = Number(m[1]);
+ if (!Number.isInteger(n) || n <= 0) return null;
+ const unit = m[2] === "m" ? 60_000 : m[2] === "h" ? 3_600_000 : DAY_MS;
+ return n * unit;
+}
+
+export interface EventInstance {
+ event: OrgCalendarItem;
+ atMs: number;
+ /** Stable key: `<agentId>/<name>@<atMs>`. */
+ key: string;
+ /** The instance is in the past against `nowMs`. */
+ past: boolean;
+ /**
+ * What the scheduler did with this instance, when it can be told: only the most recent
+ * evaluation is recorded (`lastFiredAt` / `lastOutcome`), so the instance it names carries
+ * that outcome and every other past instance carries null — "past", with no claim.
+ */
+ outcome: OrgCalendarOutcome | null;
+}
+
+/** Instances per event within a range: the runaway guard for a tiny period over a long range. */
+export const MAX_INSTANCES_PER_EVENT = 400;
+
+/**
+ * Every instance of every event inside `[startMs, endMs)`, oldest first. A one-off event
+ * (no period) yields at most its `startAt`; a periodic one yields `startAt + k·period` up to
+ * its `endAt`. The first k is computed rather than walked so a years-old daily event costs
+ * nothing before the range. An unparseable `startAt` or `period` yields nothing — the page
+ * lists such events under "invalid" from the server's own verdict.
+ */
+export function expandEvents(
+ events: readonly OrgCalendarItem[],
+ startMs: number,
+ endMs: number,
+ nowMs: number,
+): EventInstance[] {
+ const out: EventInstance[] = [];
+ for (const event of events) {
+ const startAt = Date.parse(event.startAt);
+ if (!Number.isFinite(startAt)) continue;
+ const period = event.period === undefined ? null : parsePeriodMs(event.period);
+ if (event.period !== undefined && period === null) continue;
+ const endAt = event.endAt === undefined ? Number.POSITIVE_INFINITY : Date.parse(event.endAt);
+ const lastFired = event.lastFiredAt === undefined ? null : Date.parse(event.lastFiredAt);
+ const push = (atMs: number) => {
+ // The recorded evaluation belongs to the instance it is nearest to (within half a period, or a minute for a one-off).
+ const tolerance = period === null ? 60_000 : period / 2;
+ const isLast =
+ lastFired !== null && Number.isFinite(lastFired) && Math.abs(lastFired - atMs) <= tolerance;
+ out.push({
+ event,
+ atMs,
+ key: `${event.agentId}/${event.name}@${atMs}`,
+ past: atMs <= nowMs,
+ outcome: isLast ? (event.lastOutcome ?? null) : null,
+ });
+ };
+ if (period === null) {
+ if (startAt >= startMs && startAt < endMs && startAt <= endAt) push(startAt);
+ continue;
+ }
+ let k = startAt < startMs ? Math.ceil((startMs - startAt) / period) : 0;
+ let count = 0;
+ for (;;) {
+ const atMs = startAt + k * period;
+ if (atMs >= endMs || atMs > endAt || count >= MAX_INSTANCES_PER_EVENT) break;
+ push(atMs);
+ k += 1;
+ count += 1;
+ }
+ }
+ out.sort((a, b) => a.atMs - b.atMs || a.key.localeCompare(b.key));
+ return out;
+}
+
+/** Instances bucketed by local day key, each day's list in time order. */
+export function instancesByDay(instances: readonly EventInstance[]): Map<string, EventInstance[]> {
+ const out = new Map<string, EventInstance[]>();
+ for (const i of instances) {
+ const key = dayKey(i.atMs);
+ const list = out.get(key);
+ if (list) list.push(i);
+ else out.set(key, [i]);
+ }
+ return out;
+}
+
+/** Where an instant sits in its day, as a fraction of the day (0 = midnight, 0.5 = noon) for the day and week columns. */
+export function dayFraction(atMs: number): number {
+ const d = new Date(atMs);
+ return (d.getHours() * 60 + d.getMinutes()) / (24 * 60);
+}
+
+/** `HH:mm` of an instant, local time. */
+export function timeLabel(atMs: number): string {
+ const d = new Date(atMs);
+ return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
+}
+
+/** Local `datetime-local` input value (`yyyy-mm-ddThh:mm`) of an ISO instant; "" when unparseable or absent. */
+export function toLocalInput(iso: string | undefined): string {
+ if (iso === undefined) return "";
+ const ms = Date.parse(iso);
+ if (!Number.isFinite(ms)) return "";
+ const d = new Date(ms);
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}T${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
+}
+
+/**
+ * How an event recurs, read from `period` and the wall-clock time of `startAt`: the legend
+ * says "every day at 09:00" rather than "1d". Whole days become day / week cadences with the
+ * time of day; sub-day periods keep their unit; no period is a one-off at its instant.
+ */
+export type Cadence =
+ | { kind: "once"; atMs: number }
+ | { kind: "minutes"; n: number }
+ | { kind: "hours"; n: number }
+ | { kind: "days"; n: number; time: string }
+ | { kind: "weeks"; n: number; time: string }
+ | { kind: "invalid" };
+
+export function cadenceOf(event: Pick<OrgCalendarItem, "startAt" | "period">): Cadence {
+ const startAt = Date.parse(event.startAt);
+ if (!Number.isFinite(startAt)) return { kind: "invalid" };
+ if (event.period === undefined) return { kind: "once", atMs: startAt };
+ const period = parsePeriodMs(event.period);
+ if (period === null) return { kind: "invalid" };
+ const time = timeLabel(startAt);
+ if (period % DAY_MS === 0) {
+ const days = period / DAY_MS;
+ if (days % 7 === 0) return { kind: "weeks", n: days / 7, time };
+ return { kind: "days", n: days, time };
+ }
+ if (period % 3_600_000 === 0) return { kind: "hours", n: period / 3_600_000 };
+ return { kind: "minutes", n: period / 60_000 };
+}
+
+/** Where a chip sits among the chips it overlaps: lane `lane` of `lanes` side by side. */
+export interface ChipSlot<T> {
+ item: T;
+ lane: number;
+ lanes: number;
+}
+
+/**
+ * Side-by-side placement for the day and week columns: each instance occupies `slotMs` from
+ * its instant, instances whose slots overlap form a cluster, and inside a cluster they pack
+ * greedily into lanes (the trace timeline's packer). A chip's width is then `1 / lanes` of
+ * its cluster, so a lone 14:00 event stays full width while three 09:00 events share the row.
+ */
+export function chipLanes<T extends { atMs: number; key: string }>(
+ instances: readonly T[],
+ slotMs: number,
+): ChipSlot<T>[] {
+ const sorted = [...instances].sort((a, b) => a.atMs - b.atMs || a.key.localeCompare(b.key));
+ const out: ChipSlot<T>[] = [];
+ let cluster: T[] = [];
+ let clusterEnd = Number.NEGATIVE_INFINITY;
+ const flush = () => {
+ if (cluster.length === 0) return;
+ const lanes = packToolLanes(
+ cluster.map((item) => ({
+ name: "chip",
+ startMs: item.atMs,
+ endMs: item.atMs + slotMs,
+ item,
+ })),
+ );
+ lanes.forEach((lane, i) => {
+ for (const span of lane.spans) out.push({ item: span.item, lane: i, lanes: lanes.length });
+ });
+ cluster = [];
+ };
+ for (const item of sorted) {
+ if (item.atMs >= clusterEnd) flush();
+ cluster.push(item);
+ clusterEnd = Math.max(clusterEnd, item.atMs + slotMs);
+ }
+ flush();
+ out.sort((a, b) => a.item.atMs - b.item.atMs || a.item.key.localeCompare(b.item.key));
+ return out;
+}
+
+/**
+ * How a legend entry draws under the employee filter. The legend doubles as the filter, so the
+ * state it is in has to be legible without hovering it: the employee being shown alone is
+ * pressed, and every other one is struck through, which is what says the others were switched
+ * off rather than simply not picked. With no filter nobody is struck — an unfiltered calendar
+ * shows every employee, and striking them all would say the opposite.
+ */
+export type LegendState = "pressed" | "struck" | "plain";
+
+export function legendState(filter: string, agentId: string): LegendState {
+ if (filter === "") return "plain";
+ return filter === agentId ? "pressed" : "struck";
+}
diff --git a/packages/web/src/features/company/calendar-page.tsx b/packages/web/src/features/company/calendar-page.tsx
new file mode 100644
index 00000000..3b95dee5
--- /dev/null
+++ b/packages/web/src/features/company/calendar-page.tsx
@@ -0,0 +1,1182 @@
+/**
+ * The organization calendar: month / week / day views over every employee's events
+ * (geometry in calendar-geom.ts), events coloured per employee from the categorical
+ * palette, a legend that names each employee's cadence and doubles as the employee filter,
+ * and one dialog for creating and editing an event — the scheduled-task dialog minus its
+ * target fields, with the employee as a select. The grid is always on screen: a skeleton of
+ * it while the first fetch is out, the empty grid with a one-line hint when the organization
+ * has no events yet — dismissible, and repeated in the page's "?" so it stays reachable —
+ * the grid plus an error strip when a refetch fails. A month cell shows a few chips and folds
+ * the rest into a button that opens the whole day in a popover rather than the create dialog.
+ * Past instances carry the outcome the scheduler recorded; every write confirms first, and
+ * reports back whatever the server has to say about the rota.
+ *
+ * An empty slot — a month cell, an hour row — is itself the control that creates there, and it
+ * says so: a real button (CREATE_SLOT_CLASS) that tints with the theme's accent and spells out
+ * 「新建日程」 while it is hovered or focused. The button is laid under the chips so an event
+ * still opens its own event; its 「新建日程」 hint is lifted back above them, on a line of the
+ * cell reserved for it, so a day that already has events still says what its empty space does.
+ */
+import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
+import type { ReactNode } from "react";
+import { createPortal } from "react-dom";
+import { useNavigate } from "react-router";
+import type {
+ OrgCalendarItem,
+ OrgCalendarOutcome,
+ OrgChartResponse,
+} from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { formatDateTime } from "../../lib/format";
+import { useDocumentTitle } from "../../lib/use-document-title";
+import { employeeColor } from "../../lib/category-colors";
+import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
+import { toneInk, toneStrip } from "../../lib/tone";
+import type { Tone } from "../../lib/tone";
+import { useAuth } from "../../state/auth";
+import { useCompany } from "../../state/company";
+import { Button } from "../../components/ui/button";
+import { Segmented } from "../../components/ui/segmented";
+import { Select } from "../../components/ui/select";
+import { Switch } from "../../components/ui/switch";
+import { Input, Textarea } from "../../components/ui/input";
+import { Modal } from "../../components/ui/modal";
+import { ConfirmModal } from "../../components/ui/confirm-modal";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { CloseIcon } from "../../components/ui/icons";
+import { Skeleton } from "../../components/ui/skeleton";
+import { usePortalPanel } from "../../components/ui/use-portal-panel";
+import { toastAttention, toastError, toastSuccess } from "../../components/ui/toast";
+import { OrgPage, useOrg } from "./org-layout";
+import {
+ cadenceOf,
+ chipLanes,
+ dayFraction,
+ dayKey,
+ expandEvents,
+ instancesByDay,
+ legendState,
+ monthGrid,
+ shiftAnchor,
+ timeLabel,
+ toLocalInput,
+ viewRange,
+ weekDays,
+} from "./calendar-geom";
+import type { Cadence, CalendarView, EventInstance, GridDay } from "./calendar-geom";
+import { dismissHint, hintKey, isHintDismissed } from "./page-hints";
+
+const PREV_ICON = "M15 18 9 12l6-6";
+const NEXT_ICON = "m9 18 6-6-6-6";
+
+const OUTCOME_TONE: Record<OrgCalendarOutcome, Tone> = {
+ fired: "success",
+ queued: "attention",
+ paused: "muted",
+ missed: "danger",
+ error: "danger",
+};
+
+/** The mark a recorded outcome leaves on its instance: a check, an hourglass, a pause, a cross, an alert. */
+const OUTCOME_ICON: Record<OrgCalendarOutcome, string> = {
+ fired: "M5 13l4 4L19 7",
+ queued: "M6 3h12M6 21h12M8 3v3.5L12 10l4-3.5V3M8 21v-3.5L12 14l4 3.5V21",
+ paused: "M9 5v14M15 5v14",
+ missed: "M18 6 6 18M6 6l12 12",
+ error: "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM12 8v4m0 4h.01",
+};
+
+/** Hour rows of the day and week columns (px per hour): a day is 24 × this tall. */
+const HOUR_PX = 44;
+/** The footprint of a chip in those columns: half an hour, the smallest slot a line of text fits at this row height. */
+const CHIP_SLOT_MS = 30 * 60_000;
+/** The columns open scrolled to 06:00 and show sixteen hours; the night is reached by scrolling. */
+const VISIBLE_FROM_HOUR = 6;
+const VISIBLE_HOURS = 16;
+/** Chips shown per month cell before the rest fold into a count. */
+const MONTH_CELL_CHIPS = 3;
+/**
+ * Width of the day popover, in px rather than a `w-` class: usePortalPanel clamps the panel's
+ * left edge against this number, and the app's root font size is a user setting (16 / 18 / 20
+ * px), so a rem-based class and a px constant would agree only at one of the three tiers.
+ */
+const DAY_PANEL_WIDTH = 240;
+
+/** The plus that leads the "new event" hint an empty slot spells out while the pointer is on it. */
+const PLUS_ICON = "M12 5v14M5 12h14";
+
+/**
+ * The create control that fills an empty calendar slot — a month cell, an hour row of the week
+ * and day columns. It is a real button, so it takes focus and the keyboard, and it lies *under*
+ * the chips drawn in the same cell: a chip is a button too, and interactive content may not nest
+ * inside a button.
+ *
+ * Resting it is invisible. Hovered or focused it wears a low-alpha wash of the theme's accent
+ * with a hairline inset ring — the `gray-50` it used to hover with was all but unreadable on a
+ * white page, and the accent is a CSS variable, so the tint follows whichever accent the user
+ * picked instead of pinning one hue. With nobody hired there is no event to create, so the slot
+ * is disabled and drops out of the pointer's way entirely — no tint, no tooltip, nothing to say.
+ * Positioning is the call site's (`inset-0` for a month cell, `inset-x-0` plus a top/height for an
+ * hour row), and so is where the hint sits inside it.
+ */
+const CREATE_SLOT_CLASS =
+ "group/slot absolute rounded-sm transition-colors duration-150 hover:bg-[var(--accent-bg)]/[0.07] hover:ring-1 hover:ring-inset hover:ring-[var(--accent-bg)]/25 focus-visible:bg-[var(--accent-bg)]/[0.07] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--accent-bg)]/40 disabled:pointer-events-none";
+
+/**
+ * What the slot under the pointer would do, spelled out inside it: a plus and 「新建日程」. It is
+ * hidden until its own slot is hovered or focused — a chip covering part of the slot takes the
+ * pointer itself, so the hint only ever answers for the bare part of a slot.
+ *
+ * It draws on the top layer (`z-10`), above the chips its own slot lies under, because a slot
+ * with events in it is exactly where the hint was needed and exactly where it used to be
+ * covered. That it never intercepts a click is `pointer-events-none`, not the stacking order:
+ * a click anywhere over the hint still reaches whatever is under it.
+ *
+ * The call site positions it — and so has to position it, since `z-10` only applies to a
+ * positioned element — and says how it stays readable over what it now covers: a month cell
+ * reserves its last line for it, an hour row centres it over the chips on a translucent
+ * backdrop.
+ */
+function CreateSlotHint({ className = "" }: { className?: string }) {
+ return (
+ <span
+ className={`pointer-events-none z-10 inline-flex items-center ${ICON_GAP.tight} text-[10px] leading-4 text-gray-500 opacity-0 transition-opacity duration-150 group-hover/slot:opacity-100 group-focus-visible/slot:opacity-100 dark:text-gray-400 ${className}`}
+ >
+ <GlyphIcon d={PLUS_ICON} size={ICON_SIZE.inlineGlyph} />
+ {S.company.calendar.create}
+ </span>
+ );
+}
+
+interface FormState {
+ /** Editing an existing event (its file is fixed): agentId + name; null when creating. */
+ editing: { agentId: string; name: string } | null;
+ agentId: string;
+ name: string;
+ title: string;
+ prompt: string;
+ enabled: boolean;
+ startAt: string;
+ endAt: string;
+ period: string;
+}
+
+function cadenceLabel(c: Cadence): string {
+ const t = S.company.calendar.cadence;
+ switch (c.kind) {
+ case "once":
+ return t.once;
+ case "minutes":
+ return t.minutes(c.n);
+ case "hours":
+ return t.hours(c.n);
+ case "days":
+ return c.n === 1 ? t.daily(c.time) : t.days(c.n, c.time);
+ case "weeks":
+ return c.n === 1 ? t.weekly(c.time) : t.weeks(c.n, c.time);
+ default:
+ return t.invalid;
+ }
+}
+
+const hourLabel = (h: number) => `${h < 10 ? "0" : ""}${h}:00`;
+
+export function CalendarPage() {
+ const { projectId, orgId, org } = useOrg();
+ const navigate = useNavigate();
+ const company = useCompany();
+ const { user } = useAuth();
+ useDocumentTitle(org ? `${org.name} · ${S.nav.org.calendar}` : S.nav.org.calendar);
+ const [events, setEvents] = useState<OrgCalendarItem[] | null>(null);
+ const [invalidFiles, setInvalidFiles] = useState<
+ Array<{ agentId: string; name: string; error: string }>
+ >([]);
+ const [chart, setChart] = useState<OrgChartResponse | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [view, setView] = useState<CalendarView>("month");
+ const [anchor, setAnchor] = useState(() => Date.now());
+ const [now, setNow] = useState(() => Date.now());
+ const [employeeFilter, setEmployeeFilter] = useState("");
+ const [form, setForm] = useState<FormState | null>(null);
+ const [fieldErrors, setFieldErrors] = useState<
+ Partial<Record<"name" | "prompt" | "startAt" | "agentId", string>>
+ >({});
+ const [confirmSave, setConfirmSave] = useState(false);
+ const [deleting, setDeleting] = useState<{ agentId: string; name: string } | null>(null);
+ const [busy, setBusy] = useState(false);
+ const scrollRef = useRef<HTMLDivElement>(null);
+ // The empty-calendar note goes away for good once read; the page's "?" carries the same
+ // sentence. The key holds the organization, so switching to another one — which does not
+ // unmount this page — re-reads the dismissal instead of carrying the last answer over.
+ const emptyHintKey = hintKey(user?.userId ?? null, projectId, orgId, "calendar");
+ const [hintDismissed, setHintDismissed] = useState(() => isHintDismissed(emptyHintKey));
+ useEffect(() => {
+ setHintDismissed(isHintDismissed(emptyHintKey));
+ }, [emptyHintKey]);
+
+ const load = useCallback(async () => {
+ try {
+ const [cal, ch] = await Promise.all([
+ api.listOrgCalendar(projectId, orgId),
+ api.getOrgChart(projectId, orgId),
+ ]);
+ setEvents(cal.events);
+ setInvalidFiles(cal.invalidFiles);
+ setChart(ch);
+ setError(null);
+ } catch (e) {
+ setError(apiErrorText(e));
+ }
+ }, [projectId, orgId]);
+ // A fired slot arrives as an org_run event; a budget pause flips `paused` on every event of that employee.
+ const { runs, budget } = company.versions;
+ useEffect(() => {
+ void load();
+ }, [load, runs, budget]);
+
+ // The "now" the past marks and the time line read: a minute's precision is all they show.
+ useEffect(() => {
+ const t = setInterval(() => setNow(Date.now()), 60_000);
+ return () => clearInterval(t);
+ }, []);
+
+ const loaded = events !== null;
+ // The day and week columns open at the working hours (the hour label sits astride its
+ // line, so the scroll stops a few pixels short of it); the night above is one scroll away.
+ useEffect(() => {
+ const el = scrollRef.current;
+ if (el && view !== "month") el.scrollTop = VISIBLE_FROM_HOUR * HOUR_PX - 10;
+ }, [view, loaded]);
+
+ const employees = chart?.employees ?? [];
+ const names = new Map(employees.map((e) => [e.agentId, e.name]));
+ /** Colour index by chart order, so an employee keeps its hue across days and views. */
+ const colorOf = (agentId: string) => {
+ const i = employees.findIndex((e) => e.agentId === agentId);
+ return employeeColor(i === -1 ? employees.length : i);
+ };
+
+ const range = viewRange(anchor, view);
+ const instances = useMemo(() => {
+ const list = (events ?? []).filter(
+ (e) => employeeFilter === "" || e.agentId === employeeFilter,
+ );
+ return expandEvents(list, range.startMs, range.endMs, now);
+ }, [events, employeeFilter, range.startMs, range.endMs, now]);
+ const byDay = useMemo(() => instancesByDay(instances), [instances]);
+
+ const openCreate = (atMs?: number) => {
+ setFieldErrors({});
+ setForm({
+ editing: null,
+ agentId: employeeFilter || (employees[0]?.agentId ?? ""),
+ name: "",
+ title: "",
+ prompt: "",
+ enabled: true,
+ startAt: toLocalInput(new Date(atMs ?? Date.now()).toISOString()),
+ endAt: "",
+ period: "",
+ });
+ };
+ const openEdit = (ev: OrgCalendarItem) => {
+ setFieldErrors({});
+ setForm({
+ editing: { agentId: ev.agentId, name: ev.name },
+ agentId: ev.agentId,
+ name: ev.name,
+ title: ev.title ?? "",
+ prompt: ev.prompt,
+ enabled: ev.enabled,
+ startAt: toLocalInput(ev.startAt),
+ endAt: toLocalInput(ev.endAt),
+ period: ev.period ?? "",
+ });
+ };
+ const set = (patch: Partial<FormState>) => setForm((f) => (f === null ? f : { ...f, ...patch }));
+
+ const validate = (): boolean => {
+ if (form === null) return false;
+ const next: typeof fieldErrors = {};
+ if (!form.agentId) next.agentId = S.common.requiredField;
+ if (!form.name.trim()) next.name = S.common.requiredField;
+ if (!form.prompt.trim()) next.prompt = S.common.requiredField;
+ if (!form.startAt) next.startAt = S.common.requiredField;
+ setFieldErrors(next);
+ return Object.keys(next).length === 0;
+ };
+
+ const save = async () => {
+ if (form === null) return;
+ setBusy(true);
+ try {
+ const body = {
+ ...(form.title.trim() ? { title: form.title.trim() } : {}),
+ prompt: form.prompt,
+ enabled: form.enabled,
+ startAt: new Date(form.startAt).toISOString(),
+ ...(form.period.trim() ? { period: form.period.trim() } : {}),
+ ...(form.endAt ? { endAt: new Date(form.endAt).toISOString() } : {}),
+ };
+ const written =
+ form.editing !== null
+ ? await api.updateOrgCalendarEvent(
+ projectId,
+ orgId,
+ form.editing.agentId,
+ form.editing.name,
+ body,
+ )
+ : await api.createOrgCalendarEvent(projectId, orgId, {
+ ...body,
+ agentId: form.agentId,
+ name: form.name.trim(),
+ });
+ toastSuccess(S.common.saved);
+ // Rota advice, not a failure: the event is stored either way, so it rides in a second
+ // toast rather than turning the save into an error.
+ const warnings = written.warnings ?? [];
+ if (warnings.length > 0) {
+ toastAttention(`${S.company.calendar.warningsPrefix} · ${warnings.join(" · ")}`);
+ }
+ setConfirmSave(false);
+ setForm(null);
+ void load();
+ } catch (e) {
+ setConfirmSave(false);
+ toastError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const remove = async () => {
+ if (deleting === null) return;
+ setBusy(true);
+ try {
+ await api.deleteOrgCalendarEvent(projectId, orgId, deleting.agentId, deleting.name);
+ setDeleting(null);
+ setForm(null);
+ void load();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ /** Open the desk session an instance's run went to (a past, fired instance). */
+ const openDesk = async (agentId: string) => {
+ try {
+ const desk = await api.getOrgDesk(projectId, orgId, agentId);
+ navigate(`/chat/${desk.sessionId}`);
+ } catch (e) {
+ toastError(apiErrorText(e));
+ }
+ };
+
+ const todayKey = dayKey(now);
+
+ /**
+ * One event instance as a chip. Employee colour carries identity; the recorded outcome (on
+ * the one instance it belongs to) rides at the end as a toned glyph; a past instance fades,
+ * and a disabled or paused event is struck through so the chip says it will not fire.
+ *
+ * It opens its event and nothing else: wherever a chip is drawn, the cell's create button is
+ * a *sibling* laid under it rather than an ancestor, so the click never reaches the create
+ * form and no handler here has to stop it.
+ */
+ const chip = (i: EventInstance, opts: { block?: boolean; onOpen?: () => void } = {}) => {
+ const color = colorOf(i.event.agentId);
+ const outcome = i.outcome;
+ const label = i.event.title ?? i.event.name;
+ const inert = !i.event.enabled || i.event.paused;
+ const title = [
+ `${timeLabel(i.atMs)} · ${label}`,
+ names.get(i.event.agentId) ?? i.event.agentId,
+ outcome !== null
+ ? (S.company.calendarOutcomes[outcome] ?? outcome)
+ : i.past
+ ? S.company.calendar.past
+ : null,
+ !i.event.enabled ? S.company.calendar.disabledNote : null,
+ i.event.paused ? S.company.calendar.pausedNote : null,
+ ]
+ .filter((p) => p !== null)
+ .join(" · ");
+ return (
+ <button
+ key={i.key}
+ type="button"
+ title={title}
+ onClick={() => {
+ opts.onOpen?.();
+ openEdit(i.event);
+ }}
+ className={`flex min-w-0 items-center gap-1 rounded px-1 text-left text-[11px] leading-5 transition-opacity ${color.chip} ${
+ opts.block ? "h-full w-full" : "w-full"
+ } ${i.past && outcome === null ? "opacity-60" : ""} ${
+ inert ? "line-through decoration-1 opacity-60" : ""
+ }`}
+ >
+ <span className="shrink-0 font-mono tabular-nums">{timeLabel(i.atMs)}</span>
+ <span className="min-w-0 flex-1 truncate">{label}</span>
+ {outcome !== null && (
+ <span className={`inline-flex shrink-0 items-center ${toneInk[OUTCOME_TONE[outcome]]}`}>
+ <GlyphIcon d={OUTCOME_ICON[outcome]} size={ICON_SIZE.inlineGlyph} />
+ <span className="sr-only">{S.company.calendarOutcomes[outcome] ?? outcome}</span>
+ </span>
+ )}
+ </button>
+ );
+ };
+
+ const heading =
+ view === "month"
+ ? S.company.calendar.monthTitle(
+ new Date(anchor).getFullYear(),
+ new Date(anchor).getMonth() + 1,
+ )
+ : view === "week"
+ ? `${dayKey(range.startMs)} – ${dayKey(range.endMs - 1)}`
+ : `${dayKey(anchor)} ${S.company.calendar.weekdays[(new Date(anchor).getDay() + 6) % 7] ?? ""}`;
+
+ const toolbar = (
+ <>
+ <Segmented
+ options={[
+ { value: "month" as const, label: S.company.calendar.month },
+ { value: "week" as const, label: S.company.calendar.week },
+ { value: "day" as const, label: S.company.calendar.day },
+ ]}
+ value={view}
+ onChange={setView}
+ cols={3}
+ />
+ <Button
+ variant="primary"
+ size="sm"
+ disabled={employees.length === 0}
+ onClick={() => openCreate()}
+ >
+ {S.company.calendar.create}
+ </Button>
+ </>
+ );
+
+ /**
+ * A month cell: the day number, up to three chips, the rest folded into a button that opens
+ * the whole day. Creating at 09:00 is the cell's own full-bleed button, laid under that
+ * content (CREATE_SLOT_CLASS) — the cell IS the control, but it cannot *contain* the chips,
+ * which are buttons themselves. The content above it is inert to the pointer so the create
+ * button keeps the whole cell, and each chip takes its pointer events back: a click on an
+ * event opens that event, and only the bare cell creates. The chips stop one line short of
+ * the bottom, which is the line the hint draws on, above them.
+ */
+ const monthCell = (day: GridDay) => {
+ const list = byDay.get(day.key) ?? [];
+ const shown = list.slice(0, MONTH_CELL_CHIPS);
+ const isToday = day.key === todayKey;
+ const createMs = day.dayStartMs + 9 * 3_600_000;
+ const weekday = S.company.calendar.weekdays[(new Date(day.dayStartMs).getDay() + 6) % 7] ?? "";
+ const createLabel = S.company.calendar.createAt(`${day.key} 09:00`);
+ return (
+ <div
+ key={day.key}
+ className={`relative min-h-24 border-r border-gray-100 p-1 last:border-r-0 dark:border-gray-800 ${
+ day.inMonth ? "" : "bg-gray-50/60 text-gray-400 dark:bg-gray-900/40 dark:text-gray-600"
+ }`}
+ >
+ <button
+ type="button"
+ title={createLabel}
+ aria-label={createLabel}
+ disabled={employees.length === 0}
+ onClick={() => openCreate(createMs)}
+ className={`${CREATE_SLOT_CLASS} inset-0`}
+ >
+ <CreateSlotHint className="absolute inset-x-0 bottom-1 justify-center" />
+ </button>
+ {/* The last line of the cell belongs to the hint: the chips stop above it (pb-5), so
+ the hint has a line of its own to draw on however full the day is. */}
+ <div className="pointer-events-none relative pb-5">
+ <p className="mb-1 flex h-5 items-center">
+ <span
+ className={`inline-flex h-5 min-w-5 items-center justify-center rounded-full px-1 text-[11px] tabular-nums ${
+ isToday
+ ? "bg-[var(--accent-bg)] font-semibold text-[var(--accent-fg)]"
+ : day.inMonth
+ ? "text-gray-600 dark:text-gray-300"
+ : "text-gray-400 dark:text-gray-600"
+ }`}
+ >
+ {new Date(day.dayStartMs).getDate()}
+ </span>
+ </p>
+ <div className="space-y-0.5">
+ {shown.map((i) => (
+ <span key={i.key} className="pointer-events-auto block">
+ {chip(i)}
+ </span>
+ ))}
+ {list.length > shown.length && (
+ <span className="pointer-events-auto block">
+ <DayOverflow
+ hidden={list.length - shown.length}
+ total={list.length}
+ dateLabel={`${day.key} ${weekday}`}
+ onOpenDay={() => {
+ setAnchor(day.dayStartMs);
+ setView("day");
+ }}
+ >
+ {(close) => list.map((i) => chip(i, { onOpen: close }))}
+ </DayOverflow>
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ };
+
+ /**
+ * A day column of the week and day views: hour rows that create on click — each a real button
+ * that names the hour it would create at and spells out 「新建日程」 while it is under the
+ * pointer — and chips placed by time and packed into lanes. The chips are siblings drawn after
+ * the rows, so they take their own clicks; the hint rises back over them on its own layer,
+ * reading off a translucent backdrop rather than off a chip.
+ */
+ const timeColumn = (day: GridDay) => {
+ const slots = chipLanes(byDay.get(day.key) ?? [], CHIP_SLOT_MS);
+ const chipHeight = (CHIP_SLOT_MS / 3_600_000) * HOUR_PX - 2;
+ const isToday = day.key === todayKey;
+ return (
+ <div
+ key={day.key}
+ className={`relative border-l border-gray-100 dark:border-gray-800 ${
+ isToday ? "bg-[var(--accent-bg)]/[0.03]" : ""
+ }`}
+ style={{ height: HOUR_PX * 24 }}
+ >
+ {Array.from({ length: 24 }, (_, h) => {
+ const createLabel = S.company.calendar.createAt(`${day.key} ${hourLabel(h)}`);
+ return (
+ <button
+ key={h}
+ type="button"
+ title={createLabel}
+ aria-label={createLabel}
+ disabled={employees.length === 0}
+ className={`${CREATE_SLOT_CLASS} inset-x-0 flex items-center justify-center border-t border-gray-100 dark:border-gray-800`}
+ style={{ top: h * HOUR_PX, height: HOUR_PX }}
+ onClick={() => openCreate(day.dayStartMs + h * 3_600_000)}
+ >
+ {/* An hour row has no spare line to reserve, so the hint reads over the chips on
+ a wash of the page behind it. */}
+ <CreateSlotHint className="relative rounded bg-white/85 px-1 dark:bg-gray-900/85" />
+ </button>
+ );
+ })}
+ {isToday && (
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-x-0 z-10 flex items-center"
+ style={{ top: dayFraction(now) * HOUR_PX * 24 - 1 }}
+ >
+ <span className="-ml-1 h-2 w-2 rounded-full bg-[var(--accent-bg)]" />
+ <span className="h-0.5 flex-1 bg-[var(--accent-bg)]" />
+ </div>
+ )}
+ {slots.map(({ item, lane, lanes }) => (
+ <div
+ key={item.key}
+ className="absolute"
+ style={{
+ top: dayFraction(item.atMs) * HOUR_PX * 24 + 1,
+ height: chipHeight,
+ left: `calc(${(lane / lanes) * 100}% + 2px)`,
+ width: `calc(${100 / lanes}% - 4px)`,
+ }}
+ >
+ {chip(item, { block: true })}
+ </div>
+ ))}
+ </div>
+ );
+ };
+
+ /** The week and day views share one frame: a day header, then the scrolling hour grid with its gutter. */
+ const timeGrid = (days: GridDay[]) => {
+ const cols = days.length === 1 ? "grid-cols-[3rem_1fr]" : "grid-cols-[3rem_repeat(7,1fr)]";
+ return (
+ <div className="overflow-x-auto">
+ <div
+ className={`${days.length === 1 ? "" : "min-w-[52rem]"} overflow-hidden rounded-md border border-gray-200 dark:border-gray-800`}
+ >
+ <div
+ className={`grid ${cols} border-b border-gray-200 text-[11px] font-medium text-gray-500 dark:border-gray-800 dark:text-gray-400`}
+ >
+ <div />
+ {days.map((day) => {
+ const d = new Date(day.dayStartMs);
+ const isToday = day.key === todayKey;
+ return (
+ <div
+ key={day.key}
+ className={`flex items-center gap-1.5 border-l border-gray-100 px-2 py-1.5 dark:border-gray-800 ${
+ isToday ? "font-semibold text-gray-900 dark:text-gray-100" : ""
+ }`}
+ >
+ {S.company.calendar.weekdays[(d.getDay() + 6) % 7]}
+ <span
+ className={`inline-flex h-5 min-w-5 items-center justify-center rounded-full px-1 tabular-nums ${
+ isToday ? "bg-[var(--accent-bg)] text-[var(--accent-fg)]" : ""
+ }`}
+ >
+ {d.getDate()}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ <div
+ ref={scrollRef}
+ className="overflow-y-auto"
+ style={{ height: VISIBLE_HOURS * HOUR_PX }}
+ >
+ <div className={`grid ${cols}`}>
+ <div className="relative" style={{ height: HOUR_PX * 24 }}>
+ {Array.from({ length: 24 }, (_, h) => (
+ <span
+ key={h}
+ className="absolute right-2 font-mono text-[10px] tabular-nums text-gray-400 dark:text-gray-500"
+ style={{ top: h * HOUR_PX - 6 }}
+ >
+ {h === 0 ? "" : hourLabel(h)}
+ </span>
+ ))}
+ </div>
+ {days.map(timeColumn)}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+ };
+
+ const grid =
+ view === "month" ? (
+ <div className="overflow-x-auto">
+ <div className="min-w-[44rem] overflow-hidden rounded-md border border-gray-200 dark:border-gray-800">
+ <div className="grid grid-cols-7 border-b border-gray-200 text-[11px] font-medium text-gray-500 dark:border-gray-800 dark:text-gray-400">
+ {S.company.calendar.weekdays.map((w) => (
+ <div key={w} className="px-2 py-1.5">
+ {w}
+ </div>
+ ))}
+ </div>
+ {monthGrid(anchor).map((row, r) => (
+ <div
+ key={r}
+ className="grid grid-cols-7 border-b border-gray-100 last:border-b-0 dark:border-gray-800"
+ >
+ {row.map(monthCell)}
+ </div>
+ ))}
+ </div>
+ </div>
+ ) : view === "week" ? (
+ timeGrid(weekDays(anchor))
+ ) : (
+ timeGrid([{ key: dayKey(anchor), dayStartMs: range.startMs, inMonth: true }])
+ );
+
+ const editingEvent =
+ form?.editing != null
+ ? (events ?? []).find(
+ (e) => e.agentId === form.editing?.agentId && e.name === form.editing?.name,
+ )
+ : undefined;
+
+ return (
+ <OrgPage title={S.nav.org.calendar} info={S.company.calendar.info} actions={toolbar} wide>
+ {/* Navigation row: previous / today / next, the heading, and the employee filter. */}
+ <div className="mb-3 flex flex-wrap items-center gap-2">
+ <Button
+ size="icon"
+ variant="ghost"
+ title={S.company.calendar.prev}
+ aria-label={S.company.calendar.prev}
+ onClick={() => setAnchor((a) => shiftAnchor(a, view, -1))}
+ >
+ <GlyphIcon d={PREV_ICON} size={ICON_SIZE.iconButton} />
+ </Button>
+ <Button size="sm" onClick={() => setAnchor(Date.now())}>
+ {S.company.calendar.today}
+ </Button>
+ <Button
+ size="icon"
+ variant="ghost"
+ title={S.company.calendar.next}
+ aria-label={S.company.calendar.next}
+ onClick={() => setAnchor((a) => shiftAnchor(a, view, 1))}
+ >
+ <GlyphIcon d={NEXT_ICON} size={ICON_SIZE.iconButton} />
+ </Button>
+ <span className="text-sm font-semibold tabular-nums">{heading}</span>
+ <div className="ml-auto w-48">
+ <Select
+ size="sm"
+ aria-label={S.company.calendar.filterEmployee}
+ value={employeeFilter}
+ onChange={(e) => setEmployeeFilter(e.target.value)}
+ >
+ <option value="">{S.company.calendar.allEmployees}</option>
+ {employees.map((e) => (
+ <option key={e.agentId} value={e.agentId}>
+ {e.name}
+ </option>
+ ))}
+ </Select>
+ </div>
+ </div>
+
+ {/* Legend: one entry per employee in the chart's colour order, naming its cadence; a click
+ filters to it, and strikes through everyone it just switched off. */}
+ {employees.length > 0 && (
+ <div className="mb-3 flex flex-wrap gap-x-1 gap-y-1 text-[11px]">
+ {employees.map((e) => {
+ const own = (events ?? []).filter((ev) => ev.agentId === e.agentId);
+ const cadences = own.map(
+ (ev) => `${ev.title ?? ev.name} ${cadenceLabel(cadenceOf(ev))}`,
+ );
+ const shown = cadences.slice(0, 2);
+ const rest = cadences.length - shown.length;
+ const state = legendState(employeeFilter, e.agentId);
+ const active = state === "pressed";
+ const struck = state === "struck";
+ return (
+ <button
+ key={e.agentId}
+ type="button"
+ title={
+ active ? S.company.calendar.allEmployees : S.company.calendar.legendFilter(e.name)
+ }
+ aria-pressed={active}
+ onClick={() => setEmployeeFilter(active ? "" : e.agentId)}
+ className={`inline-flex max-w-full items-center gap-1.5 rounded-md px-1.5 py-0.5 text-left transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${
+ active ? "bg-gray-100 dark:bg-gray-800" : struck ? "line-through" : ""
+ }`}
+ >
+ <span
+ className={`h-2 w-2 shrink-0 rounded-full ${colorOf(e.agentId).dot} ${struck ? "opacity-40" : ""}`}
+ />
+ <span
+ className={
+ struck
+ ? "text-gray-400 dark:text-gray-500"
+ : "font-medium text-gray-700 dark:text-gray-200"
+ }
+ >
+ {e.name}
+ </span>
+ <span
+ className={`truncate ${struck ? "text-gray-400 dark:text-gray-500" : "text-gray-500 dark:text-gray-400"}`}
+ title={cadences.join(" · ")}
+ >
+ {cadences.length === 0
+ ? S.company.calendar.legendEmpty
+ : `${shown.join(" · ")}${rest > 0 ? ` +${rest}` : ""}`}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ )}
+
+ {error !== null && (
+ <div
+ className={`mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border px-3 py-2 text-xs ${toneStrip.danger}`}
+ >
+ <span>{S.company.calendar.loadFailed(error)}</span>
+ <Button size="sm" onClick={() => void load()}>
+ {S.common.retry}
+ </Button>
+ </div>
+ )}
+
+ {events !== null && events.length === 0 && invalidFiles.length === 0 && !hintDismissed && (
+ <div
+ className={`mb-3 flex items-center gap-2 rounded-md border px-3 py-2 text-xs ${toneStrip.muted}`}
+ >
+ <span className="min-w-0 flex-1">{S.company.calendar.emptyHint}</span>
+ <Button
+ size="icon"
+ variant="ghost"
+ className="shrink-0"
+ title={S.company.calendar.dismissHint}
+ aria-label={S.company.calendar.dismissHint}
+ onClick={() => {
+ dismissHint(emptyHintKey);
+ setHintDismissed(true);
+ }}
+ >
+ <CloseIcon />
+ </Button>
+ </div>
+ )}
+
+ {events === null && error === null ? <CalendarSkeleton view={view} /> : grid}
+
+ {invalidFiles.length > 0 && (
+ <div className={`mt-4 rounded-md border px-3 py-2 text-xs ${toneStrip.danger}`}>
+ <p className="mb-1 font-medium">{S.company.calendar.invalidFiles}</p>
+ <ul className="space-y-0.5 font-mono">
+ {invalidFiles.map((f) => (
+ <li key={`${f.agentId}/${f.name}`}>
+ {f.agentId}/{f.name}: {f.error}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+
+ {/* Create / edit dialog: the scheduled-task form minus its target, the employee as a select. */}
+ <Modal
+ open={form !== null}
+ title={
+ form?.editing != null
+ ? S.company.calendar.editTitle(form.name)
+ : S.company.calendar.createTitle
+ }
+ onClose={() => setForm(null)}
+ widthClass="sm:max-w-lg"
+ footer={
+ <>
+ {form?.editing != null && (
+ <Button
+ size="sm"
+ variant="danger"
+ className="mr-auto"
+ disabled={busy}
+ onClick={() => setDeleting(form.editing)}
+ >
+ {S.company.calendar.delete}
+ </Button>
+ )}
+ <Button size="sm" onClick={() => setForm(null)} disabled={busy}>
+ {S.common.cancel}
+ </Button>
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={busy}
+ onClick={() => {
+ if (validate()) setConfirmSave(true);
+ }}
+ >
+ {form?.editing != null ? S.common.save : S.common.create}
+ </Button>
+ </>
+ }
+ >
+ {form !== null && (
+ <div className="space-y-3">
+ {editingEvent !== undefined && (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-500 dark:text-gray-400">
+ {editingEvent.nextFireAt !== undefined && (
+ <span>
+ {S.company.calendar.nextFire}{" "}
+ <span className="font-mono tabular-nums">
+ {formatDateTime(editingEvent.nextFireAt)}
+ </span>
+ </span>
+ )}
+ {editingEvent.lastFiredAt !== undefined && (
+ <span className="inline-flex items-center gap-1">
+ {S.company.calendar.lastFired}{" "}
+ <span className="font-mono tabular-nums">
+ {formatDateTime(editingEvent.lastFiredAt)}
+ </span>
+ {editingEvent.lastOutcome !== undefined && (
+ <span className={toneInk[OUTCOME_TONE[editingEvent.lastOutcome]]}>
+ {S.company.calendarOutcomes[editingEvent.lastOutcome] ??
+ editingEvent.lastOutcome}
+ </span>
+ )}
+ {editingEvent.lastOutcome === "fired" && (
+ <button
+ type="button"
+ className="underline"
+ onClick={() => void openDesk(editingEvent.agentId)}
+ >
+ {S.company.openDesk}
+ </button>
+ )}
+ </span>
+ )}
+ {editingEvent.paused && (
+ <span className={toneInk.attention}>{S.company.calendar.pausedNote}</span>
+ )}
+ {editingEvent.invalidReason !== undefined && (
+ <span className={toneInk.danger}>{editingEvent.invalidReason}</span>
+ )}
+ </div>
+ )}
+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
+ <Select
+ size="sm"
+ label={S.company.calendar.employee}
+ required
+ value={form.agentId}
+ disabled={form.editing !== null}
+ {...(fieldErrors.agentId !== undefined ? { error: fieldErrors.agentId } : {})}
+ onChange={(e) => set({ agentId: e.target.value })}
+ >
+ {employees.map((e) => (
+ <option key={e.agentId} value={e.agentId}>
+ {e.name}
+ </option>
+ ))}
+ </Select>
+ <Input
+ size="sm"
+ label={S.company.calendar.name}
+ required
+ hint={S.company.calendar.nameHint}
+ {...(fieldErrors.name !== undefined ? { error: fieldErrors.name } : {})}
+ value={form.name}
+ disabled={form.editing !== null}
+ onChange={(e) => set({ name: e.target.value })}
+ className="font-mono"
+ placeholder="daily_sweep"
+ />
+ </div>
+ <Input
+ size="sm"
+ label={S.common.name}
+ value={form.title}
+ onChange={(e) => set({ title: e.target.value })}
+ />
+ <Textarea
+ label={S.company.calendar.prompt}
+ required
+ size="sm"
+ rows={4}
+ hint={S.company.calendar.promptHint}
+ {...(fieldErrors.prompt !== undefined ? { error: fieldErrors.prompt } : {})}
+ value={form.prompt}
+ onChange={(e) => set({ prompt: e.target.value })}
+ />
+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
+ <Input
+ size="sm"
+ label={S.company.calendar.startAt}
+ required
+ type="datetime-local"
+ hint={S.company.calendar.staggerHint}
+ {...(fieldErrors.startAt !== undefined ? { error: fieldErrors.startAt } : {})}
+ value={form.startAt}
+ onChange={(e) => set({ startAt: e.target.value })}
+ className="font-mono"
+ />
+ <Input
+ size="sm"
+ label={S.company.calendar.period}
+ value={form.period}
+ hint={S.company.calendar.periodHint}
+ onChange={(e) => set({ period: e.target.value })}
+ className="font-mono"
+ placeholder="1d"
+ />
+ <Input
+ size="sm"
+ label={S.company.calendar.endAt}
+ type="datetime-local"
+ value={form.endAt}
+ onChange={(e) => set({ endAt: e.target.value })}
+ className="font-mono"
+ />
+ <label className="flex items-center gap-2 self-end pb-1.5 text-xs text-gray-600 dark:text-gray-300">
+ <Switch checked={form.enabled} onChange={(v) => set({ enabled: v })} />
+ {S.company.calendar.enabled}
+ </label>
+ </div>
+ </div>
+ )}
+ </Modal>
+ <ConfirmModal
+ open={confirmSave}
+ title={S.common.confirmSaveTitle}
+ tone="primary"
+ confirmLabel={S.common.save}
+ busy={busy}
+ onClose={() => (busy ? undefined : setConfirmSave(false))}
+ onConfirm={() => void save()}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {S.company.calendar.saveConfirm(form?.name ?? "")}
+ </p>
+ </ConfirmModal>
+ <ConfirmModal
+ open={deleting !== null}
+ title={S.company.calendar.delete}
+ confirmLabel={S.common.delete}
+ busy={busy}
+ onClose={() => (busy ? undefined : setDeleting(null))}
+ onConfirm={() => void remove()}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {S.company.calendar.deleteConfirm(deleting?.name ?? "")}
+ </p>
+ </ConfirmModal>
+ </OrgPage>
+ );
+}
+
+/**
+ * The chips a month cell could not fit, behind the count that stands for them: a button that
+ * opens the day — every chip of it in time order, plus a link into the day view. It sits over
+ * the cell's create button rather than inside it, so reading "3 more" never opens the create
+ * dialog.
+ *
+ * The panel is portaled to document.body and placed by usePortalPanel, which also closes it on
+ * an outside click, on Esc (captured, so an enclosing dialog stays open), and on a scroll or a
+ * resize that moves the trigger. A chip inside it closes the panel before opening its event.
+ */
+function DayOverflow({
+ hidden,
+ total,
+ dateLabel,
+ onOpenDay,
+ children,
+}: {
+ /** How many chips the cell could not show — what the trigger counts. */
+ hidden: number;
+ /** How many the day holds in all — what the panel lists, and how tall it is expected to be. */
+ total: number;
+ /** The day the panel heads with, as the day view names it ("2026-09-08 Tue"). */
+ dateLabel: string;
+ onOpenDay: () => void;
+ /** The day's chips; `close` puts the panel away as one of them opens its event. */
+ children: (close: () => void) => ReactNode;
+}) {
+ const [open, setOpen] = useState(false);
+ const panelId = useId();
+ const { triggerRef, panelRef, position } = usePortalPanel({
+ open,
+ onClose: () => setOpen(false),
+ // A chip row is 20px tall; the header and the panel's own padding add about 40.
+ estimatedHeight: total * 22 + 40,
+ panelWidth: DAY_PANEL_WIDTH,
+ });
+ const close = () => setOpen(false);
+ const label = S.company.calendar.moreEventsExpand(hidden);
+ return (
+ <>
+ <button
+ ref={triggerRef}
+ type="button"
+ title={label}
+ aria-label={label}
+ aria-expanded={open}
+ aria-controls={panelId}
+ onClick={() => setOpen((v) => !v)}
+ className="block w-full rounded px-1 text-left text-[10px] text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-600 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-300"
+ >
+ {S.company.calendar.moreEvents(hidden)}
+ </button>
+ {open &&
+ position &&
+ createPortal(
+ <div
+ ref={panelRef}
+ id={panelId}
+ role="group"
+ aria-label={dateLabel}
+ style={{
+ position: "fixed",
+ top: position.topPx,
+ bottom: position.bottomPx,
+ left: position.left,
+ width: DAY_PANEL_WIDTH,
+ }}
+ className="anim-pop z-[60] flex max-h-[70vh] max-w-[calc(100vw-2rem)] flex-col rounded-md border border-gray-200 bg-white shadow-lg dark:border-gray-700 dark:bg-gray-900"
+ >
+ <div className="flex items-center justify-between gap-2 border-b border-gray-100 px-2 py-1.5 dark:border-gray-800">
+ <span className="truncate text-[11px] font-medium tabular-nums text-gray-700 dark:text-gray-200">
+ {dateLabel}
+ </span>
+ <button
+ type="button"
+ onClick={() => {
+ close();
+ onOpenDay();
+ }}
+ className="shrink-0 text-[11px] text-gray-500 underline-offset-2 transition-colors duration-150 hover:text-gray-900 hover:underline dark:text-gray-400 dark:hover:text-gray-100"
+ >
+ {S.company.calendar.openDay}
+ </button>
+ </div>
+ <div className="space-y-0.5 overflow-y-auto p-1">{children(close)}</div>
+ </div>,
+ document.body,
+ )}
+ </>
+ );
+}
+
+/** The grid's shape while the first fetch is out: the same frame, cells of placeholder instead of days. */
+function CalendarSkeleton({ view }: { view: CalendarView }) {
+ if (view === "month") {
+ return (
+ <div className="overflow-x-auto">
+ <div className="min-w-[44rem] overflow-hidden rounded-md border border-gray-200 dark:border-gray-800">
+ <div className="grid grid-cols-7 border-b border-gray-200 dark:border-gray-800">
+ {Array.from({ length: 7 }, (_, i) => (
+ <div key={i} className="px-2 py-2">
+ <Skeleton className="h-3 w-8" />
+ </div>
+ ))}
+ </div>
+ {Array.from({ length: 5 }, (_, r) => (
+ <div
+ key={r}
+ className="grid grid-cols-7 border-b border-gray-100 last:border-b-0 dark:border-gray-800"
+ >
+ {Array.from({ length: 7 }, (_, c) => (
+ <div
+ key={c}
+ className="min-h-24 space-y-1 border-r border-gray-100 p-1.5 last:border-r-0 dark:border-gray-800"
+ >
+ <Skeleton className="h-3 w-4" />
+ {(r + c) % 3 === 0 && <Skeleton className="h-4 w-full" />}
+ </div>
+ ))}
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+ }
+ return (
+ <div className="overflow-hidden rounded-md border border-gray-200 dark:border-gray-800">
+ <div className="flex gap-4 border-b border-gray-200 px-14 py-2 dark:border-gray-800">
+ {Array.from({ length: view === "week" ? 7 : 1 }, (_, i) => (
+ <Skeleton key={i} className="h-3 w-12" />
+ ))}
+ </div>
+ <div className="space-y-px p-2" style={{ height: VISIBLE_HOURS * HOUR_PX }}>
+ {Array.from({ length: VISIBLE_HOURS }, (_, i) => (
+ <div key={i} className="flex items-start gap-3" style={{ height: HOUR_PX }}>
+ <Skeleton className="h-2.5 w-8" />
+ {i % 4 === 1 && <Skeleton className="h-5 w-40" />}
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/features/company/canvas-view.ts b/packages/web/src/features/company/canvas-view.ts
new file mode 100644
index 00000000..43991be4
--- /dev/null
+++ b/packages/web/src/features/company/canvas-view.ts
@@ -0,0 +1,125 @@
+/**
+ * The org chart canvas's view arithmetic (pure, unit tested). The drawing is painted once at
+ * its natural size and placed by a single transform, so a view is three numbers: where the
+ * drawing's top-left corner sits inside the frame, and the scale it is drawn at (the layer's
+ * `transform-origin` is `0 0`, which is what makes the two compose in this order).
+ *
+ * Zooming is anchored: whatever sits under the pointer must still sit under it afterwards,
+ * which is `translate' = pointer − (pointer − translate) · factor`. Panning adds a pointer
+ * delta to the translation. Both go through `clampView`, which keeps the frame's centre on
+ * the drawing — a canvas whose content has been flicked off the window gives the reader
+ * nothing to aim at, and "fit" would be the only way back.
+ */
+
+/** Where the drawing sits in the frame (px, from the frame's top-left corner) and what it is scaled by. */
+export interface CanvasView {
+ x: number;
+ y: number;
+ scale: number;
+}
+
+/** A box the view arithmetic measures against: the frame's inside, or the drawing's natural size. */
+export interface CanvasSize {
+ width: number;
+ height: number;
+}
+
+export const ZOOM_MIN = 0.2;
+export const ZOOM_MAX = 2;
+/** One −/+ press. Multiplicative, so a press covers the same visual ground at 30% as at 150%. */
+export const ZOOM_STEP = 1.2;
+
+/** The drawing at its natural size in the frame's top-left corner — the view before anything is measured. */
+export const IDENTITY_VIEW: CanvasView = { x: 0, y: 0, scale: 1 };
+
+export function clampZoom(scale: number): number {
+ if (!Number.isFinite(scale)) return 1;
+ return Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, scale));
+}
+
+/** A wheel event's line and page modes in pixels (Firefox reports lines, a few setups whole pages). */
+const WHEEL_LINE_PX = 16;
+const WHEEL_PAGE_PX = 100;
+/** The largest tick a single event may zoom by: one wheel notch, whatever the source claims to have moved. */
+const WHEEL_MAX_PX = 100;
+
+/**
+ * The zoom factor of one wheel tick: smooth and multiplicative, so a mouse's few large
+ * deltas and a trackpad's stream of small ones land on the same curve (a notch is ~100px
+ * and a tenth of zoom). Scrolling up — a negative delta — zooms in, as every canvas does.
+ */
+export function wheelZoomFactor(deltaY: number, deltaMode = 0): number {
+ if (!Number.isFinite(deltaY) || deltaY === 0) return 1;
+ const px = deltaY * (deltaMode === 1 ? WHEEL_LINE_PX : deltaMode === 2 ? WHEEL_PAGE_PX : 1);
+ const tick = Math.max(-WHEEL_MAX_PX, Math.min(WHEEL_MAX_PX, px));
+ return 1.1 ** (-tick / 100);
+}
+
+/**
+ * Zoom by `factor` around a point given in frame coordinates, keeping what is under that
+ * point where it is. The clamp is applied to the scale first and the translation follows the
+ * factor that survived it, so a wheel at either end of the range moves nothing at all rather
+ * than sliding the drawing sideways.
+ */
+export function zoomAt(
+ view: CanvasView,
+ pointer: { x: number; y: number },
+ factor: number,
+): CanvasView {
+ const from = clampZoom(view.scale);
+ const scale = clampZoom(from * factor);
+ const applied = scale / from;
+ return {
+ x: pointer.x - (pointer.x - view.x) * applied,
+ y: pointer.y - (pointer.y - view.y) * applied,
+ scale,
+ };
+}
+
+/** Move the drawing by a pointer delta; the scale is untouched. */
+export function panBy(view: CanvasView, dx: number, dy: number): CanvasView {
+ return { x: view.x + dx, y: view.y + dy, scale: view.scale };
+}
+
+/**
+ * Keep the frame's centre inside the drawing: every point of the tree can be brought to the
+ * middle of the frame, and nothing further. One rule holds at both ends of the zoom range —
+ * a drawing wider than the frame still reaches each of its own edges, and a small one cannot
+ * be flicked into a corner and lost. A rule counting overlapping pixels instead allows
+ * exactly that, since the corner a flick leaves in the frame is the tree's empty margin: the
+ * box is still technically on screen and there is nothing on it to see.
+ */
+export function clampView(view: CanvasView, frame: CanvasSize, drawing: CanvasSize): CanvasView {
+ const scale = clampZoom(view.scale);
+ const axis = (value: number, frameSize: number, drawingSize: number): number => {
+ const centre = frameSize / 2;
+ return Math.min(centre, Math.max(centre - drawingSize * scale, value));
+ };
+ return {
+ x: axis(view.x, frame.width, drawing.width),
+ y: axis(view.y, frame.height, drawing.height),
+ scale,
+ };
+}
+
+/**
+ * The view a chart opens at: the whole drawing centred in the frame, shrunk to fit but never
+ * enlarged past its natural size — a two-person chart blown up to fill a monitor reads as a
+ * rendering fault, not as a fit. An unmeasured frame or an empty drawing leaves the identity
+ * view, which the next measurement replaces.
+ */
+export function fitView(frame: CanvasSize, drawing: CanvasSize): CanvasView {
+ if (!(frame.width > 0) || !(frame.height > 0)) return IDENTITY_VIEW;
+ if (!(drawing.width > 0) || !(drawing.height > 0)) return IDENTITY_VIEW;
+ const scale = clampZoom(Math.min(1, frame.width / drawing.width, frame.height / drawing.height));
+ return {
+ x: (frame.width - drawing.width * scale) / 2,
+ y: (frame.height - drawing.height * scale) / 2,
+ scale,
+ };
+}
+
+/** The CSS the drawing layer is placed by. Translation before scale, matching `zoomAt`'s arithmetic. */
+export function viewTransform(view: CanvasView): string {
+ return `translate(${view.x}px, ${view.y}px) scale(${view.scale})`;
+}
diff --git a/packages/web/src/features/company/channel-composer.tsx b/packages/web/src/features/company/channel-composer.tsx
new file mode 100644
index 00000000..5dec24d5
--- /dev/null
+++ b/packages/web/src/features/company/channel-composer.tsx
@@ -0,0 +1,233 @@
+/**
+ * A channel's composer: a growing textarea (Enter sends, Shift+Enter breaks the line, an
+ * IME's accepting Enter never sends), the send button, and the `@` autocomplete — a portaled
+ * panel above the box (through Dropdown's portal, so no ancestor's overflow clips it) listing
+ * the channel's own members — employees with their titles, then people, then everyone —
+ * ranked against what was typed, walked with the arrow keys and picked with Enter or Tab. A
+ * pick types the bare id (`@ceo`), which is what the server resolves; Escape dismisses the
+ * panel for that token until it changes.
+ *
+ * The keys are named in the placeholder and nothing is rendered under the box, the way
+ * development mode's chat input reads: a line of hint below the composer is read once and
+ * then costs a row of the stream on every later visit.
+ */
+import { useId, useLayoutEffect, useRef, useState } from "react";
+import type { KeyboardEvent as ReactKeyboardEvent } from "react";
+import { S } from "../../lib/strings";
+import { ICON_GAP } from "../../lib/icon-scale";
+import { Button } from "../../components/ui/button";
+import { Dropdown } from "../../components/ui/dropdown";
+import { noAutofill } from "../../components/ui/input";
+import { PrincipalChip } from "./shared";
+import {
+ insertMention,
+ mentionInsertId,
+ mentionQueryAt,
+ rankMentionCandidates,
+} from "./channel-mentions";
+import type { MentionCandidate, MentionKind } from "./channel-mentions";
+
+/**
+ * The box grows with the draft up to this many pixels, then scrolls inside — the same cap the
+ * development-mode composer sets in chat-input.tsx, and deliberately a pixel count rather than
+ * `max-h-40`: the root font is the reader's own (16 / 18 / 20px, theme.tsx FONT_PX), so a rem
+ * cap would let the box eat a different share of the stream at each scale. `max-h-40` is only
+ * the outer guard; this is the one that binds.
+ */
+const MAX_BOX_PX = 160;
+
+function kindTitle(kind: MentionKind): string {
+ if (kind === "employee") return S.company.channels.employees;
+ if (kind === "member") return S.company.channels.members;
+ return S.company.channels.mentionAll;
+}
+
+export function ChannelComposer({
+ candidates,
+ names,
+ onSend,
+}: {
+ candidates: readonly MentionCandidate[];
+ names: ReadonlyMap<string, string>;
+ /** Sends the draft; resolves true once it is in the stream (the draft is then cleared). */
+ onSend: (text: string) => Promise<boolean>;
+}) {
+ const [text, setText] = useState("");
+ const [caret, setCaret] = useState(0);
+ const [highlight, setHighlight] = useState(0);
+ /** The `start:query` token Escape dismissed the panel for; typing on changes the token and reopens it. */
+ const [dismissed, setDismissed] = useState<string | null>(null);
+ const [sending, setSending] = useState(false);
+ const inputRef = useRef<HTMLTextAreaElement>(null);
+ const listId = useId();
+
+ const mention = mentionQueryAt(text, caret);
+ const suggestions = mention === null ? [] : rankMentionCandidates(candidates, mention.query);
+ const tokenKey = mention === null ? null : `${mention.start}:${mention.query}`;
+ const panelOpen = mention !== null && suggestions.length > 0 && dismissed !== tokenKey;
+ const active = suggestions[Math.min(highlight, Math.max(0, suggestions.length - 1))];
+
+ // The box follows its content up to the cap, so a long draft stays in view without a
+ // scrollbar appearing at the second line. `scrollHeight` is content + padding and the box
+ // is border-box, so the border has to be added back — without it every line would be set
+ // 2px short and the box would scroll against itself from the very first one.
+ //
+ // The resting height is not set here: `min-h-10` on the box and `h-10` on the button are the
+ // same 2.5rem, so an empty or single-line draft sits exactly as tall as 发送 at every font
+ // scale, and `min-height` outranks the height written below. The row is `items-end`, so the
+ // button stays welded to the box's bottom edge as the box grows.
+ useLayoutEffect(() => {
+ const el = inputRef.current;
+ if (!el) return;
+ el.style.height = "auto";
+ const border = el.offsetHeight - el.clientHeight;
+ el.style.height = `${Math.min(el.scrollHeight + border, MAX_BOX_PX)}px`;
+ }, [text]);
+
+ const pick = (c: MentionCandidate) => {
+ if (mention === null) return;
+ const next = insertMention(text, mention.start, caret, mentionInsertId(c, candidates));
+ setText(next.text);
+ setCaret(next.caret);
+ setHighlight(0);
+ requestAnimationFrame(() => {
+ const el = inputRef.current;
+ if (el) {
+ el.focus();
+ el.setSelectionRange(next.caret, next.caret);
+ }
+ });
+ };
+
+ const send = async () => {
+ const body = text.trim();
+ if (body === "" || sending) return;
+ setSending(true);
+ try {
+ if (await onSend(body)) {
+ setText("");
+ setCaret(0);
+ }
+ } finally {
+ setSending(false);
+ requestAnimationFrame(() => inputRef.current?.focus());
+ }
+ };
+
+ const onKeyDown = (e: ReactKeyboardEvent<HTMLTextAreaElement>) => {
+ if (panelOpen) {
+ if (e.key === "ArrowDown") {
+ e.preventDefault();
+ setHighlight((h) => (h + 1) % suggestions.length);
+ return;
+ }
+ if (e.key === "ArrowUp") {
+ e.preventDefault();
+ setHighlight((h) => (h - 1 + suggestions.length) % suggestions.length);
+ return;
+ }
+ if (e.key === "Enter" || e.key === "Tab") {
+ e.preventDefault();
+ if (active) pick(active);
+ return;
+ }
+ }
+ // Enter sends; Shift+Enter breaks the line. The isComposing guard keeps an IME's
+ // candidate-accepting Enter from sending the raw pinyin.
+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ void send();
+ }
+ };
+
+ const rows: Array<{ c: MentionCandidate; i: number; head: boolean }> = suggestions.map(
+ (c, i) => ({ c, i, head: i === 0 || suggestions[i - 1]!.kind !== c.kind }),
+ );
+
+ return (
+ <div className="shrink-0 border-t border-gray-200 pt-3 dark:border-gray-800">
+ <div className={`flex items-end ${ICON_GAP.menu}`}>
+ <Dropdown
+ className="min-w-0 flex-1"
+ open={panelOpen}
+ setOpen={(v) => {
+ if (!v) setDismissed(tokenKey);
+ }}
+ portal={{ direction: "up", align: "left" }}
+ menuClass="w-80"
+ focusOnOpen={false}
+ button={
+ <textarea
+ ref={inputRef}
+ rows={1}
+ value={text}
+ placeholder={S.company.channels.placeholder}
+ aria-label={S.company.channels.placeholder}
+ aria-autocomplete="list"
+ aria-expanded={panelOpen}
+ aria-controls={panelOpen ? listId : undefined}
+ aria-activedescendant={
+ panelOpen && active ? `${listId}-${active.principal}` : undefined
+ }
+ disabled={sending}
+ {...noAutofill}
+ onChange={(e) => {
+ setText(e.target.value);
+ setCaret(e.target.selectionStart ?? e.target.value.length);
+ setHighlight(0);
+ }}
+ onSelect={(e) => setCaret(e.currentTarget.selectionStart ?? 0)}
+ onKeyDown={onKeyDown}
+ className="block max-h-40 min-h-10 w-full resize-none rounded-md border border-gray-300 bg-white px-3 py-[9px] text-sm leading-5 placeholder:text-gray-400 focus:border-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-400/30 disabled:opacity-60 dark:border-gray-700 dark:bg-gray-900 dark:placeholder:text-gray-500"
+ />
+ }
+ >
+ <div id={listId} role="listbox" aria-label={S.company.channels.mentionPanel}>
+ {rows.map(({ c, i, head }) => (
+ <div key={c.principal}>
+ {head && (
+ <p className="px-2.5 pb-0.5 pt-1.5 text-[11px] font-medium text-gray-400 dark:text-gray-500">
+ {kindTitle(c.kind)}
+ </p>
+ )}
+ <button
+ type="button"
+ role="option"
+ id={`${listId}-${c.principal}`}
+ aria-selected={i === highlight}
+ onMouseDown={(e) => e.preventDefault()}
+ onMouseEnter={() => setHighlight(i)}
+ onClick={() => pick(c)}
+ className={`flex w-full items-center justify-between gap-3 px-2.5 py-1.5 text-left text-xs transition-colors duration-150 ${
+ i === highlight ? "bg-gray-100 dark:bg-gray-800" : ""
+ }`}
+ >
+ <span className="min-w-0 truncate">
+ <PrincipalChip principal={c.principal} names={names} />
+ </span>
+ <span className="shrink-0 text-[11px] text-gray-400 dark:text-gray-500">
+ {c.kind === "all"
+ ? S.company.channels.mentionAllDesc
+ : c.kind === "employee"
+ ? (c.detail ?? "")
+ : ""}
+ </span>
+ </button>
+ </div>
+ ))}
+ </div>
+ </Dropdown>
+ {/* `items-end` on the row plus a fixed height here: the button stays welded to the
+ box's bottom edge as the box grows for a multi-line draft. */}
+ <Button
+ variant="primary"
+ className="h-10 shrink-0"
+ disabled={sending || text.trim() === ""}
+ onClick={() => void send()}
+ >
+ {S.company.channels.send}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/features/company/channel-dialogs.tsx b/packages/web/src/features/company/channel-dialogs.tsx
new file mode 100644
index 00000000..2ffe4619
--- /dev/null
+++ b/packages/web/src/features/company/channel-dialogs.tsx
@@ -0,0 +1,296 @@
+/**
+ * The dialogs a channel needs: creating one (display name, then the id derived from it by
+ * the field's own button, then the purpose) from the channel list's header, and the two
+ * one-field edits its header menu opens — rename and purpose. Failures stay inside the
+ * dialog: a rejected id lands under the id field, anything else in a strip above the footer,
+ * so the fields never sit disabled behind a toast that has already gone.
+ *
+ * Plus the join prompt, which both entry points into joining raise — the channel view's
+ * "you are not a member" notice and the sidebar row's own Join — so the two cannot ask
+ * different questions.
+ */
+import { useEffect, useState } from "react";
+import type { OrgChannelItem } from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { ApiError } from "../../api/client";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { Button } from "../../components/ui/button";
+import { ConfirmModal } from "../../components/ui/confirm-modal";
+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 { ErrorLine } from "./shared";
+
+/** The error codes that are about the id the user typed; every other failure is the form's. */
+const ID_ERROR_CODES = new Set(["channel_exists", "bad_request"]);
+
+/** What the id field says about what was typed, in the reader's language. */
+function idProblemText(problem: ChannelIdProblem): string {
+ if (problem === "required") return S.common.requiredField;
+ if (problem === "reserved") return S.company.channels.idReserved;
+ if (problem === "taken") return S.company.channels.idTaken;
+ return S.company.channels.idHint;
+}
+
+export function NewChannelDialog({
+ open,
+ projectId,
+ orgId,
+ taken,
+ onClose,
+ onCreated,
+}: {
+ open: boolean;
+ projectId: string;
+ orgId: string;
+ /** Every channel id the listing holds, so a duplicate is refused before it collides. */
+ taken: readonly string[];
+ onClose: () => void;
+ onCreated: (channel: OrgChannelItem) => void;
+}) {
+ const [channelId, setChannelId] = useState("");
+ const [name, setName] = useState("");
+ const [purpose, setPurpose] = useState("");
+ const [idError, setIdError] = useState<string | undefined>(undefined);
+ const [formError, setFormError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+
+ // No draft is kept: the form starts empty every time it opens.
+ useEffect(() => {
+ if (!open) return;
+ setChannelId("");
+ setName("");
+ setPurpose("");
+ setIdError(undefined);
+ setFormError(null);
+ }, [open]);
+
+ const submit = async () => {
+ const id = channelId.trim();
+ const problem = channelIdProblem(id, taken);
+ if (problem !== null) {
+ setIdError(idProblemText(problem));
+ return;
+ }
+ setBusy(true);
+ setFormError(null);
+ try {
+ const created = await api.createOrgChannel(projectId, orgId, {
+ channelId: id,
+ ...(name.trim() !== "" ? { name: name.trim() } : {}),
+ ...(purpose.trim() !== "" ? { purpose: purpose.trim() } : {}),
+ });
+ onCreated(created);
+ } catch (e) {
+ const text = apiErrorText(e);
+ if (e instanceof ApiError && ID_ERROR_CODES.has(e.code)) setIdError(text);
+ else setFormError(text);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <Modal
+ open={open}
+ title={S.company.channels.createTitle}
+ onClose={busy ? () => undefined : onClose}
+ footer={
+ <>
+ <Button size="sm" onClick={onClose} disabled={busy}>
+ {S.common.cancel}
+ </Button>
+ <Button size="sm" variant="primary" disabled={busy} onClick={() => void submit()}>
+ {busy ? S.company.channels.creating : S.common.create}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ {/* The name comes first and the id is derived from it: an id is the harder half to
+ invent, and naming the channel is where anyone starts anyway. */}
+ <Input
+ label={S.company.channels.nameField}
+ size="sm"
+ value={name}
+ hint={S.company.channels.nameHint}
+ autoFocus
+ disabled={busy}
+ onChange={(e) => setName(e.target.value)}
+ />
+ <SemanticIdField
+ projectId={projectId}
+ kind="channel"
+ label={S.company.channels.idField}
+ hint={S.company.channels.idHint}
+ value={channelId}
+ source={name}
+ taken={taken}
+ error={idError}
+ disabled={busy}
+ onChange={(id) => {
+ setChannelId(id);
+ setIdError(undefined);
+ }}
+ onEnter={() => void submit()}
+ />
+ <Textarea
+ label={S.company.channels.purpose}
+ size="sm"
+ rows={2}
+ value={purpose}
+ hint={S.company.channels.purposeHint}
+ disabled={busy}
+ onChange={(e) => setPurpose(e.target.value)}
+ />
+ {formError !== null && <ErrorLine message={formError} onRetry={() => void submit()} />}
+ </div>
+ </Modal>
+ );
+}
+
+/**
+ * One text field in a dialog: the channel's name (one line) or its purpose (a short
+ * paragraph). The caller owns the request, so the same shell serves both edits.
+ */
+export function ChannelTextDialog({
+ open,
+ title,
+ label,
+ hint,
+ initial,
+ multiline = false,
+ required = false,
+ onClose,
+ onSubmit,
+}: {
+ open: boolean;
+ title: string;
+ label: string;
+ hint?: string;
+ initial: string;
+ multiline?: boolean;
+ required?: boolean;
+ onClose: () => void;
+ /** Writes the value; a rejection is shown inside the dialog and the field stays editable. */
+ onSubmit: (value: string) => Promise<void>;
+}) {
+ const [value, setValue] = useState(initial);
+ const [fieldError, setFieldError] = useState<string | undefined>(undefined);
+ const [formError, setFormError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+
+ // Every opening starts from what is stored now, not from the last edit's leftovers.
+ useEffect(() => {
+ if (!open) return;
+ setValue(initial);
+ setFieldError(undefined);
+ setFormError(null);
+ }, [open, initial]);
+
+ const submit = async () => {
+ const next = value.trim();
+ if (required && next === "") {
+ setFieldError(S.common.requiredField);
+ return;
+ }
+ setBusy(true);
+ setFormError(null);
+ try {
+ await onSubmit(next);
+ } catch (e) {
+ setFormError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <Modal
+ open={open}
+ title={title}
+ onClose={busy ? () => undefined : onClose}
+ footer={
+ <>
+ <Button size="sm" onClick={onClose} disabled={busy}>
+ {S.common.cancel}
+ </Button>
+ <Button size="sm" variant="primary" disabled={busy} onClick={() => void submit()}>
+ {busy ? S.common.saving : S.common.save}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ {multiline ? (
+ <Textarea
+ label={label}
+ size="sm"
+ rows={3}
+ value={value}
+ {...(hint !== undefined ? { hint } : {})}
+ autoFocus
+ disabled={busy}
+ onChange={(e) => setValue(e.target.value)}
+ />
+ ) : (
+ <Input
+ label={label}
+ size="sm"
+ required={required}
+ value={value}
+ error={fieldError}
+ {...(hint !== undefined ? { hint } : {})}
+ autoFocus
+ disabled={busy}
+ onChange={(e) => {
+ setValue(e.target.value);
+ setFieldError(undefined);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ void submit();
+ }
+ }}
+ />
+ )}
+ {formError !== null && <ErrorLine message={formError} onRetry={() => void submit()} />}
+ </div>
+ </Modal>
+ );
+}
+
+/**
+ * "Join this channel?". Joining is not a destructive act but it is a standing one: from then
+ * on this channel's @-mentions reach the reader, which is what the body says rather than
+ * "are you sure".
+ */
+export function JoinChannelConfirm({
+ open,
+ busy,
+ onClose,
+ onConfirm,
+}: {
+ open: boolean;
+ busy: boolean;
+ onClose: () => void;
+ onConfirm: () => void;
+}) {
+ return (
+ <ConfirmModal
+ open={open}
+ title={S.company.channels.joinTitle}
+ tone="primary"
+ confirmLabel={S.company.channels.join}
+ busy={busy}
+ onClose={onClose}
+ onConfirm={onConfirm}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">{S.company.channels.joinConfirm}</p>
+ </ConfirmModal>
+ );
+}
diff --git a/packages/web/src/features/company/channel-header.tsx b/packages/web/src/features/company/channel-header.tsx
new file mode 100644
index 00000000..d5c26886
--- /dev/null
+++ b/packages/web/src/features/company/channel-header.tsx
@@ -0,0 +1,579 @@
+/**
+ * A channel's header, above its stream: the name (the localized label for the all-hands
+ * channel, never its stored name) with the "?" that says what kind of channel this is and how
+ * far an @-chain relays, the channel's own purpose beside it — nothing when the all-hands
+ * channel has none, since what that channel is for is in the "?" — the members as a stack of
+ * avatars opening a member popover — an employee row there opens its desk session — and the
+ * actions: invite, leave, and the overflow menu with rename, purpose, archive and unarchive.
+ *
+ * Who may do what is the server's rule, not this file's: everything here is shown to a
+ * person, who is a Project member and therefore may join, archive and unarchive — and may
+ * invite once it is in the channel itself. The all-hands channel is the one exception the UI
+ * itself enforces — it cannot be left, archived, or have its membership edited, so those
+ * controls are simply absent, the missing archive row named by one muted line in the menu.
+ * What that channel is stays in the header's "?", said once.
+ */
+import { useEffect, useState } from "react";
+import { createPortal } from "react-dom";
+import { useNavigate } from "react-router";
+import type { OrgChannelDetail, OrgChannelMember } from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
+import { useProject } from "../../state/project";
+import { AgentAvatar } from "../../components/ui/agent-avatar";
+import { Button } from "../../components/ui/button";
+import { ConfirmModal } from "../../components/ui/confirm-modal";
+import { Dropdown } from "../../components/ui/dropdown";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { InfoPopover } from "../../components/ui/info-popover";
+import { Input, noAutofill } from "../../components/ui/input";
+import {
+ ARCHIVE_ICON,
+ ELLIPSIS_ICON,
+ PENCIL_ICON,
+ UNARCHIVE_ICON,
+ overflowMenuGlyph,
+ overflowMenuRowClass,
+} from "../../components/ui/session-row-menu";
+import { usePortalPanel } from "../../components/ui/use-portal-panel";
+import { toastError, toastSuccess } from "../../components/ui/toast";
+import { Truncated } from "../../components/ui/truncated";
+import { ChannelTextDialog } from "./channel-dialogs";
+import { channelGlyph } from "./channel-sidebar";
+import { channelLabel, inviteCandidates, isAllHands } from "./channel-list";
+import type { InviteCandidate } from "./channel-list";
+import { parsePrincipal } from "./principals";
+
+/** Invite (lucide user-plus): the header's "add somebody to this channel" action. */
+const INVITE_ICON =
+ "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M13 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0zM19 8v6M22 11h-6";
+
+/** Leave (lucide log-out): removing oneself from the channel. */
+const LEAVE_ICON = "M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9";
+
+/** Purpose (lucide text): the menu row that edits what the channel is for. */
+const PURPOSE_ICON = "M4 6h16M4 12h12M4 18h8";
+
+/** Opening a desk session (lucide door-open): the member popover's employee rows, and the org chart's node menu. */
+export const DESK_ICON = "M13 4h3v16h-3M3 20h11V4L3 6zM10 12h.01";
+
+/** Members shown as avatars before the count takes over. */
+const AVATAR_STACK = 3;
+
+const PANEL_WIDTH = 288;
+
+/** One member's avatar: an employee's tile, a person's initial disc. */
+function MemberAvatar({ member, size }: { member: OrgChannelMember; size: number }) {
+ const parsed = parsePrincipal(member.principal);
+ if (parsed.kind === "agent") {
+ return (
+ <AgentAvatar id={parsed.id} name={member.name} size={size} className="shrink-0 rounded" />
+ );
+ }
+ return (
+ <span
+ aria-hidden
+ style={{ width: size, height: size, fontSize: Math.round(size * 0.55) }}
+ className="flex shrink-0 items-center justify-center rounded-full bg-gray-900 font-bold text-white dark:bg-gray-200 dark:text-gray-900"
+ >
+ {member.name.slice(0, 1).toUpperCase()}
+ </span>
+ );
+}
+
+/** The member list: who is in the channel, with an employee's desk session one click away. */
+function MemberPopover({
+ members,
+ onOpenDesk,
+ openingDesk,
+}: {
+ members: readonly OrgChannelMember[];
+ /** Opens an employee's desk session; takes the member's principal. */
+ onOpenDesk: (principal: string) => void;
+ /** The principal whose desk is being opened, so the rows do not fire twice. */
+ openingDesk: string | null;
+}) {
+ const [open, setOpen] = useState(false);
+ const { triggerRef, panelRef, position } = usePortalPanel({
+ open,
+ onClose: () => setOpen(false),
+ estimatedHeight: Math.min(320, members.length * 32 + 24),
+ panelWidth: PANEL_WIDTH,
+ });
+ const label = `${S.company.channels.memberList} · ${S.company.channels.memberCount(members.length)}`;
+ return (
+ <>
+ <button
+ ref={triggerRef}
+ type="button"
+ title={label}
+ aria-label={label}
+ aria-haspopup="dialog"
+ aria-expanded={open}
+ onClick={() => setOpen((v) => !v)}
+ className="flex shrink-0 items-center gap-1.5 rounded-md px-1.5 py-1 text-xs text-gray-600 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100"
+ >
+ <span className="flex -space-x-1">
+ {members.slice(0, AVATAR_STACK).map((m) => (
+ <span
+ key={m.principal}
+ className="rounded-full ring-2 ring-white dark:ring-gray-950"
+ // The ring separates overlapping tiles; it is the page ground, not a colour.
+ >
+ <MemberAvatar member={m} size={ICON_SIZE.groupHeaderAvatar} />
+ </span>
+ ))}
+ </span>
+ <span className="tabular-nums">{S.company.channels.memberCount(members.length)}</span>
+ </button>
+ {open &&
+ position &&
+ createPortal(
+ <div
+ ref={panelRef}
+ role="dialog"
+ aria-label={S.company.channels.memberList}
+ style={{
+ position: "fixed",
+ top: position.topPx,
+ bottom: position.bottomPx,
+ left: position.left,
+ width: PANEL_WIDTH,
+ }}
+ className="z-[60] max-h-[60vh] overflow-y-auto rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-900"
+ >
+ {members.length === 0 ? (
+ <p className="px-2.5 py-1.5 text-xs text-gray-400 dark:text-gray-500">
+ {S.company.channels.memberCount(0)}
+ </p>
+ ) : (
+ members.map((m) => (
+ <div
+ key={m.principal}
+ className={`flex items-center ${ICON_GAP.row} px-2.5 py-1.5 text-xs`}
+ >
+ <MemberAvatar member={m} size={ICON_SIZE.rowLead} />
+ <Truncated text={m.name} className="min-w-0 flex-1" />
+ {m.kind === "agent" && (
+ <button
+ type="button"
+ disabled={openingDesk !== null}
+ onClick={() => onOpenDesk(m.principal)}
+ className={`flex shrink-0 items-center ${ICON_GAP.tight} rounded px-1.5 py-0.5 text-[11px] text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900 disabled:opacity-60 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-100`}
+ >
+ <GlyphIcon d={DESK_ICON} size={ICON_SIZE.inlineGlyph} />
+ {S.company.openDesk}
+ </button>
+ )}
+ </div>
+ ))
+ )}
+ </div>,
+ document.body,
+ )}
+ </>
+ );
+}
+
+/** The invite picker: everyone not in the channel yet, filtered by what is typed. */
+function InvitePicker({
+ candidates,
+ query,
+ onQuery,
+ onPick,
+ busy,
+}: {
+ candidates: readonly InviteCandidate[];
+ query: string;
+ onQuery: (value: string) => void;
+ onPick: (candidate: InviteCandidate) => void;
+ busy: boolean;
+}) {
+ const [open, setOpen] = useState(false);
+ return (
+ <Dropdown
+ open={open}
+ setOpen={(v) => {
+ setOpen(v);
+ if (!v) onQuery("");
+ }}
+ portal={{ direction: "down", align: "right" }}
+ menuClass="w-72"
+ className="shrink-0"
+ button={
+ <Button size="sm" onClick={() => setOpen(!open)} disabled={busy}>
+ {S.company.channels.invite}
+ </Button>
+ }
+ >
+ <div role="dialog" aria-label={S.company.channels.inviteTitle}>
+ <div className="px-2 pb-1 pt-1.5">
+ <Input
+ size="sm"
+ value={query}
+ aria-label={S.company.channels.inviteSearch}
+ placeholder={S.company.channels.inviteSearch}
+ {...noAutofill}
+ onChange={(e) => onQuery(e.target.value)}
+ />
+ </div>
+ <div className="max-h-64 overflow-y-auto">
+ {candidates.length === 0 ? (
+ <p className="px-2.5 py-1.5 text-xs text-gray-400 dark:text-gray-500">
+ {S.company.channels.inviteEmpty}
+ </p>
+ ) : (
+ candidates.map((c) => (
+ <button
+ key={c.principal}
+ type="button"
+ disabled={busy}
+ onClick={() => {
+ setOpen(false);
+ onQuery("");
+ onPick(c);
+ }}
+ className={`flex w-full items-center justify-between gap-3 px-2.5 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 disabled:opacity-60 dark:hover:bg-gray-800`}
+ >
+ <span className={`flex min-w-0 items-center ${ICON_GAP.row}`}>
+ <MemberAvatar
+ member={{ principal: c.principal, name: c.name, kind: c.kind }}
+ size={ICON_SIZE.rowLead}
+ />
+ <span className="min-w-0 truncate">{c.name}</span>
+ </span>
+ <span className="shrink-0 text-[11px] text-gray-400 dark:text-gray-500">
+ {c.detail ?? (c.kind === "user" ? S.company.channels.members : "")}
+ </span>
+ </button>
+ ))
+ )}
+ </div>
+ </div>
+ </Dropdown>
+ );
+}
+
+export function ChannelHeader({
+ projectId,
+ orgId,
+ me,
+ detail,
+ employees,
+ projectMembers,
+ onChanged,
+}: {
+ projectId: string;
+ orgId: string;
+ /** The reader's own principal (`user:<id>`) — what leaving removes. */
+ me: string;
+ /** The channel as the server last described it, members included; null while it loads. */
+ detail: OrgChannelDetail | null;
+ employees: ReadonlyArray<{ agentId: string; name: string; title: string }>;
+ projectMembers: readonly string[];
+ /** Re-read the channel (and the sidebar's listing) after a write. */
+ onChanged: () => void;
+}) {
+ const navigate = useNavigate();
+ const { setCurrentAgentId } = useProject();
+ const [renameOpen, setRenameOpen] = useState(false);
+ const [purposeOpen, setPurposeOpen] = useState(false);
+ const [leaveOpen, setLeaveOpen] = useState(false);
+ const [archiveOpen, setArchiveOpen] = useState(false);
+ const [menuOpen, setMenuOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [openingDesk, setOpeningDesk] = useState<string | null>(null);
+
+ // A channel switch must not leave the previous one's dialogs standing.
+ const channelId = detail?.channelId ?? null;
+ useEffect(() => {
+ setRenameOpen(false);
+ setPurposeOpen(false);
+ setLeaveOpen(false);
+ setArchiveOpen(false);
+ setMenuOpen(false);
+ setQuery("");
+ }, [channelId]);
+
+ if (detail === null) {
+ return (
+ <div className="flex h-12 shrink-0 items-center border-b border-gray-200 px-3 md:px-4 dark:border-gray-800" />
+ );
+ }
+
+ const allHands = isAllHands(detail.channelId);
+ const label = channelLabel(detail, S.company.channels.allHands);
+ // The subtitle is the channel's own purpose and nothing else. The all-hands channel is seeded
+ // without one and stays blank until somebody writes one: what it is for is the kind of channel
+ // it is, which is the "?" beside the name, and standing text there would be a sentence the
+ // reader re-reads on every visit to a channel it can never change. An invited channel without
+ // a purpose says so instead, because writing one is a menu row away.
+ const purpose =
+ detail.purpose !== "" ? detail.purpose : allHands ? null : S.company.channels.purposeEmpty;
+ const candidates = inviteCandidates(employees, projectMembers, detail.members, query);
+
+ const openDesk = async (principal: string) => {
+ const parsed = parsePrincipal(principal);
+ if (parsed.kind !== "agent" || openingDesk !== null) return;
+ const agentId = parsed.id;
+ setOpeningDesk(principal);
+ try {
+ const desk = await api.getOrgDesk(projectId, orgId, agentId);
+ setCurrentAgentId(agentId);
+ navigate(`/chat/${desk.sessionId}`);
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setOpeningDesk(null);
+ }
+ };
+
+ const invite = async (candidate: InviteCandidate) => {
+ setBusy(true);
+ try {
+ await api.addOrgChannelMember(projectId, orgId, detail.channelId, {
+ principal: candidate.principal,
+ });
+ toastSuccess(S.company.channels.invited(candidate.name));
+ onChanged();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const leave = async (principal: string) => {
+ setBusy(true);
+ try {
+ await api.removeOrgChannelMember(projectId, orgId, detail.channelId, principal);
+ setLeaveOpen(false);
+ toastSuccess(S.company.channels.left);
+ onChanged();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const setArchived = async (archived: boolean) => {
+ setBusy(true);
+ try {
+ await api.patchOrgChannel(projectId, orgId, detail.channelId, { archived });
+ setArchiveOpen(false);
+ toastSuccess(archived ? S.company.channels.archived : S.company.channels.unarchived);
+ onChanged();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const patchText = async (body: { name?: string; purpose?: string }) => {
+ await api.patchOrgChannel(projectId, orgId, detail.channelId, body);
+ setRenameOpen(false);
+ setPurposeOpen(false);
+ toastSuccess(S.common.saved);
+ onChanged();
+ };
+
+ return (
+ <>
+ <div className="flex shrink-0 flex-wrap items-center gap-x-3 gap-y-1 border-b border-gray-200 px-3 py-2 md:px-4 dark:border-gray-800">
+ <div className="flex min-w-0 flex-1 items-baseline gap-x-3 gap-y-1">
+ {/* The name is a direct child of the heading, with the "?" right after it — the
+ anchoring every other title in the app uses (OrgPage's own header included), and
+ what test/disclosure-anchor.test.ts reads. The row clips rather than wraps: the
+ server caps a channel name at 100 characters and the tooltip carries it whole. */}
+ <h1
+ title={label}
+ className={`flex min-w-0 items-center overflow-hidden whitespace-nowrap ${ICON_GAP.row} text-[15px] font-semibold`}
+ >
+ <span className="shrink-0 text-gray-400 dark:text-gray-500">
+ <GlyphIcon d={channelGlyph(detail.channelId)} size={ICON_SIZE.rowLead} />
+ </span>
+ {label}
+ {/* Two paragraphs, not one string per channel kind: what a hop is has to be
+ readable here as well as from a relay chip's tooltip, and only the first half
+ differs between the all-hands channel and an invited one. */}
+ <InfoPopover label={label}>
+ <span className="block">
+ {allHands ? S.company.channels.allHandsInfo : S.company.channels.channelInfo}
+ </span>
+ <span className="mt-1.5 block">{S.company.channels.hopSummary}</span>
+ </InfoPopover>
+ </h1>
+ {/* The purpose reads as a subtitle on the same line, so the header stays one row. */}
+ {purpose !== null && (
+ <span
+ title={purpose}
+ className="hidden min-w-0 flex-1 truncate text-xs text-gray-500 sm:block dark:text-gray-400"
+ >
+ {purpose}
+ </span>
+ )}
+ </div>
+ <div className="flex shrink-0 items-center gap-1.5">
+ <MemberPopover
+ members={detail.members}
+ onOpenDesk={(principal) => void openDesk(principal)}
+ openingDesk={openingDesk}
+ />
+ {/* Inviting is a member's action, and never edits the all-hands channel — which
+ already holds everyone, so its candidate list is empty by construction. Both
+ refusals are the server's rule (`all_hands_immutable`, `not_a_member`); the
+ button is absent rather than dead. */}
+ {!allHands && detail.isMember && !detail.archived && (
+ <InvitePicker
+ candidates={candidates}
+ query={query}
+ onQuery={setQuery}
+ onPick={(c) => void invite(c)}
+ busy={busy}
+ />
+ )}
+ {!allHands && detail.isMember && !detail.archived && (
+ <Button size="sm" disabled={busy} onClick={() => setLeaveOpen(true)}>
+ <span className={`flex items-center ${ICON_GAP.tight}`}>
+ <GlyphIcon d={LEAVE_ICON} size={ICON_SIZE.inlineGlyph} />
+ {S.company.channels.leave}
+ </span>
+ </Button>
+ )}
+ <Dropdown
+ open={menuOpen}
+ setOpen={setMenuOpen}
+ portal={{ direction: "down", align: "right" }}
+ menuClass="w-44"
+ className="shrink-0"
+ button={
+ <button
+ type="button"
+ title={S.company.channels.channelMenu}
+ aria-label={`${S.company.channels.channelMenu}: ${label}`}
+ aria-haspopup="menu"
+ aria-expanded={menuOpen}
+ onClick={() => setMenuOpen(!menuOpen)}
+ className="flex h-7 w-7 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ >
+ <GlyphIcon d={ELLIPSIS_ICON} size={ICON_SIZE.iconButton} filled />
+ </button>
+ }
+ >
+ {!detail.archived && (
+ <>
+ <button
+ type="button"
+ className={overflowMenuRowClass}
+ onClick={() => {
+ setMenuOpen(false);
+ setRenameOpen(true);
+ }}
+ >
+ {overflowMenuGlyph(PENCIL_ICON)}
+ {S.company.channels.rename}
+ </button>
+ <button
+ type="button"
+ className={overflowMenuRowClass}
+ onClick={() => {
+ setMenuOpen(false);
+ setPurposeOpen(true);
+ }}
+ >
+ {overflowMenuGlyph(PURPOSE_ICON)}
+ {S.company.channels.editPurpose}
+ </button>
+ </>
+ )}
+ {/* Archiving is a people-only action, and the Web App's caller is always a
+ person — an employee reaches channels through the CLI. */}
+ {!allHands &&
+ (detail.archived ? (
+ <button
+ type="button"
+ className={overflowMenuRowClass}
+ onClick={() => {
+ setMenuOpen(false);
+ void setArchived(false);
+ }}
+ >
+ {overflowMenuGlyph(UNARCHIVE_ICON)}
+ {S.company.channels.unarchive}
+ </button>
+ ) : (
+ <button
+ type="button"
+ className={overflowMenuRowClass}
+ onClick={() => {
+ setMenuOpen(false);
+ setArchiveOpen(true);
+ }}
+ >
+ {overflowMenuGlyph(ARCHIVE_ICON)}
+ {S.company.channels.archive}
+ </button>
+ ))}
+ {/* The all-hands channel simply has no archive row; one short line says why it is
+ missing. What that channel IS belongs to the header's "?", and repeating the
+ whole paragraph here made a menu out of an explanation. */}
+ {allHands && detail.archived === false && (
+ <p className="px-2.5 py-1.5 text-[11px] text-gray-400 dark:text-gray-500">
+ {S.company.channels.allHandsNoArchive}
+ </p>
+ )}
+ </Dropdown>
+ </div>
+ </div>
+
+ <ChannelTextDialog
+ open={renameOpen}
+ title={S.company.channels.renameTitle}
+ label={S.company.channels.nameField}
+ initial={detail.name}
+ required
+ onClose={() => setRenameOpen(false)}
+ onSubmit={(value) => patchText({ name: value })}
+ />
+ <ChannelTextDialog
+ open={purposeOpen}
+ title={S.company.channels.purposeTitle}
+ label={S.company.channels.purpose}
+ hint={S.company.channels.purposeHint}
+ initial={detail.purpose}
+ multiline
+ onClose={() => setPurposeOpen(false)}
+ onSubmit={(value) => patchText({ purpose: value })}
+ />
+ <ConfirmModal
+ open={leaveOpen}
+ title={S.company.channels.leaveTitle}
+ confirmLabel={S.company.channels.leave}
+ busy={busy}
+ onClose={() => (busy ? undefined : setLeaveOpen(false))}
+ onConfirm={() => void leave(me)}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {S.company.channels.leaveConfirm(label)}
+ </p>
+ </ConfirmModal>
+ <ConfirmModal
+ open={archiveOpen}
+ title={S.company.channels.archiveTitle}
+ confirmLabel={S.company.channels.archive}
+ busy={busy}
+ onClose={() => (busy ? undefined : setArchiveOpen(false))}
+ onConfirm={() => void setArchived(true)}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {S.company.channels.archiveConfirm(label)}
+ </p>
+ </ConfirmModal>
+ </>
+ );
+}
diff --git a/packages/web/src/features/company/channel-list.ts b/packages/web/src/features/company/channel-list.ts
new file mode 100644
index 00000000..bfcc7da3
--- /dev/null
+++ b/packages/web/src/features/company/channel-list.ts
@@ -0,0 +1,161 @@
+/**
+ * Channels as the sidebar and the dialogs need them (pure, unit tested): the all-hands
+ * channel pinned above the channels the caller is in, the channels it is not in and the
+ * archived ones folded away; the id a new channel may take; who is left to invite; and the
+ * two numbers the sidebar's and the rail's badges sum.
+ *
+ * The all-hands channel is `default_channel` — created with the organization, holding every
+ * employee and every Project member implicitly. Its stored name is never displayed: the list,
+ * the header and every reference to it render the localized 全员频道 / "All hands" label
+ * instead, so one organization reads the same in both languages whatever its files say.
+ */
+import type { OrgChannelItem, OrgChannelMember } from "@prismshadow/penguin-server/api";
+
+/** The all-hands channel's id; reserved, so no other channel may take it. */
+export const DEFAULT_CHANNEL_ID = "default_channel";
+
+/** Channel ids follow the semantic-id rule the organization ids use (mirrors the server's isChannelId). */
+export const CHANNEL_ID_PATTERN = /^[a-z][a-z0-9_]{1,63}$/;
+
+/** Whether a channel is the all-hands one — membership implicit, never archived, never left. */
+export function isAllHands(channelId: string): boolean {
+ return channelId === DEFAULT_CHANNEL_ID;
+}
+
+/** What a channel is called on screen: the localized label for the all-hands channel, the stored name for the rest. */
+export function channelLabel(
+ channel: { channelId: string; name: string },
+ allHandsLabel: string,
+): string {
+ return isAllHands(channel.channelId) ? allHandsLabel : channel.name;
+}
+
+/** Why an id the user typed cannot be created; null when it can. */
+export type ChannelIdProblem = "required" | "invalid" | "reserved" | "taken";
+
+/**
+ * The new-channel dialog's check, run before the request so the failure lands under the
+ * field: the grammar the server enforces, `default_channel` refused because the all-hands
+ * channel owns it, and an id the listing already holds refused before it collides.
+ */
+export function channelIdProblem(
+ raw: string,
+ taken: Iterable<string> = [],
+): ChannelIdProblem | null {
+ const id = raw.trim();
+ if (id === "") return "required";
+ if (!CHANNEL_ID_PATTERN.test(id)) return "invalid";
+ if (isAllHands(id)) return "reserved";
+ for (const other of taken) if (other === id) return "taken";
+ return null;
+}
+
+/** The four runs of the channel list, in rendered order. */
+export interface ChannelGroups {
+ /** The all-hands channel, pinned above everything; null only while an organization's files are being repaired. */
+ allHands: OrgChannelItem | null;
+ /** Channels the caller is in. */
+ mine: OrgChannelItem[];
+ /** Channels the caller is not in — a person may join any of them. */
+ others: OrgChannelItem[];
+ /** Archived channels, whether or not the caller is in them: read-only, folded away. */
+ archived: OrgChannelItem[];
+}
+
+/** By display name, then by id so two channels sharing a name keep a stable order. */
+function byName(allHandsLabel: string) {
+ return (a: OrgChannelItem, b: OrgChannelItem): number =>
+ channelLabel(a, allHandsLabel).localeCompare(channelLabel(b, allHandsLabel)) ||
+ a.channelId.localeCompare(b.channelId);
+}
+
+/**
+ * The listing split into the list's runs. Archived wins over membership — an archived
+ * channel is a record, not a place to work — and the all-hands channel is pinned out of
+ * every run, since it cannot be archived and everyone is in it.
+ */
+export function groupChannels(
+ channels: readonly OrgChannelItem[],
+ allHandsLabel = "",
+): ChannelGroups {
+ const groups: ChannelGroups = { allHands: null, mine: [], others: [], archived: [] };
+ for (const channel of channels) {
+ if (isAllHands(channel.channelId)) groups.allHands = channel;
+ else if (channel.archived) groups.archived.push(channel);
+ else if (channel.isMember) groups.mine.push(channel);
+ else groups.others.push(channel);
+ }
+ const order = byName(allHandsLabel);
+ groups.mine.sort(order);
+ groups.others.sort(order);
+ groups.archived.sort(order);
+ return groups;
+}
+
+/**
+ * What the summary badges count: unread and @me summed over the channels the caller belongs
+ * to — the ones it can be reached in. A channel it merely reads (people see every channel)
+ * is waiting for nobody, and an archived one is a record rather than a place to work: both
+ * are left out, so the total never claims something the list has folded away.
+ */
+export function channelBadgeCounts(channels: readonly OrgChannelItem[]): {
+ unread: number;
+ mentions: number;
+} {
+ let unread = 0;
+ let mentions = 0;
+ for (const channel of channels) {
+ if (!channel.isMember || channel.archived) continue;
+ unread += channel.unread;
+ mentions += channel.mentionsMe;
+ }
+ return { unread, mentions };
+}
+
+/** One row of the invite picker: a principal that could be added to the channel. */
+export interface InviteCandidate {
+ /** `agent:<id>` (an employee) or `user:<id>` (a Project member). */
+ principal: string;
+ /** The employee's name, or the member's user id. */
+ name: string;
+ kind: "agent" | "user";
+ /** Secondary text beside the name: an employee's title. */
+ detail?: string;
+}
+
+/**
+ * Who is left to invite: the organization's employees, then the Project's members, minus
+ * whoever is already in the channel, ranked against what was typed — a name or id that
+ * starts with the query above one that merely contains it, ties in list order.
+ */
+export function inviteCandidates(
+ employees: ReadonlyArray<{ agentId: string; name: string; title?: string }>,
+ memberUserIds: readonly string[],
+ current: ReadonlyArray<OrgChannelMember | { principal: string }>,
+ query = "",
+): InviteCandidate[] {
+ const taken = new Set(current.map((m) => m.principal));
+ const list: InviteCandidate[] = [];
+ for (const e of employees) {
+ const principal = `agent:${e.agentId}`;
+ if (taken.has(principal)) continue;
+ const detail = e.title?.trim() ?? "";
+ list.push({ principal, name: e.name, kind: "agent", ...(detail !== "" ? { detail } : {}) });
+ }
+ for (const userId of memberUserIds) {
+ const principal = `user:${userId}`;
+ if (taken.has(principal)) continue;
+ list.push({ principal, name: userId, kind: "user" });
+ }
+ const q = query.trim().toLowerCase();
+ if (q === "") return list;
+ const scored: Array<{ c: InviteCandidate; score: number; i: number }> = [];
+ list.forEach((c, i) => {
+ const id = c.principal.slice(c.principal.indexOf(":") + 1).toLowerCase();
+ const name = c.name.toLowerCase();
+ const score =
+ id.startsWith(q) || name.startsWith(q) ? 0 : id.includes(q) || name.includes(q) ? 1 : -1;
+ if (score >= 0) scored.push({ c, score, i });
+ });
+ return scored.sort((a, b) => a.score - b.score || a.i - b.i).map((s) => s.c);
+}
diff --git a/packages/web/src/features/company/channel-markdown.tsx b/packages/web/src/features/company/channel-markdown.tsx
new file mode 100644
index 00000000..263a82bf
--- /dev/null
+++ b/packages/web/src/features/company/channel-markdown.tsx
@@ -0,0 +1,176 @@
+/**
+ * A channel message's body: Markdown through the app's shared pipeline, with `@mentions` kept
+ * as chips and typed line breaks kept as line breaks.
+ *
+ * A message in a channel is prose somebody typed, so it renders the way every other Markdown
+ * surface in this app does — headings, lists, tables, fenced code — instead of showing its own
+ * markers. Two things separate it from a chat reply, and one remark pass covers both:
+ *
+ * - **Mentions.** `@ceo` is not Markdown, it is this product's own token, and the reader has to
+ * see at a glance which ones name them. Splitting it out of the text before the renderer runs
+ * is what lets a mention survive inside a list item, a heading or a table cell — and because
+ * the pass only ever touches `text` nodes, an `@` inside inline code or a fence stays literal.
+ * - **Line breaks.** A composer with Shift+Enter for a new line makes single newlines
+ * meaningful; Markdown folds them into spaces. They become hard breaks here.
+ *
+ * A mention reaches the renderer as `<data value="agent:ceo">`: mdast has no mention node, no
+ * Markdown syntax produces a `<data>` element (so claiming it in the components map collides
+ * with nothing the parser or KaTeX emits), and it is the one HTML element that already means "a
+ * machine value beside its human-readable label". Who is reading comes from context rather than
+ * props, because the components map has to be a module constant.
+ */
+import { createContext, useContext } from "react";
+import type { ReactNode } from "react";
+import type { Components, Options } from "react-markdown";
+import { S } from "../../lib/strings";
+import { toneSurface } from "../../lib/tone";
+import { Md } from "../chat/md";
+import { mentionIsMe, mentionLabel, mentionRuns } from "./channel-mentions";
+
+/** The mdast shapes this pass touches, declared structurally rather than taking `@types/mdast` on. */
+interface MdNode {
+ type: string;
+ value?: string;
+ children?: MdNode[];
+ data?: {
+ hName?: string;
+ hProperties?: Record<string, string>;
+ hChildren?: Array<{ type: string; value: string }>;
+ };
+}
+interface MdParent {
+ children: MdNode[];
+}
+
+/** The element a mention becomes; see this module's comment for why `data` and not a span. */
+const MENTION_TAG = "data";
+
+function mentionNode(raw: string, token: string): MdNode {
+ return {
+ type: "mention",
+ data: {
+ hName: MENTION_TAG,
+ hProperties: { value: token },
+ // The raw token as the element's text: what the chip falls back to, and what a copy of
+ // the rendered message carries.
+ hChildren: [{ type: "text", value: raw }],
+ },
+ };
+}
+
+/**
+ * One text node as the nodes that replace it — mention nodes for the `@` runs, hard breaks for
+ * the newlines — or null when it holds neither and is left exactly as it is.
+ */
+function splitText(value: string): MdNode[] | null {
+ const out: MdNode[] = [];
+ let changed = false;
+ for (const run of mentionRuns(value)) {
+ if (run.mention !== null) {
+ out.push(mentionNode(run.text, run.mention));
+ changed = true;
+ continue;
+ }
+ const lines = run.text.split("\n");
+ for (const [i, line] of lines.entries()) {
+ if (i > 0) {
+ out.push({ type: "break" });
+ changed = true;
+ }
+ if (line !== "") out.push({ type: "text", value: line });
+ }
+ }
+ return changed ? out : null;
+}
+
+/** Walks every parent, so a mention in a list item or a table cell is covered too. */
+function walk(parent: MdParent): void {
+ const children = parent.children;
+ for (let i = 0; i < children.length; i += 1) {
+ const node = children[i]!;
+ if (node.type === "text" && typeof node.value === "string") {
+ const split = splitText(node.value);
+ if (split !== null) {
+ children.splice(i, 1, ...split);
+ i += split.length - 1;
+ }
+ continue;
+ }
+ if (Array.isArray(node.children)) walk(node as MdParent);
+ }
+}
+
+/** Runs after remark-gfm, on the tree it produced. */
+export function remarkChannelMessage() {
+ return (tree: MdParent): void => walk(tree);
+}
+
+/** What a channel body adds to the shared remark stage — the pass above, and nothing else. */
+export const CHANNEL_REMARK_PLUGINS: NonNullable<Options["remarkPlugins"]> = [remarkChannelMessage];
+
+/** Who is reading, which is what decides whether a mention is highlighted. */
+export interface ChannelReader {
+ /** Employee id to display name. */
+ names: ReadonlyMap<string, string>;
+ /** The reading user's own id; "" while it is unknown. */
+ me: string;
+ /** Every employee id, so a bare `@id` an employee claims is not read as the user's. */
+ employeeIds: ReadonlySet<string>;
+}
+
+const NOBODY: ChannelReader = { names: new Map(), me: "", employeeIds: new Set() };
+const ReaderContext = createContext<ChannelReader>(NOBODY);
+
+/** Names every mention chip rendered below against this reader. */
+export function ChannelReaderProvider({
+ reader,
+ children,
+}: {
+ reader: ChannelReader;
+ children: ReactNode;
+}) {
+ return <ReaderContext.Provider value={reader}>{children}</ReaderContext.Provider>;
+}
+
+/**
+ * A mention as a chip: the resolved name after the `@`, the raw token in the tooltip;
+ * attention-toned when it addresses the reader. The ordinary chip sits one step deeper than
+ * the app's usual grey fill, because the bubble it is printed on is that grey (channel-view's
+ * BUBBLE_SURFACE) and a chip the colour of its background is not a chip.
+ */
+export function MentionChip({ raw, label, me }: { raw: string; label: string; me: boolean }) {
+ return (
+ <span
+ title={raw}
+ className={`rounded px-1 ${
+ me
+ ? `font-semibold ${toneSurface.attention}`
+ : "bg-gray-200 font-medium text-gray-800 dark:bg-gray-700 dark:text-gray-100"
+ }`}
+ >
+ @{label}
+ {me && <span className="sr-only"> ({S.company.channels.mentionsYou})</span>}
+ </span>
+ );
+}
+
+/** The `<data>` element the pass produced, as the chip. Its props are the element's, hence the width of `value`. */
+function MentionNode({ value }: { value?: string | number | readonly string[] }) {
+ const reader = useContext(ReaderContext);
+ const token = typeof value === "string" ? value : "";
+ return (
+ <MentionChip
+ raw={`@${token}`}
+ label={mentionLabel(token, reader.names, S.company.principalAll)}
+ me={mentionIsMe(token, reader.me, reader.employeeIds)}
+ />
+ );
+}
+
+/** The one element a channel body overrides; the chat renderer's `pre` and `a` stay as they are. */
+export const CHANNEL_COMPONENTS: Components = { [MENTION_TAG]: MentionNode };
+
+/** A message body. The caller supplies the `md-body md-compact` container it renders into. */
+export function ChannelMessageBody({ text }: { text: string }) {
+ return <Md text={text} extraPlugins={CHANNEL_REMARK_PLUGINS} components={CHANNEL_COMPONENTS} />;
+}
diff --git a/packages/web/src/features/company/channel-mentions.ts b/packages/web/src/features/company/channel-mentions.ts
new file mode 100644
index 00000000..fd8b9e95
--- /dev/null
+++ b/packages/web/src/features/company/channel-mentions.ts
@@ -0,0 +1,184 @@
+/**
+ * A channel's @-mentions (pure, unit tested): the candidates the composer offers — the
+ * channel's own members, plus `all` — and how they rank against what was typed, the token
+ * being typed at the caret, what a pick types and how it is spliced into the draft, how a
+ * stored message is split into plain runs and mention runs for highlighting, and what a
+ * mention run displays and whether it addresses the reader. The token grammar mirrors the
+ * server's extractMentionTokens — `@id`, `@agent:id`, `@user:id`, `@all` — and its
+ * resolution order (an employee before a member of the same id), so what the composer
+ * highlights is what the server delivers.
+ *
+ * Membership is the source, not the org chart: a mention delivers only inside the channel it
+ * was written in, and the server rejects a message naming an outsider (`mention_not_member`).
+ * The composer therefore offers the channel's members and nobody else.
+ */
+
+export type MentionKind = "employee" | "member" | "all";
+
+export interface MentionCandidate {
+ /** The principal the pick stands for (`agent:<id>`, `user:<id>`, `all`). */
+ principal: string;
+ /** The display name (an employee's name, a member's user id, "everyone"). */
+ label: string;
+ /** The bare id the user may have typed (`ceo`, `alice`, `all`). */
+ id: string;
+ kind: MentionKind;
+ /** Secondary text beside the name: an employee's title. */
+ detail?: string;
+}
+
+/** Employees first, then Project members, then `all` — the order the panel lists them in. */
+export function mentionCandidates(
+ employees: ReadonlyArray<{ agentId: string; name: string; title?: string }>,
+ members: readonly string[],
+ allLabel: string,
+): MentionCandidate[] {
+ const out: MentionCandidate[] = employees.map((e) => ({
+ principal: `agent:${e.agentId}`,
+ label: e.name,
+ id: e.agentId,
+ kind: "employee" as const,
+ ...(e.title !== undefined && e.title.trim() !== "" ? { detail: e.title.trim() } : {}),
+ }));
+ for (const userId of members) {
+ out.push({ principal: `user:${userId}`, label: userId, id: userId, kind: "member" });
+ }
+ out.push({ principal: "all", label: allLabel, id: "all", kind: "all" });
+ return out;
+}
+
+/**
+ * Candidates ranked for the panel: an id or name that starts with the query ranks above one
+ * that merely contains it (or whose principal does), and ties keep the list's own order —
+ * employees, then members, then `all`. An empty query keeps everyone in that order.
+ */
+export function rankMentionCandidates(
+ candidates: readonly MentionCandidate[],
+ query: string,
+): MentionCandidate[] {
+ const q = query.trim().toLowerCase();
+ if (q === "") return [...candidates];
+ const scored: Array<{ c: MentionCandidate; score: number; i: number }> = [];
+ candidates.forEach((c, i) => {
+ const id = c.id.toLowerCase();
+ const label = c.label.toLowerCase();
+ const score =
+ id.startsWith(q) || label.startsWith(q)
+ ? 0
+ : id.includes(q) || label.includes(q) || c.principal.toLowerCase().includes(q)
+ ? 1
+ : -1;
+ if (score >= 0) scored.push({ c, score, i });
+ });
+ return scored.sort((a, b) => a.score - b.score || a.i - b.i).map((s) => s.c);
+}
+
+/**
+ * What a pick types after the `@`: an employee's bare id, a member's bare id — unless an
+ * employee shares it, in which case `user:` disambiguates, since the server resolves a bare
+ * id to the employee first — and `all`.
+ */
+export function mentionInsertId(
+ c: MentionCandidate,
+ candidates: readonly MentionCandidate[],
+): string {
+ if (c.kind === "member" && candidates.some((o) => o.kind === "employee" && o.id === c.id)) {
+ return `user:${c.id}`;
+ }
+ return c.id;
+}
+
+/** What a mention token displays: the employee's name for an agent id (prefixed or bare), the user id for a member, the "everyone" label for `all`. */
+export function mentionLabel(
+ token: string,
+ names: ReadonlyMap<string, string>,
+ allLabel: string,
+): string {
+ if (token === "all") return allLabel;
+ const m = /^(agent|user):(.+)$/.exec(token);
+ if (m) return m[1] === "agent" ? (names.get(m[2]!) ?? m[2]!) : m[2]!;
+ return names.get(token) ?? token;
+}
+
+/** Whether a mention token addresses this user: their `user:` principal, `all`, or their bare id when no employee claims it. */
+export function mentionIsMe(
+ token: string,
+ userId: string,
+ employeeIds: ReadonlySet<string>,
+): boolean {
+ if (userId === "") return false;
+ if (token === "all" || token === `user:${userId}`) return true;
+ return token === userId && !employeeIds.has(userId);
+}
+
+/**
+ * The `@token` the caret sits at the end of, if any: the `@` must start the text or follow a
+ * character that cannot be part of an id, and the token runs unbroken to the caret. Null when
+ * the caret is not inside such a token (the panel then stays closed).
+ */
+export function mentionQueryAt(
+ text: string,
+ caret: number,
+): { start: number; query: string } | null {
+ const before = text.slice(0, caret);
+ const at = before.lastIndexOf("@");
+ if (at === -1) return null;
+ if (at > 0 && /[A-Za-z0-9_@]/.test(before[at - 1]!)) return null;
+ const query = before.slice(at + 1);
+ if (!/^[A-Za-z0-9_:.-]*$/.test(query)) return null;
+ return { start: at, query };
+}
+
+/** Replaces the token at `start`…`caret` with the principal and a trailing space; returns the new text and caret. */
+export function insertMention(
+ text: string,
+ start: number,
+ caret: number,
+ principal: string,
+): { text: string; caret: number } {
+ const inserted = `@${principal} `;
+ const next = text.slice(0, start) + inserted + text.slice(caret);
+ return { text: next, caret: start + inserted.length };
+}
+
+export interface TextRun {
+ text: string;
+ /** The mention token without its `@` (`agent:ceo`, `ceo`, `all`), or null for a plain run. */
+ mention: string | null;
+}
+
+const MENTION_RE = /(^|[^A-Za-z0-9_@])@((?:(?:agent|user):)?[A-Za-z0-9][A-Za-z0-9_.-]*)/g;
+
+/** Splits a message into plain runs and mention runs, in order; trailing `.`/`-` stay outside the mention as the server reads them. */
+export function mentionRuns(text: string): TextRun[] {
+ const runs: TextRun[] = [];
+ let last = 0;
+ for (const m of text.matchAll(MENTION_RE)) {
+ const lead = m[1]!;
+ let token = m[2]!;
+ const trailing = /[.-]+$/.exec(token)?.[0] ?? "";
+ token = token.slice(0, token.length - trailing.length);
+ if (token === "" || /^(agent|user):$/.test(token)) continue;
+ const mentionStart = m.index + lead.length;
+ if (mentionStart > last) runs.push({ text: text.slice(last, mentionStart), mention: null });
+ runs.push({ text: `@${token}`, mention: token });
+ last = mentionStart + 1 + token.length;
+ }
+ if (last < text.length) runs.push({ text: text.slice(last), mention: null });
+ return runs;
+}
+
+/**
+ * The candidates a channel's composer offers: everyone above who is a member of it, `all`
+ * always kept (it means that channel's membership). A null membership — the channel detail
+ * has not arrived, or its request failed — offers the whole list rather than an empty panel:
+ * the server still refuses a mention that leaves the channel, so this degrades to a slower
+ * error rather than to a composer that can name nobody.
+ */
+export function channelMentionCandidates(
+ candidates: readonly MentionCandidate[],
+ memberPrincipals: ReadonlySet<string> | null,
+): MentionCandidate[] {
+ if (memberPrincipals === null) return [...candidates];
+ return candidates.filter((c) => c.kind === "all" || memberPrincipals.has(c.principal));
+}
diff --git a/packages/web/src/features/company/channel-notices.ts b/packages/web/src/features/company/channel-notices.ts
new file mode 100644
index 00000000..0d03d43b
--- /dev/null
+++ b/packages/web/src/features/company/channel-notices.ts
@@ -0,0 +1,104 @@
+/**
+ * A channel's `system` lines in the reader's language (pure, unit tested).
+ *
+ * The server records each such line twice: as the English sentence in `text`, which the day
+ * file itself and the CLI read, and as a structured `notice` — the kind of the event and its
+ * parameters. This module turns the notice into the sentence, with employees under their
+ * display names rather than spelled `agent:<id>`. A line carrying no notice (one written
+ * before the field existed) or one of a kind this build does not know (a newer server) has no
+ * localized sentence, and the view falls back to the English `text` it always had.
+ *
+ * The parameter names are the contract's, not this module's invention: principals arrive as
+ * `agent` / `principal` / `by` / `reportsTo`, a ticket as `ticket` + `title` (which an
+ * employee's job title reuses), a budget event as `agent`, `period`, `percent`, `cost` and
+ * `budget`. A parameter the server omitted renders as an empty string rather than throwing —
+ * a malformed notice must not take the stream down with it.
+ */
+import type { OrgChannelNotice, OrgChannelNoticeKind } from "@prismshadow/penguin-server/api";
+import type { Strings } from "../../lib/strings";
+import { parsePrincipal } from "./principals";
+
+/** The sentences, one function per kind — `S.company.channels.notices`. */
+export type NoticeStrings = Strings["company"]["channels"]["notices"];
+
+/**
+ * Every kind as a value, for the test that checks both dictionaries carry a function for each.
+ * The `satisfies` is what keeps it honest: a kind added to the contract stops compiling here
+ * until it is listed, and a kind that no longer exists stops compiling too.
+ */
+export const NOTICE_KINDS = Object.keys({
+ employee_joined: true,
+ employee_left: true,
+ channel_created: true,
+ channel_archived: true,
+ channel_unarchived: true,
+ channel_joined: true,
+ channel_invited: true,
+ channel_left: true,
+ channel_removed: true,
+ budget_warned: true,
+ budget_paused: true,
+ ticket_blocked: true,
+ ticket_done: true,
+ ticket_rejected: true,
+} satisfies Record<OrgChannelNoticeKind, true>) as OrgChannelNoticeKind[];
+
+/** How a principal in a notice reads: an employee's name, a member's user id, anything else as written. */
+export function noticePrincipalName(raw: string, names: ReadonlyMap<string, string>): string {
+ const p = parsePrincipal(raw);
+ if (p.kind === "agent") return names.get(p.id) ?? p.id;
+ if (p.kind === "user") return p.id;
+ return raw;
+}
+
+/**
+ * The notice as one sentence, or null when this build has no wording for its kind — the
+ * caller then shows the server's English `text`.
+ */
+export function noticeText(
+ notice: OrgChannelNotice,
+ names: ReadonlyMap<string, string>,
+ notices: NoticeStrings,
+): string | null {
+ const params = notice.params;
+ const value = (key: string): string => params[key] ?? "";
+ const who = (key: string): string => noticePrincipalName(value(key), names);
+ const budget = (
+ line: (a: string, percent: string, period: string, cost: string, budget: string) => string,
+ ): string =>
+ line(who("agent"), value("percent"), value("period"), value("cost"), value("budget"));
+ const ticket = (line: (id: string, title: string) => string): string =>
+ line(value("ticket"), value("title"));
+ switch (notice.kind) {
+ case "employee_joined":
+ return notices.employee_joined(who("agent"), value("title"), who("reportsTo"));
+ case "employee_left":
+ return notices.employee_left(who("agent"), who("reportsTo"));
+ case "channel_created":
+ return notices.channel_created(who("by"));
+ case "channel_archived":
+ return notices.channel_archived(who("by"));
+ case "channel_unarchived":
+ return notices.channel_unarchived(who("by"));
+ case "channel_joined":
+ return notices.channel_joined(who("principal"));
+ case "channel_invited":
+ return notices.channel_invited(who("by"), who("principal"));
+ case "channel_left":
+ return notices.channel_left(who("principal"));
+ case "channel_removed":
+ return notices.channel_removed(who("by"), who("principal"));
+ case "budget_warned":
+ return budget(notices.budget_warned);
+ case "budget_paused":
+ return budget(notices.budget_paused);
+ case "ticket_blocked":
+ return ticket(notices.ticket_blocked);
+ case "ticket_done":
+ return ticket(notices.ticket_done);
+ case "ticket_rejected":
+ return ticket(notices.ticket_rejected);
+ default:
+ return null;
+ }
+}
diff --git a/packages/web/src/features/company/channel-sidebar.tsx b/packages/web/src/features/company/channel-sidebar.tsx
new file mode 100644
index 00000000..62ff39f4
--- /dev/null
+++ b/packages/web/src/features/company/channel-sidebar.tsx
@@ -0,0 +1,353 @@
+/**
+ * Company mode's channel list — the sidebar block that stands where development mode lists
+ * conversations, and the collapsed rail's icon-only twin. The all-hands channel is pinned at
+ * the top under its localized label, then the channels the person is in, then the ones it is
+ * not (each with a Join action, which asks first — people may join any channel), then the
+ * archived ones folded away. A row carries its unread count and, when a message names the
+ * reader, an "@me" chip.
+ *
+ * "New channel" is the header's own trailing action rather than a pinned row above the list;
+ * the organization's desks follow the list as their own group (org-session-groups.tsx).
+ *
+ * The list itself is the store's (state/company.tsx): one listing per organization, refreshed
+ * when a message event says a counter moved, so the sidebar, the rail and the channel view
+ * never disagree about what is unread.
+ */
+import { useState } from "react";
+import { NavLink, useNavigate } from "react-router";
+import type { OrgChannelItem } from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
+import { toneInk, toneSurface } from "../../lib/tone";
+import { useAuth } from "../../state/auth";
+import { useCompany } from "../../state/company";
+import { Button } from "../../components/ui/button";
+import { FolderSection, Icon } from "../../components/ui/group-list";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { PlusIcon } from "../../components/ui/icons";
+import { SkeletonList } from "../../components/ui/skeleton";
+import { toastError, toastSuccess } from "../../components/ui/toast";
+import { Truncated } from "../../components/ui/truncated";
+import { orgChannelPath } from "./company-nav";
+import { JoinChannelConfirm, NewChannelDialog } from "./channel-dialogs";
+import { channelLabel, groupChannels, isAllHands } from "./channel-list";
+
+/** A channel (lucide hash): the mark every channel but the all-hands one wears. */
+export const CHANNEL_ICON = "M4 9h16M4 15h16M10 3L8 21M16 3l-2 18";
+
+/** The all-hands channel (lucide users): everyone in the organization is in it. */
+export const ALL_HANDS_ICON =
+ "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M13 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0zM22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75";
+
+export const channelGlyph = (channelId: string): string =>
+ isAllHands(channelId) ? ALL_HANDS_ICON : CHANNEL_ICON;
+
+/** What a row's badges add to its name for a reader who cannot see them. */
+function badgeNote(channel: OrgChannelItem): string | null {
+ if (channel.mentionsMe > 0) return S.company.channels.badgeMentions(channel.mentionsMe);
+ if (channel.unread > 0) return S.company.channels.badgeUnread(channel.unread);
+ return null;
+}
+
+/**
+ * "New channel", at the right end of the channel list's header — the group-header action
+ * shape, not a pinned row: development mode's pinned slot holds "New chat" because a
+ * conversation is what a person makes there several times a day, while a channel is made
+ * rarely and belongs beside the list it joins. The collapsed rail carries no counterpart for
+ * the same reason. Creating one opens it.
+ */
+function NewChannelButton({
+ projectId,
+ orgId,
+ onNavigate,
+}: {
+ projectId: string;
+ orgId: string;
+ onNavigate?: () => void;
+}) {
+ const [open, setOpen] = useState(false);
+ const navigate = useNavigate();
+ const company = useCompany();
+ const taken = (company.channels ?? []).map((c) => c.channelId);
+ const label = S.company.channels.newChannel;
+ return (
+ <>
+ <button
+ type="button"
+ title={label}
+ aria-label={label}
+ onClick={() => setOpen(true)}
+ className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ >
+ <PlusIcon size={ICON_SIZE.groupHeaderAction} />
+ </button>
+ <NewChannelDialog
+ open={open}
+ projectId={projectId}
+ orgId={orgId}
+ taken={taken}
+ onClose={() => setOpen(false)}
+ onCreated={(channel) => {
+ setOpen(false);
+ toastSuccess(S.company.channels.created);
+ void company.reloadChannels();
+ navigate(orgChannelPath(projectId, orgId, channel.channelId));
+ onNavigate?.();
+ }}
+ />
+ </>
+ );
+}
+
+/** One row: the channel's glyph and label, its unread count, and the "@me" chip when a message names the reader. */
+function ChannelRow({
+ projectId,
+ orgId,
+ channel,
+ onNavigate,
+ join,
+}: {
+ projectId: string;
+ orgId: string;
+ channel: OrgChannelItem;
+ onNavigate?: () => void;
+ /** Rendered beside the row for a channel the person has not joined. */
+ join?: () => void;
+}) {
+ const label = channelLabel(channel, S.company.channels.allHands);
+ const note = badgeNote(channel);
+ const unread = channel.unread > 0;
+ return (
+ <li className="group relative flex items-center rounded-md transition-colors duration-150 hover:bg-gray-200/50 dark:hover:bg-gray-800/70">
+ <NavLink
+ to={orgChannelPath(projectId, orgId, channel.channelId)}
+ onClick={() => onNavigate?.()}
+ title={channel.purpose !== "" ? `${label} · ${channel.purpose}` : label}
+ aria-label={note !== null ? `${label} · ${note}` : label}
+ className={({ isActive }) =>
+ `flex min-w-0 flex-1 items-center ${ICON_GAP.row} rounded-md px-2.5 py-1.5 text-sm transition-colors duration-150 ${
+ isActive
+ ? "bg-gray-200/70 font-medium text-gray-900 dark:bg-gray-800 dark:text-gray-100"
+ : unread
+ ? "font-medium text-gray-900 dark:text-gray-100"
+ : "text-gray-600 dark:text-gray-400"
+ }`
+ }
+ >
+ <span className="shrink-0 text-gray-400 dark:text-gray-500">
+ <Icon d={channelGlyph(channel.channelId)} size={ICON_SIZE.rowLead} />
+ </span>
+ <Truncated text={label} className="min-w-0 flex-1" />
+ {channel.mentionsMe > 0 && (
+ <span
+ className={`shrink-0 rounded px-1 text-[10px] font-semibold ${toneSurface.attention}`}
+ >
+ {S.company.channels.mentionChip}
+ </span>
+ )}
+ {channel.unread > 0 && (
+ <span className="shrink-0 text-[11px] tabular-nums text-gray-500 dark:text-gray-400">
+ {channel.unread}
+ </span>
+ )}
+ </NavLink>
+ {join !== undefined && (
+ /* Overlaid rather than laid out: reserving a slot would shorten the row's own fill
+ and its label for a control that is invisible at rest. Pointer events follow the
+ opacity, so a hidden button never takes a tap (the development list's rule). */
+ <button
+ type="button"
+ onClick={join}
+ className="pointer-events-none absolute right-1 top-1/2 -translate-y-1/2 rounded bg-gray-200 px-1.5 py-0.5 text-[11px] text-gray-600 opacity-0 transition-opacity duration-150 hover:text-gray-900 focus:pointer-events-auto focus:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100 dark:bg-gray-700 dark:text-gray-300 dark:hover:text-gray-100"
+ >
+ {S.company.channels.join}
+ </button>
+ )}
+ </li>
+ );
+}
+
+/** A run's title inside the list (My channels / Other channels), with how many it holds. */
+function GroupTitle({ label, count }: { label: string; count: number }) {
+ return (
+ <p className="flex items-center gap-1.5 px-2.5 pb-0.5 pt-2.5 text-[11px] font-medium text-gray-500 dark:text-gray-400">
+ <span className="min-w-0 truncate">{label}</span>
+ <span className="tabular-nums text-gray-400 dark:text-gray-500">{count}</span>
+ </p>
+ );
+}
+
+export function ChannelSidebar({
+ projectId,
+ orgId,
+ onNavigate,
+}: {
+ projectId: string;
+ orgId: string;
+ onNavigate?: () => void;
+}) {
+ const company = useCompany();
+ const { user } = useAuth();
+ const [archivedOpen, setArchivedOpen] = useState(false);
+ const [joining, setJoining] = useState<string | null>(null);
+ /** The channel whose Join was clicked, waiting on the prompt; null when nothing is asked. */
+ const [pendingJoin, setPendingJoin] = useState<OrgChannelItem | null>(null);
+ const channels = company.channels;
+
+ const join = async (channel: OrgChannelItem) => {
+ if (joining !== null) return;
+ setJoining(channel.channelId);
+ setPendingJoin(null);
+ try {
+ await api.addOrgChannelMember(projectId, orgId, channel.channelId, {
+ principal: `user:${user?.userId ?? ""}`,
+ });
+ toastSuccess(S.company.channels.joined);
+ // The listing is what the open channel's view watches to re-read its own detail, so
+ // this one reload replaces the Join prompt there too (channel-stream.joinedElsewhere).
+ await company.reloadChannels();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setJoining(null);
+ }
+ };
+
+ const groups = groupChannels(channels ?? [], S.company.channels.allHands);
+ const row = (channel: OrgChannelItem, joinable = false) => (
+ <ChannelRow
+ key={channel.channelId}
+ projectId={projectId}
+ orgId={orgId}
+ channel={channel}
+ {...(onNavigate ? { onNavigate } : {})}
+ {...(joinable ? { join: () => setPendingJoin(channel) } : {})}
+ />
+ );
+
+ return (
+ <>
+ {/* The list's header, at the height and density of the development list's own, with
+ "New channel" as its trailing action. */}
+ <div className="mt-3 flex items-center justify-between gap-2 px-1 pt-2">
+ <span className="px-1 text-[11px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500">
+ {S.company.channels.listTitle}
+ </span>
+ <NewChannelButton
+ projectId={projectId}
+ orgId={orgId}
+ {...(onNavigate ? { onNavigate } : {})}
+ />
+ </div>
+ {channels === null ? (
+ company.channelsError !== null ? (
+ <div className="flex items-center justify-between gap-2 px-2.5 py-1">
+ <span className={`text-xs ${toneInk.danger}`}>{S.company.channels.loadFailed}</span>
+ <Button size="sm" onClick={() => void company.reloadChannels()}>
+ {S.common.retry}
+ </Button>
+ </div>
+ ) : (
+ <SkeletonList rows={3} />
+ )
+ ) : (
+ <>
+ <ul className="space-y-0.5 pt-1">
+ {groups.allHands !== null && row(groups.allHands)}
+ {groups.mine.length > 0 && (
+ <li>
+ <GroupTitle label={S.company.channels.mine} count={groups.mine.length} />
+ </li>
+ )}
+ {groups.mine.map((c) => row(c))}
+ {groups.others.length > 0 && (
+ <li>
+ <GroupTitle label={S.company.channels.others} count={groups.others.length} />
+ </li>
+ )}
+ {groups.others.map((c) => row(c, true))}
+ </ul>
+ {groups.archived.length > 0 && (
+ <FolderSection
+ label={`${S.company.channels.archivedGroup} (${groups.archived.length})`}
+ open={archivedOpen}
+ onToggle={() => setArchivedOpen((v) => !v)}
+ >
+ <ul className="space-y-0.5">{groups.archived.map((c) => row(c))}</ul>
+ </FolderSection>
+ )}
+ {groups.allHands === null &&
+ groups.mine.length === 0 &&
+ groups.others.length === 0 &&
+ groups.archived.length === 0 && (
+ <p className="px-2.5 pt-2 text-xs text-gray-400 dark:text-gray-600">
+ {S.company.channels.noChannels}
+ </p>
+ )}
+ </>
+ )}
+ <JoinChannelConfirm
+ open={pendingJoin !== null}
+ busy={joining !== null}
+ onClose={() => setPendingJoin(null)}
+ onConfirm={() => {
+ if (pendingJoin !== null) void join(pendingJoin);
+ }}
+ />
+ </>
+ );
+}
+
+/** The collapsed rail's channels: the same rows as icons, each carrying its own count. */
+export function ChannelRailRows({ projectId, orgId }: { projectId: string; orgId: string }) {
+ const company = useCompany();
+ const groups = groupChannels(company.channels ?? [], S.company.channels.allHands);
+ const rows = [
+ ...(groups.allHands !== null ? [groups.allHands] : []),
+ ...groups.mine,
+ ...groups.others,
+ ];
+ return (
+ <>
+ {rows.map((channel) => {
+ const label = channelLabel(channel, S.company.channels.allHands);
+ const note = badgeNote(channel);
+ const name = note !== null ? `${label} · ${note}` : label;
+ return (
+ <NavLink
+ key={channel.channelId}
+ to={orgChannelPath(projectId, orgId, channel.channelId)}
+ title={name}
+ aria-label={name}
+ className={({ isActive }) =>
+ `relative flex h-8 w-8 items-center justify-center rounded-md transition-colors duration-150 ${
+ isActive
+ ? "bg-gray-200/70 text-gray-900 dark:bg-gray-800 dark:text-gray-100"
+ : "text-gray-500 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ }`
+ }
+ >
+ <GlyphIcon d={channelGlyph(channel.channelId)} size={18} />
+ {channel.unread > 0 && (
+ // The count itself, not a bare dot: the rail is the whole sidebar while
+ // collapsed, and "something is waiting" without "how much" sends the reader
+ // back to expanding it just to look.
+ <span
+ aria-hidden
+ className={`absolute -right-0.5 -top-0.5 min-w-[14px] rounded-full px-1 text-[9px] font-semibold leading-[14px] tabular-nums ${
+ channel.mentionsMe > 0
+ ? toneSurface.attention
+ : "bg-gray-300 text-gray-800 dark:bg-gray-700 dark:text-gray-100"
+ }`}
+ >
+ {channel.unread > 99 ? "99+" : channel.unread}
+ </span>
+ )}
+ </NavLink>
+ );
+ })}
+ </>
+ );
+}
diff --git a/packages/web/src/features/company/channel-stream.ts b/packages/web/src/features/company/channel-stream.ts
new file mode 100644
index 00000000..ca92e7c7
--- /dev/null
+++ b/packages/web/src/features/company/channel-stream.ts
@@ -0,0 +1,225 @@
+/**
+ * A channel's stream shaping (pure, unit tested): the loaded day files in
+ * order become one list of items — a separator per day, the unread divider at the read
+ * cursor, `system` messages on their own, and consecutive messages by one sender folded
+ * into a run under a single header — plus which side of the stream a run sits on and where
+ * each of its bubbles falls inside it, the day arithmetic the separators and the two paging
+ * decisions need (how far the opening load walks back, and which day "earlier" fetches), the
+ * immutable append a live message goes through, and when a join made on another surface
+ * obliges the view to re-read its own detail.
+ */
+import type { OrgChannelMessage } from "@prismshadow/penguin-server/api";
+import { parsePrincipal } from "./principals";
+
+/** One day file as loaded: the organization-timezone date and its messages in file order. */
+export interface ChannelDay {
+ date: string;
+ messages: OrgChannelMessage[];
+}
+
+export type StreamItem =
+ | { kind: "day"; date: string }
+ | { kind: "unread" }
+ | { kind: "system"; message: OrgChannelMessage }
+ | { kind: "run"; sender: string; hop: number; messages: OrgChannelMessage[] };
+
+/** Messages by one sender closer together than this join one run (the same idiom as any chat client). */
+export const RUN_GAP_MS = 5 * 60_000;
+
+/**
+ * Whether a run's header shows its hop count. Hop 1 is the ordinary case — an employee
+ * answering a trigger — and a chip on every single answer says nothing; from the second hop
+ * the message is an agent answering an agent, which is the thing worth seeing.
+ */
+export function hopChipShown(hop: number): boolean {
+ return hop >= 2;
+}
+
+/**
+ * Whether a run is the reader's own, which is what puts it on the right of the stream with
+ * neither an avatar nor a name. Only a `user:` principal can be: an employee writes as
+ * `agent:`, and a reader whose id is not known yet (`me` is "" until the session loads) owns
+ * nothing rather than owning every unnamed message.
+ */
+export function isOwnRun(sender: string, me: string): boolean {
+ if (me === "") return false;
+ const p = parsePrincipal(sender);
+ return p.kind === "user" && p.id === me;
+}
+
+/** Where one bubble of a run sits: which side of the stream, and its place inside the run. */
+export interface BubbleShape {
+ /** The reader's own message: the right-hand side, without an avatar or a name above it. */
+ own: boolean;
+ /** First of the run — the bubble under the header the sender's name and avatar share. */
+ first: boolean;
+ /** Last of the run — the run's tail, the bubble whose corner nearest its side is squared. */
+ last: boolean;
+}
+
+/**
+ * How the bubble at `index` of a run is drawn. A run of one message is both its first and its
+ * last bubble, so it sits under the name and carries the squared corner at once.
+ */
+export function bubbleShape(
+ run: { sender: string; messages: readonly OrgChannelMessage[] },
+ index: number,
+ me: string,
+): BubbleShape {
+ return {
+ own: isOwnRun(run.sender, me),
+ first: index === 0,
+ last: index === run.messages.length - 1,
+ };
+}
+
+/**
+ * The stream in display order. The unread divider goes before the first message whose id
+ * sorts after the read cursor (ids sort in write order, which is how the server counts
+ * unread), and it breaks a run: the messages either side of it must not share a header. No
+ * cursor means the reader has never marked anything — every message is technically unread,
+ * and a divider above the whole history would say nothing, so none is drawn.
+ */
+export function buildStream(
+ days: readonly ChannelDay[],
+ opts: { unreadAfterId?: string | null; gapMs?: number } = {},
+): StreamItem[] {
+ const gap = opts.gapMs ?? RUN_GAP_MS;
+ const cursor = opts.unreadAfterId ?? null;
+ const out: StreamItem[] = [];
+ let divided = false;
+ for (const day of days) {
+ out.push({ kind: "day", date: day.date });
+ for (const m of day.messages) {
+ if (cursor !== null && !divided && m.id > cursor) {
+ out.push({ kind: "unread" });
+ divided = true;
+ }
+ if (parsePrincipal(m.sender).kind === "system") {
+ out.push({ kind: "system", message: m });
+ continue;
+ }
+ const last = out[out.length - 1];
+ if (
+ last !== undefined &&
+ last.kind === "run" &&
+ last.sender === m.sender &&
+ last.hop === m.hop &&
+ Date.parse(m.time) - Date.parse(last.messages[last.messages.length - 1]!.time) <= gap
+ ) {
+ last.messages.push(m);
+ continue;
+ }
+ out.push({ kind: "run", sender: m.sender, hop: m.hop, messages: [m] });
+ }
+ }
+ return out;
+}
+
+const pad2 = (n: number): string => (n < 10 ? `0${n}` : `${n}`);
+
+/** `yyyy-mm-dd` shifted by whole days; null for anything not of that shape. */
+export function shiftDate(date: string, deltaDays: number): string | null {
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date);
+ if (!m) return null;
+ const d = new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]) + deltaDays));
+ if (Number.isNaN(d.getTime())) return null;
+ return `${d.getUTCFullYear()}-${pad2(d.getUTCMonth() + 1)}-${pad2(d.getUTCDate())}`;
+}
+
+/** How a day separator names its day, relative to the organization's today. */
+export function dayKind(date: string, today: string): "today" | "yesterday" | "other" {
+ if (date === today) return "today";
+ if (shiftDate(today, -1) === date) return "yesterday";
+ return "other";
+}
+
+/**
+ * The day file to load next when paging back: the newest day older than the earliest one
+ * loaded, from the server's newest-first list; null at the start of history.
+ */
+export function earlierDay(days: readonly string[], earliest: string): string | null {
+ return days.find((d) => d < earliest) ?? null;
+}
+
+/** How many messages the opening load tries to have in hand before it stops walking back. */
+export const INITIAL_MESSAGES = 30;
+
+/** How many day files that walk may hold in total, today's included — its bound on requests. */
+export const INITIAL_DAYS_MAX = 7;
+
+/**
+ * The day file the opening load fetches next, or null when it has what it needs: enough
+ * messages, the day budget spent, or no history left. A channel is served one day file at a
+ * time, and today's may well be empty — without this walk a channel opened on a quiet day
+ * shows a blank stream with its whole history hidden behind the "earlier" button.
+ *
+ * `loaded` is what the load holds so far, oldest day first; `days` is the server's
+ * newest-first list of the day files that exist. Only today's file can come back empty (a day
+ * file is written when a message lands), so each further step adds at least one message and
+ * the walk always terminates.
+ */
+export function initialDaysToLoad(
+ days: readonly string[],
+ today: string,
+ loaded: readonly ChannelDay[],
+ want: number = INITIAL_MESSAGES,
+): string | null {
+ if (messageCount(loaded) >= want) return null;
+ if (loaded.length >= INITIAL_DAYS_MAX) return null;
+ return earlierDay(days, loaded[0]?.date ?? today);
+}
+
+/**
+ * Whether the view has to re-read its channel detail because the reader joined from somewhere
+ * else. The sidebar's own Join posts and then reloads the LISTING; the detail behind the
+ * composer is not part of that, so the view would keep offering Join until a re-navigation.
+ *
+ * Only the moment the listing flips to "member" counts. A listing that has said so all along
+ * while the detail disagrees is the server's own answer, and re-reading on every render would
+ * turn that disagreement into a refetch loop.
+ */
+export function joinedElsewhere(
+ previous: boolean | null,
+ listed: boolean | null,
+ detailIsMember: boolean,
+): boolean {
+ return previous === false && listed === true && !detailIsMember;
+}
+
+/**
+ * A message appended to its day (created at the end when that day is not loaded yet) — a
+ * new array, or the same one back when the id is already present, so a live event that
+ * repeats a message the send already added changes nothing.
+ */
+export function appendMessage(
+ days: ChannelDay[],
+ date: string,
+ message: OrgChannelMessage,
+): ChannelDay[] {
+ if (days.some((d) => d.messages.some((m) => m.id === message.id))) return days;
+ const idx = days.findIndex((d) => d.date === date);
+ if (idx === -1) return [...days, { date, messages: [message] }];
+ return days.map((d, i) => (i === idx ? { ...d, messages: [...d.messages, message] } : d));
+}
+
+/** The id of the newest loaded message, or null when nothing is loaded. */
+export function lastMessageId(days: readonly ChannelDay[]): string | null {
+ for (let i = days.length - 1; i >= 0; i--) {
+ const list = days[i]!.messages;
+ if (list.length > 0) return list[list.length - 1]!.id;
+ }
+ return null;
+}
+
+/** How many messages are loaded across every day. */
+export function messageCount(days: readonly ChannelDay[]): number {
+ return days.reduce((n, d) => n + d.messages.length, 0);
+}
+
+/** ISO timestamp → local `HH:mm` (the day separator already names the day); "" when unparsable. */
+export function clockTime(iso: string): string {
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return "";
+ return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
+}
diff --git a/packages/web/src/features/company/channel-view.tsx b/packages/web/src/features/company/channel-view.tsx
new file mode 100644
index 00000000..64257c78
--- /dev/null
+++ b/packages/web/src/features/company/channel-view.tsx
@@ -0,0 +1,819 @@
+/**
+ * One channel: its header, the stream of the loaded days — a separator per day, one bubble per
+ * message, each body rendered as Markdown with its @-mentions kept as chips (stronger when
+ * they address the reader), `system` messages as centred banners in the reader's own language,
+ * ticket and session references as chips that open them, an unread divider at the read
+ * cursor — and the composer beneath it. The view follows the stream while it is at the bottom;
+ * scrolled up, new messages collect behind a pill that returns to the latest. Sitting at the
+ * bottom of today marks this channel read, which is what clears its badge in the sidebar and
+ * the rail. Nothing here delivers to an employee unless it is @-mentioned, and only inside
+ * this channel's membership; the empty state and the header's "?" say so.
+ *
+ * Opening a channel assembles its whole first screen before the first render — today's day
+ * file, then earlier ones until the stream holds enough messages or the day budget runs out
+ * (initialDaysToLoad) — so the reader lands at the bottom of real history rather than on a
+ * blank day, and without the scroll jump a prepend after the first paint would cost. Anything
+ * older stays behind "earlier", which prepends one day file per click.
+ *
+ * The stream is drawn the way every chat client draws one, because a channel is read the way
+ * every chat is. Somebody else's run stands on the left: the avatar once, top-aligned so that
+ * it sits beside the sender's name — with the relay chip beside it from the second hop on, the
+ * whole @-chain rule in its tooltip — and the run's bubbles under both, in the column the name
+ * starts. Who is speaking is one mark, so the two halves of it stay on one line: an avatar tied
+ * to the run's last bubble drifts a screenful below its own name as soon as a message runs
+ * long. The reader's own run stands on the right in its own tint, with no avatar and no name
+ * (a screen reader gets one, since a side and a colour are not something every reader can
+ * read). Each bubble carries its own time at its bottom-right, inside it: a time that only
+ * appears on hover is a time a touch reader never sees, and one time per run leaves every
+ * later message in a long run unstamped.
+ *
+ * A `system` line is one sentence, so it stays one muted line rather than a Markdown body: the
+ * server writes it twice — as English text and as a structured notice — and the notice is what
+ * this renders (channel-notices.ts), falling back to the text for a line written before that
+ * field existed.
+ *
+ * A channel the reader has not joined offers Join instead of the composer — people may read
+ * every channel but post only in the ones they are in; joining asks first, because it is what
+ * puts this channel's @-mentions in front of the reader from then on. An archived channel says
+ * it is read-only. Only the messages are essential: the chart and the Project's member list feed
+ * names and the invite picker, so a hiccup there degrades names to ids rather than blocking
+ * the page.
+ */
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import { useNavigate, useParams } from "react-router";
+import type { OrgChannelDetail, OrgChannelMessage } from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { formatDateTime } from "../../lib/format";
+import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
+import { useDocumentTitle } from "../../lib/use-document-title";
+import { toneDot, toneInk, toneStrip } from "../../lib/tone";
+import { useAuth } from "../../state/auth";
+import { useCompany, useCompanyEvents } from "../../state/company";
+import { AgentAvatar } from "../../components/ui/agent-avatar";
+import { Button } from "../../components/ui/button";
+import { EmptyState } from "../../components/ui/empty-state";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { NAV_ICONS } from "../../components/ui/icons";
+import { Skeleton } from "../../components/ui/skeleton";
+import { toastError, toastSuccess } from "../../components/ui/toast";
+import { createStreamFollow, stickToBottom } from "../chat/stream-follow";
+import { useOrg } from "./org-layout";
+import { principalLabel } from "./shared";
+import { orgKey } from "./company-nav";
+import { ChannelComposer } from "./channel-composer";
+import { ChannelHeader } from "./channel-header";
+import { ChannelMessageBody, ChannelReaderProvider, MentionChip } from "./channel-markdown";
+import { noticeText } from "./channel-notices";
+import { JoinChannelConfirm } from "./channel-dialogs";
+import { DEFAULT_CHANNEL_ID, channelLabel } from "./channel-list";
+import {
+ channelMentionCandidates,
+ mentionCandidates,
+ mentionIsMe,
+ mentionLabel,
+ mentionRuns,
+} from "./channel-mentions";
+import {
+ appendMessage,
+ bubbleShape,
+ buildStream,
+ clockTime,
+ dayKind,
+ earlierDay,
+ hopChipShown,
+ initialDaysToLoad,
+ isOwnRun,
+ joinedElsewhere,
+ lastMessageId,
+ messageCount,
+} from "./channel-stream";
+import type { BubbleShape, ChannelDay, StreamItem } from "./channel-stream";
+import { parsePrincipal } from "./principals";
+
+/** What the first response fixes for this channel: today, the day list, and the read cursor the divider is drawn at. */
+interface StreamMeta {
+ today: string;
+ /** Every day of this channel with a file, newest first. */
+ days: string[];
+ unreadAfterId: string | null;
+}
+
+/** Downward arrow on the return-to-latest pill (lucide arrow-down). */
+const ARROW_DOWN_ICON = "M12 5v14M6 13l6 6 6-6";
+
+/** The avatar that leads somebody else's run, in pixels — a tile, so one rung above a line glyph. */
+const RUN_AVATAR_PX = 28;
+
+/**
+ * The two bubble surfaces. The reader's own takes the app's brand blue rather than a tone from
+ * lib/tone.ts: which side of a conversation wrote a message is an identity, not a judgement,
+ * and a status hue would announce a state the message does not have. It is also the only tint
+ * that stays clearly apart from the neutral bubble under every accent — `--accent-bg` is grey
+ * in the default neutral theme, where a wash of it is the neutral bubble again.
+ */
+const BUBBLE_SURFACE = {
+ other: "bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200",
+ own: "bg-brand-50 text-gray-900 dark:bg-brand-950 dark:text-gray-100",
+} as const;
+
+/**
+ * A bubble's corners: 2xl all round, except on the last bubble of a run, where the corner
+ * nearest the run's tail is squared — bottom-left on somebody else's side of the stream,
+ * bottom-right on the reader's own. Every corner is named rather than layering a per-corner
+ * utility over the all-corner one, so the result does not depend on which of the two the
+ * stylesheet emits last.
+ */
+function bubbleCorners(shape: BubbleShape): string {
+ if (!shape.last) return "rounded-2xl";
+ return shape.own
+ ? "rounded-bl-2xl rounded-br-sm rounded-tl-2xl rounded-tr-2xl"
+ : "rounded-bl-sm rounded-br-2xl rounded-tl-2xl rounded-tr-2xl";
+}
+
+export function ChannelView() {
+ const { projectId, orgId, org } = useOrg();
+ const params = useParams<{ channelId: string }>();
+ const channelId = params.channelId ?? DEFAULT_CHANNEL_ID;
+ const navigate = useNavigate();
+ const company = useCompany();
+ const { user } = useAuth();
+ const [detail, setDetail] = useState<OrgChannelDetail | null>(null);
+ const [detailError, setDetailError] = useState<string | null>(null);
+ const [days, setDays] = useState<ChannelDay[] | null>(null);
+ const [meta, setMeta] = useState<StreamMeta | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [employees, setEmployees] = useState<
+ ReadonlyArray<{ agentId: string; name: string; title: string }>
+ >([]);
+ const [members, setMembers] = useState<string[]>([]);
+ const [loadingEarlier, setLoadingEarlier] = useState(false);
+ const [joining, setJoining] = useState(false);
+ const [confirmJoin, setConfirmJoin] = useState(false);
+ /** Messages that arrived while the view was scrolled up; shown on the pill. */
+ const [pendingNew, setPendingNew] = useState(0);
+ const [showJump, setShowJump] = useState(false);
+ const [atBottom, setAtBottom] = useState(true);
+ const listRef = useRef<HTMLDivElement>(null);
+ const follow = useMemo(createStreamFollow, []);
+ /** The newest id already posted as read: the cursor is written once per new tail, not per render. */
+ const markedRef = useRef<string | null>(null);
+ /** Scroll anchoring across a prepend: the height before the earlier day landed, and which day was first. */
+ const heightRef = useRef(0);
+ const firstDayRef = useRef<string | null>(null);
+ /**
+ * Which opening load is still the current one. The walk back through earlier days is several
+ * round trips long, and a channel switched during it would otherwise be overwritten by the
+ * stream of the channel the reader left.
+ */
+ const loadSeq = useRef(0);
+ /** What the sidebar's listing last said about this reader's membership (see joinedElsewhere). */
+ const listedMemberRef = useRef<boolean | null>(null);
+ const me = user?.userId ?? "";
+ const myPrincipal = `user:${me}`;
+ const myKey = orgKey(projectId, orgId);
+ const label = detail === null ? channelId : channelLabel(detail, S.company.channels.allHands);
+ useDocumentTitle(org ? `${org.name} · ${label}` : label);
+
+ // Another channel's stream must not linger while this one loads: everything the stream
+ // holds is keyed on the channel, the read marker included.
+ useEffect(() => {
+ setDays(null);
+ setMeta(null);
+ setError(null);
+ setDetail(null);
+ setDetailError(null);
+ setPendingNew(0);
+ setConfirmJoin(false);
+ markedRef.current = null;
+ firstDayRef.current = null;
+ listedMemberRef.current = null;
+ follow.resume();
+ }, [projectId, orgId, channelId, follow]);
+
+ const loadDetail = useCallback(async () => {
+ try {
+ const res = await api.getOrgChannel(projectId, orgId, channelId);
+ setDetail(res);
+ setDetailError(null);
+ } catch (e) {
+ setDetailError(apiErrorText(e));
+ }
+ }, [projectId, orgId, channelId]);
+
+ const load = useCallback(async () => {
+ const seq = ++loadSeq.current;
+ /** Still the load this channel wants: a later one (or another channel) supersedes it. */
+ const current = () => loadSeq.current === seq;
+ // Names and invite candidates are best effort: the stream must not wait on them.
+ void api
+ .getOrgChart(projectId, orgId)
+ .then((ch) =>
+ setEmployees(
+ ch.employees.map((e) => ({ agentId: e.agentId, name: e.name, title: e.title })),
+ ),
+ )
+ .catch(() => undefined);
+ void api
+ .listMembers(projectId)
+ .then((res) => setMembers(res.members.map((m) => m.userId)))
+ .catch(() => undefined);
+ void loadDetail();
+ try {
+ const res = await api.getOrgChannelMessages(projectId, orgId, channelId);
+ if (!current()) return;
+ let loaded: ChannelDay[] = [{ date: res.date, messages: res.messages }];
+ try {
+ // Walk back one day file at a time until the first screen holds history. Sequential
+ // rather than parallel: how far back to go depends on how much each day turned out
+ // to hold, and a quiet channel would otherwise pay for seven requests it does not need.
+ for (;;) {
+ const target = initialDaysToLoad(res.days, res.date, loaded);
+ if (target === null) break;
+ const older = await api.getOrgChannelMessages(projectId, orgId, channelId, target);
+ if (!current()) return;
+ loaded = [{ date: target, messages: older.messages }, ...loaded];
+ }
+ } catch {
+ // An earlier day that fails is not fatal — today is already in hand and "earlier"
+ // stays for another attempt — so the stream renders with what the walk did reach.
+ }
+ setDays(loaded);
+ setMeta((prev) => ({
+ today: res.date,
+ days: res.days,
+ // The divider stays where the first load put it: marking read must not move it out
+ // from under the reader.
+ unreadAfterId: prev?.unreadAfterId ?? res.lastReadId ?? null,
+ }));
+ setError(null);
+ } catch (e) {
+ if (!current()) return;
+ setError(apiErrorText(e));
+ }
+ }, [projectId, orgId, channelId, loadDetail]);
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ // A Join from the sidebar's own row reloads the listing, not this detail: without this the
+ // view would keep offering Join under a channel the reader is already in (joinedElsewhere).
+ const listedMember = company.channels?.find((c) => c.channelId === channelId)?.isMember ?? null;
+ useEffect(() => {
+ // Only once there is a detail to compare against: a listing read before the first detail
+ // landed is not a membership this view has ever shown.
+ if (detail === null) return;
+ const previous = listedMemberRef.current;
+ listedMemberRef.current = listedMember;
+ if (joinedElsewhere(previous, listedMember, detail.isMember)) void loadDetail();
+ }, [listedMember, detail, loadDetail]);
+
+ const loadEarlier = async () => {
+ if (days === null || meta === null || loadingEarlier) return;
+ const target = earlierDay(meta.days, days[0]?.date ?? meta.today);
+ if (target === null) return;
+ setLoadingEarlier(true);
+ try {
+ const res = await api.getOrgChannelMessages(projectId, orgId, channelId, target);
+ setDays((prev) =>
+ prev === null || prev.some((d) => d.date === target)
+ ? prev
+ : [{ date: target, messages: res.messages }, ...prev],
+ );
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setLoadingEarlier(false);
+ }
+ };
+
+ // A new message in THIS channel lands in the stream without a refetch. While the view is
+ // at the bottom it simply appears; scrolled up, it counts towards the pill. Another
+ // channel's message only moves its own badge, which the store owns. The append is decided
+ // here, not inside a setDays updater: bumping the pill is a side effect and an updater must
+ // stay pure. It reads the latest list through a ref rather than this render's `days`, so
+ // two messages arriving before React re-renders both land instead of the second
+ // overwriting the first.
+ const latestDays = useRef(days);
+ latestDays.current = days;
+ useCompanyEvents((ev) => {
+ if (ev.type !== "org_channel" || orgKey(ev.projectId, ev.orgId) !== myKey) return;
+ if (ev.channelId !== channelId) return;
+ const current = latestDays.current;
+ if (meta === null || current === null) return;
+ const next = appendMessage(current, meta.today, ev.message);
+ // Unchanged means the message is already in the stream — the reader's own, appended on send.
+ if (next === current) return;
+ latestDays.current = next;
+ setDays(next);
+ if (!follow.stick) setPendingNew((n) => n + 1);
+ });
+
+ const syncScrollState = () => {
+ const el = listRef.current;
+ const stick = follow.stick;
+ setAtBottom(stick);
+ setShowJump(!stick && el !== null && el.scrollHeight - el.scrollTop - el.clientHeight > 1);
+ if (stick) setPendingNew(0);
+ };
+
+ const onScroll = () => {
+ const el = listRef.current;
+ if (!el) return;
+ follow.scrolled({
+ scrollTop: el.scrollTop,
+ scrollHeight: el.scrollHeight,
+ clientHeight: el.clientHeight,
+ });
+ syncScrollState();
+ };
+
+ // Before paint: keep the reader's place when an earlier day lands above the viewport, and
+ // otherwise stick to the bottom while following.
+ useLayoutEffect(() => {
+ const el = listRef.current;
+ if (!el || days === null) return;
+ const firstDay = days[0]?.date ?? null;
+ const prepended = firstDayRef.current !== null && firstDay !== firstDayRef.current;
+ if (prepended && !follow.stick) el.scrollTop += el.scrollHeight - heightRef.current;
+ firstDayRef.current = firstDay;
+ heightRef.current = el.scrollHeight;
+ if (follow.stick) stickToBottom(el, follow);
+ syncScrollState();
+ // syncScrollState is recreated per render; the effect keys on the stream's content only.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [days, follow]);
+
+ // The composer growing, or the window resizing, shrinks the stream: re-snap while following.
+ useEffect(() => {
+ const el = listRef.current;
+ if (!el || typeof ResizeObserver === "undefined") return;
+ const ro = new ResizeObserver(() => {
+ heightRef.current = el.scrollHeight;
+ if (follow.stick) stickToBottom(el, follow);
+ });
+ ro.observe(el);
+ if (el.firstElementChild) ro.observe(el.firstElementChild);
+ return () => ro.disconnect();
+ }, [follow, days === null]);
+
+ // Sitting at the bottom of the newest day marks this channel's tail as read and clears its
+ // badge; the store's copy is cleared first so the sidebar does not wait for the round trip.
+ const lastId = days === null ? null : lastMessageId(days);
+ const { markChannelRead } = company;
+ useEffect(() => {
+ if (!atBottom || lastId === null || lastId === markedRef.current) return;
+ markedRef.current = lastId;
+ markChannelRead(channelId);
+ void api
+ .readOrgChannel(projectId, orgId, channelId, { upTo: lastId })
+ .then(() => markChannelRead(channelId))
+ .catch(() => undefined);
+ }, [atBottom, lastId, markChannelRead, projectId, orgId, channelId]);
+
+ const jumpToLatest = () => {
+ const el = listRef.current;
+ if (!el) return;
+ follow.resume();
+ stickToBottom(el, follow);
+ syncScrollState();
+ };
+
+ const send = async (text: string): Promise<boolean> => {
+ try {
+ const msg = await api.sendOrgChannelMessage(projectId, orgId, channelId, { text });
+ follow.resume();
+ setDays((prev) =>
+ prev === null ? prev : appendMessage(prev, meta?.today ?? msg.time.slice(0, 10), msg),
+ );
+ return true;
+ } catch (e) {
+ toastError(apiErrorText(e));
+ return false;
+ }
+ };
+
+ const join = async () => {
+ if (joining) return;
+ setJoining(true);
+ setConfirmJoin(false);
+ try {
+ await api.addOrgChannelMember(projectId, orgId, channelId, { principal: myPrincipal });
+ toastSuccess(S.company.channels.joined);
+ await loadDetail();
+ void company.reloadChannels();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setJoining(false);
+ }
+ };
+
+ const names = useMemo(() => new Map(employees.map((e) => [e.agentId, e.name])), [employees]);
+ const employeeIds = useMemo(() => new Set(employees.map((e) => e.agentId)), [employees]);
+ // Who the mention chips inside the rendered bodies are measured against. Memoized because it
+ // is a context value: a fresh object per render would re-render every message body.
+ const reader = useMemo(() => ({ names, me, employeeIds }), [names, me, employeeIds]);
+ const memberPrincipals = useMemo(
+ () => (detail === null ? null : new Set(detail.members.map((m) => m.principal))),
+ [detail],
+ );
+ const candidates = useMemo(
+ () =>
+ channelMentionCandidates(
+ mentionCandidates(employees, members, S.company.channels.mentionAll),
+ memberPrincipals,
+ ),
+ [employees, members, memberPrincipals],
+ );
+ const stream = useMemo(
+ () => (days === null ? [] : buildStream(days, { unreadAfterId: meta?.unreadAfterId ?? null })),
+ [days, meta],
+ );
+ const earlier =
+ days !== null && meta !== null ? earlierDay(meta.days, days[0]?.date ?? meta.today) : null;
+
+ // A ticket named in a message opens as the dialog over the channel: the reader stays in
+ // the conversation they were reading. A session has no in-place form and still navigates.
+ const openTicket = (ticketId: string) => company.openTicket(projectId, orgId, ticketId);
+ const scrollToMessage = (id: string) =>
+ document.getElementById(id)?.scrollIntoView({ block: "center" });
+
+ const renderText = (m: OrgChannelMessage) =>
+ mentionRuns(m.text).map((run, i) =>
+ run.mention === null ? (
+ <span key={i}>{run.text}</span>
+ ) : (
+ <MentionChip
+ key={i}
+ raw={run.text}
+ label={mentionLabel(run.mention, names, S.company.principalAll)}
+ me={mentionIsMe(run.mention, me, employeeIds)}
+ />
+ ),
+ );
+
+ const renderRefs = (m: OrgChannelMessage) => {
+ // Destructured, so each id narrows to `string` inside the chips' closures too.
+ const { ticket, session, replyTo } = m.refs ?? {};
+ if (ticket === undefined && session === undefined && replyTo === undefined) return null;
+ return (
+ <span className={`mt-1 flex flex-wrap items-center ${ICON_GAP.row}`}>
+ {ticket !== undefined && (
+ <RefChip
+ onClick={() => openTicket(ticket)}
+ icon={NAV_ICONS.orgTickets}
+ title={S.company.channels.openTicketRef}
+ >
+ {S.company.channels.ticketRef(ticket)}
+ </RefChip>
+ )}
+ {session !== undefined && (
+ <RefChip
+ onClick={() => navigate(`/chat/${session}`)}
+ title={S.company.channels.sessionRef}
+ >
+ {S.company.channels.sessionRef}
+ </RefChip>
+ )}
+ {replyTo !== undefined && (
+ <RefChip onClick={() => scrollToMessage(replyTo)} title={S.company.channels.replyToJump}>
+ {S.company.channels.replyTo}
+ </RefChip>
+ )}
+ </span>
+ );
+ };
+
+ const renderItem = (item: StreamItem, i: number) => {
+ if (item.kind === "day") {
+ const kind = meta === null ? "other" : dayKind(item.date, meta.today);
+ const dayLabel =
+ kind === "today"
+ ? S.company.channels.today
+ : kind === "yesterday"
+ ? S.company.channels.yesterday
+ : null;
+ return (
+ <div key={`day-${item.date}`} className={`flex items-center ${ICON_GAP.menu} py-3`}>
+ <span className="h-px flex-1 bg-gray-200 dark:bg-gray-800" />
+ <span className="text-[11px] font-medium text-gray-500 dark:text-gray-400">
+ {dayLabel !== null ? `${dayLabel} · ${item.date}` : item.date}
+ </span>
+ <span className="h-px flex-1 bg-gray-200 dark:bg-gray-800" />
+ </div>
+ );
+ }
+ if (item.kind === "unread") {
+ return (
+ <div
+ key={`unread-${i}`}
+ className={`flex items-center ${ICON_GAP.menu} py-2`}
+ role="separator"
+ aria-label={S.company.channels.unreadDivider}
+ >
+ <span className={`h-px flex-1 ${toneDot.attention}`} />
+ <span className={`text-[11px] font-medium ${toneInk.attention}`}>
+ {S.company.channels.unreadDivider}
+ </span>
+ <span className={`h-px flex-1 ${toneDot.attention}`} />
+ </div>
+ );
+ }
+ if (item.kind === "system") {
+ const m = item.message;
+ // The structured notice in the reader's language; a line from before that field, or of a
+ // kind this build does not know, keeps the server's English sentence with its mentions.
+ const notice =
+ m.notice === undefined ? null : noticeText(m.notice, names, S.company.channels.notices);
+ return (
+ <div key={m.id} id={m.id} className="my-2 flex justify-center">
+ <p
+ title={formatDateTime(m.time)}
+ className="max-w-[85%] rounded-md border border-gray-200 bg-gray-50 px-3 py-1.5 text-center text-xs leading-relaxed text-gray-500 dark:border-gray-800 dark:bg-gray-900 dark:text-gray-400"
+ >
+ <span className="sr-only">{S.company.channels.systemMessage} </span>
+ {notice === null ? renderText(m) : notice}
+ {/* A notice addressed to people keeps their chips: the sentence names the event,
+ the chips say who has to act on it. */}
+ {notice !== null &&
+ m.mentions.map((principal) => (
+ <span key={principal} className="ml-1">
+ <MentionChip
+ raw={`@${principal}`}
+ label={mentionLabel(principal, names, S.company.principalAll)}
+ me={mentionIsMe(principal, me, employeeIds)}
+ />
+ </span>
+ ))}
+ <span className="ml-2 text-gray-400 dark:text-gray-500">{clockTime(m.time)}</span>
+ {renderRefs(m)}
+ </p>
+ </div>
+ );
+ }
+ const first = item.messages[0]!;
+ const p = parsePrincipal(item.sender);
+ const senderLabel = principalLabel(item.sender, names);
+ const own = isOwnRun(item.sender, me);
+ return (
+ <div key={first.id} className={`flex items-start ${ICON_GAP.card} py-1.5`}>
+ {/* One avatar per run, top-aligned so it lands beside the name row: a run is one person
+ speaking, and an avatar per line turns a burst of three into three arrivals. The
+ face and the name are one identity and have to be read as one — aligning the avatar
+ to the run's last bubble instead puts a ten-line message between them. */}
+ {!own &&
+ (p.kind === "agent" ? (
+ <AgentAvatar
+ id={p.id}
+ name={senderLabel}
+ size={RUN_AVATAR_PX}
+ className="shrink-0 rounded-md"
+ />
+ ) : (
+ <span
+ aria-hidden
+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-gray-900 text-xs font-bold text-white dark:bg-gray-200 dark:text-gray-900"
+ >
+ {senderLabel.slice(0, 1).toUpperCase()}
+ </span>
+ ))}
+ <div
+ className={`flex min-w-0 flex-1 flex-col gap-0.5 ${own ? "items-end" : "items-start"}`}
+ >
+ {own ? (
+ // The side and the tint are the whole of "this one is mine" on screen, and neither
+ // survives a screen reader: it gets the word instead.
+ <span className="sr-only">{S.company.channels.you}</span>
+ ) : (
+ <div
+ className={`flex max-w-full flex-wrap items-baseline ${ICON_GAP.row} px-1 text-[11px]`}
+ >
+ <span className="truncate font-semibold text-gray-700 dark:text-gray-300">
+ {senderLabel}
+ </span>
+ {/* The relay chip names what it is and carries the @-chain rule in its tooltip:
+ "hop 3" alone tells a reader nothing about why a message arrived. */}
+ {hopChipShown(item.hop) && (
+ <span
+ title={S.company.channels.hopInfo}
+ className="text-gray-500 dark:text-gray-400"
+ >
+ {S.company.channels.hop(item.hop)}
+ </span>
+ )}
+ </div>
+ )}
+ {item.messages.map((m, i) => {
+ const shape = bubbleShape(item, i, me);
+ const at = formatDateTime(m.time);
+ return (
+ <div
+ key={m.id}
+ id={m.id}
+ /* A message that names the reader is marked by its mention chip alone: a
+ tinted bubble reads as a state of the whole message, and in a channel where
+ most messages name someone it turns the stream into a highlight. */
+ className={`channel-bubble max-w-[75%] px-3 py-1.5 text-sm leading-relaxed ${bubbleCorners(shape)} ${own ? BUBBLE_SURFACE.own : BUBBLE_SURFACE.other}`}
+ >
+ {/* The time is a column of its own at the bubble's end, bottom-aligned: on a
+ one-line message it lands beside the words, on a longer one it settles
+ into the bottom-right corner, and it never overlaps the body. */}
+ <div className={`flex items-end ${ICON_GAP.menu}`}>
+ <div className="min-w-0 flex-1">
+ <div className="md-body md-compact">
+ <ChannelMessageBody text={m.text} />
+ </div>
+ {renderRefs(m)}
+ </div>
+ <span
+ title={at}
+ className="shrink-0 text-[11px] tabular-nums text-gray-600 dark:text-gray-400"
+ >
+ <span className="sr-only">{S.company.channels.sentAt(at)}</span>
+ <span aria-hidden>{clockTime(m.time)}</span>
+ </span>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+ };
+
+ const canPost = detail !== null && detail.isMember && !detail.archived;
+
+ return (
+ <ChannelReaderProvider reader={reader}>
+ <div className="flex h-full min-h-0 flex-col bg-white dark:bg-gray-950">
+ <ChannelHeader
+ projectId={projectId}
+ orgId={orgId}
+ me={myPrincipal}
+ detail={detail}
+ employees={employees}
+ projectMembers={members}
+ onChanged={() => {
+ void loadDetail();
+ void company.reloadChannels();
+ }}
+ />
+ {detailError !== null && detail === null && (
+ <p role="alert" className={`border-b px-4 py-1.5 text-xs ${toneStrip.danger}`}>
+ {S.company.channels.channelLoadFailed} · {detailError}
+ </p>
+ )}
+ <div className="flex min-h-0 flex-1 flex-col px-3 pb-3 md:px-4 md:pb-4">
+ <div className="relative mx-auto flex min-h-0 w-full max-w-5xl flex-1 flex-col">
+ <div
+ ref={listRef}
+ role="log"
+ aria-label={S.company.channels.streamLabel(label)}
+ onScroll={onScroll}
+ onWheel={(e) => follow.wheel(e.deltaY)}
+ onTouchStart={(e) => follow.touchStart(e.touches[0]?.clientY ?? 0)}
+ onTouchMove={(e) => follow.touchMove(e.touches[0]?.clientY ?? 0)}
+ onTouchEnd={() => follow.touchEnd()}
+ className="min-h-0 flex-1 overflow-y-auto pr-1"
+ >
+ <div>
+ {days === null && error !== null ? (
+ <EmptyState
+ title={error}
+ action={<Button onClick={() => void load()}>{S.common.retry}</Button>}
+ />
+ ) : days === null ? (
+ <StreamSkeleton />
+ ) : (
+ <>
+ {earlier !== null ? (
+ <div className="flex justify-center py-2">
+ <Button
+ size="sm"
+ disabled={loadingEarlier}
+ onClick={() => void loadEarlier()}
+ >
+ {loadingEarlier ? S.common.loading : S.company.channels.earlierDays}
+ </Button>
+ </div>
+ ) : (
+ messageCount(days) > 0 && (
+ <p className="py-2 text-center text-[11px] text-gray-400 dark:text-gray-500">
+ {S.company.channels.noEarlier}
+ </p>
+ )
+ )}
+ {messageCount(days) === 0 ? (
+ <EmptyState
+ title={S.company.channels.empty}
+ description={S.company.channels.emptyHint}
+ />
+ ) : (
+ stream.map(renderItem)
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ {showJump && (
+ <button
+ type="button"
+ aria-label={S.chat.jumpToLatest}
+ title={S.chat.jumpToLatest}
+ onClick={jumpToLatest}
+ className={`anim-pop absolute bottom-3 left-1/2 z-10 inline-flex -translate-x-1/2 items-center ${ICON_GAP.tight} rounded-full border border-gray-300 bg-white py-1 pl-2.5 pr-2 text-xs text-gray-600 shadow-sm transition-colors duration-150 hover:bg-gray-50 hover:text-gray-900 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100`}
+ >
+ {pendingNew > 0 ? S.company.channels.newMessages(pendingNew) : S.chat.jumpToLatest}
+ <GlyphIcon d={ARROW_DOWN_ICON} size={ICON_SIZE.inlineGlyph} />
+ </button>
+ )}
+ </div>
+ <div className="mx-auto w-full max-w-5xl">
+ {canPost ? (
+ <ChannelComposer candidates={candidates} names={names} onSend={send} />
+ ) : detail !== null && detail.archived ? (
+ <p
+ className={`mt-3 rounded-md border px-3 py-2 text-xs ${toneStrip.muted}`}
+ role="status"
+ >
+ {S.company.channels.archivedNotice}
+ </p>
+ ) : detail !== null ? (
+ <div
+ className={`mt-3 flex flex-wrap items-center justify-between gap-x-3 gap-y-2 rounded-md border px-3 py-2 text-xs ${toneStrip.attention}`}
+ >
+ <span>{S.company.channels.notMemberNotice}</span>
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={joining}
+ onClick={() => setConfirmJoin(true)}
+ >
+ {joining ? S.company.channels.joining : S.company.channels.join}
+ </Button>
+ </div>
+ ) : null}
+ </div>
+ </div>
+ <JoinChannelConfirm
+ open={confirmJoin}
+ busy={joining}
+ onClose={() => setConfirmJoin(false)}
+ onConfirm={() => void join()}
+ />
+ </div>
+ </ChannelReaderProvider>
+ );
+}
+
+/**
+ * A small bordered chip that opens what a message refers to. The message bubble itself is inert
+ * — these chips are the only way out of it — so each says in its tooltip where it lands, which
+ * the chip's own text alone ("工单 T-3", "回复") does not.
+ */
+function RefChip({
+ onClick,
+ icon,
+ title,
+ children,
+}: {
+ onClick: () => void;
+ icon?: string;
+ /** Where the chip goes, as its tooltip reads it. */
+ title: string;
+ children: string;
+}) {
+ return (
+ <button
+ type="button"
+ title={title}
+ onClick={onClick}
+ className={`inline-flex items-center ${ICON_GAP.tight} rounded-full border border-gray-200 bg-white px-2 py-0.5 text-[11px] text-gray-600 transition-colors duration-150 hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100`}
+ >
+ {icon !== undefined && <GlyphIcon d={icon} size={ICON_SIZE.inlineGlyph} />}
+ {children}
+ </button>
+ );
+}
+
+/** Three bubble-shaped bands while the first day loads, on the side each will land on. */
+function StreamSkeleton() {
+ return (
+ <div className="space-y-4 py-2">
+ {[0, 1, 2].map((i) => {
+ const own = i === 1;
+ return (
+ <div key={i} className={`flex items-start ${ICON_GAP.card}`}>
+ {!own && <Skeleton className="h-7 w-7 shrink-0 rounded-md" />}
+ <div className={`flex flex-1 flex-col gap-1 ${own ? "items-end" : "items-start"}`}>
+ {!own && <Skeleton className="h-3 w-24" />}
+ <Skeleton className={`h-8 rounded-2xl ${own ? "w-1/2" : "w-3/5"}`} />
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/packages/web/src/features/company/chart-card.tsx b/packages/web/src/features/company/chart-card.tsx
new file mode 100644
index 00000000..1babd653
--- /dev/null
+++ b/packages/web/src/features/company/chart-card.tsx
@@ -0,0 +1,265 @@
+/**
+ * One employee card on the org chart, plus the state-dot legend shown beside the chart.
+ *
+ * The face carries no primary action: it is a plain card that reads, and the personnel menu —
+ * opening the desk session and every personnel action — is the one thing it can do. A
+ * whole-card link would promise one of those many actions and steal the click from the rest.
+ * Three rows: avatar with the name and title (the CEO wears a chip); the live state dot and
+ * its label, the workspace tail, this period's spend against the budget; a thin ratio bar.
+ * The state the dot draws is passed in rather than read off the employee: the chart is a
+ * snapshot re-read on organization events, and no event says a run ended (org-sessions.ts,
+ * liveEmployeeStates).
+ * Every status colour is a tone picked by meaning; running and on-desk share emerald and
+ * are told apart by motion (the running dot pulses) and by their labels.
+ *
+ * Three ways into that one menu, all of them the same panel: the kebab in the top-right
+ * corner (the only focusable thing on the card, and the pointer's discoverable route), a
+ * secondary click anywhere on the card, and Shift+F10 from the focused kebab. The sidebar's
+ * `useRowContextMenu` drives them, so the panel hangs off the point the gesture landed on and
+ * inherits the Dropdown's dismiss stack, focus handling and viewport clamping. The card owns
+ * that state: which card's menu is open is decided by the panel itself, since opening one is
+ * an outside press on any other.
+ *
+ * The card sits on a pan/zoom canvas (org-chart-page.tsx), which is why the kebab names its
+ * own cursor: the canvas wears `grab` over the whole surface, the card included — pressing
+ * the inert face drags the canvas — and the one control on it has to say it is not that. A
+ * secondary click never starts that pan: usePointerDrag refuses any button but the primary.
+ *
+ * That pan is also why press-and-hold is NOT one of the three, though the hook offers it: the
+ * canvas takes pointer capture on press, so every later pointer event for that gesture is
+ * retargeted to the canvas and the card never sees the move or the lift that would cancel a
+ * hold. The timer would then fire on a finger that has been dragging for half a second. Touch
+ * reaches the menu through the kebab, which is drawn on every card rather than revealed on
+ * hover for exactly this reason.
+ */
+import { useEffect } from "react";
+import type { ReactNode } from "react";
+import type { OrgEmployeeItem, OrgEmployeeState } from "@prismshadow/penguin-server/api";
+import { S } from "../../lib/strings";
+import { useRowContextMenu } from "../../components/ui/context-menu";
+import { formatMoney, formatPercent } from "../../lib/format";
+import { ICON_SIZE } from "../../lib/icon-scale";
+import { toneDot, toneInk } from "../../lib/tone";
+import type { Currency } from "../../state/theme";
+import { AgentAvatar } from "../../components/ui/agent-avatar";
+import { Badge } from "../../components/ui/badge";
+import { Dropdown } from "../../components/ui/dropdown";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { ELLIPSIS_ICON } from "../../components/ui/session-row-menu";
+import { FOLDER_ICON } from "../../components/ui/group-list";
+import { budgetTone } from "./finance-tree";
+import { INVALID_ICON } from "./shared";
+import { CHART_NODE_H, CHART_NODE_W, workspaceTail } from "./org-chart-tree";
+import { employeeStateTone } from "./chart-view";
+
+/** The legend's order: the states a reader is most likely to be looking for first. */
+const LEGEND_STATES: readonly OrgEmployeeState[] = ["running", "idle", "paused"];
+
+/** A 6px state dot with its label beside it; the running dot carries a pulsing halo (transform-only, so reduced motion leaves a plain dot). */
+export function ChartStateDot({ state }: { state: OrgEmployeeState }) {
+ const tone = employeeStateTone(state);
+ const label = S.company.employeeStates[state] ?? state;
+ return (
+ <span className="inline-flex shrink-0 items-center gap-1.5">
+ <span className="relative flex h-1.5 w-1.5 shrink-0" aria-hidden>
+ {state === "running" && (
+ <span
+ className={`absolute inline-flex h-full w-full animate-ping rounded-full opacity-75 ${toneDot[tone]}`}
+ />
+ )}
+ <span className={`relative inline-flex h-1.5 w-1.5 rounded-full ${toneDot[tone]}`} />
+ </span>
+ <span>{label}</span>
+ </span>
+ );
+}
+
+export function ChartLegend() {
+ return (
+ <ul
+ aria-label={S.company.chart.legend}
+ className="flex flex-wrap items-center gap-x-4 gap-y-1 text-[11px] text-gray-500 dark:text-gray-400"
+ >
+ {LEGEND_STATES.map((state) => (
+ <li key={state} className="flex items-center">
+ <ChartStateDot state={state} />
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+export function ChartCard({
+ employee,
+ state,
+ isCeo,
+ currency,
+ x,
+ y,
+ detached = false,
+ viewEpoch,
+ menu,
+}: {
+ employee: OrgEmployeeItem;
+ /** The state the dot draws — the live one, which the chart's own `state` cannot be. */
+ state: OrgEmployeeState;
+ isCeo: boolean;
+ currency: Currency;
+ /** Top-left corner inside the drawing. */
+ x: number;
+ y: number;
+ /** In the detached row: its reporting line does not reach the CEO. */
+ detached?: boolean;
+ /**
+ * Moves whenever the canvas pans or zooms under the cards, which closes an open menu: the
+ * panel hangs off a viewport point, and a transform carries the card out from under it
+ * without being either of the two things the panel can detect on its own (a scroll of a
+ * container it sits in, or a resize of the window).
+ */
+ viewEpoch: number;
+ /**
+ * The personnel menu's rows, built against the panel's own close: a row runs after the
+ * panel has gone, and the menu is the only keyboard route to these actions.
+ */
+ menu: (close: () => void) => ReactNode;
+}) {
+ const ctx = useRowContextMenu();
+ const { close } = ctx;
+ useEffect(() => {
+ close();
+ }, [viewEpoch, close]);
+ const tone = budgetTone(employee.spend.ratio);
+ const spent = formatMoney(employee.spend.cumulative, currency);
+ const spend =
+ employee.budget === undefined
+ ? spent
+ : S.company.spendOfBudget(spent, formatMoney(employee.budget, currency));
+ const spendTitle = `${S.company.chart.spend}: ${spend} · ${
+ employee.spend.ratio === undefined ? S.company.noBudget : formatPercent(employee.spend.ratio)
+ }`;
+ const fill =
+ employee.spend.ratio === undefined ? 0 : Math.min(100, Math.max(0, employee.spend.ratio * 100));
+ const flagged = employee.invalid !== undefined || detached;
+ const flag = employee.invalid ?? (detached ? S.company.chart.detached : undefined);
+ return (
+ <div
+ ref={ctx.rowRef}
+ // Secondary click and Shift+F10 open the card's menu (not the hook's press-and-hold —
+ // see the header). The native menu is suppressed inside that handler only, so the rest
+ // of the app keeps the browser's own.
+ onContextMenu={ctx.rowProps.onContextMenu}
+ onKeyDown={ctx.rowProps.onKeyDown}
+ className="group absolute"
+ style={{ left: x, top: y, width: CHART_NODE_W, height: CHART_NODE_H }}
+ >
+ {/* The tooltip carries what the two truncating lines may have cut, and nothing else:
+ the face has no click of its own, so it must not promise one either. */}
+ <div
+ title={
+ flag !== undefined ? `${employee.name} · ${flag}` : `${employee.name} · ${employee.title}`
+ }
+ className={`absolute inset-0 flex flex-col rounded-lg border bg-white px-3 py-2.5 shadow-sm dark:bg-gray-900 ${
+ flagged ? "border-red-300 dark:border-red-800" : "border-gray-200 dark:border-gray-700"
+ }`}
+ >
+ <span className="flex items-center gap-2.5 pr-6">
+ <AgentAvatar
+ id={employee.agentId}
+ name={employee.name}
+ size={28}
+ className="shrink-0 rounded-md"
+ />
+ <span className="min-w-0 flex-1">
+ <span className="flex items-center gap-1.5">
+ <span className="min-w-0 truncate text-[13px] leading-4 font-semibold text-gray-900 dark:text-gray-100">
+ {employee.name}
+ </span>
+ {isCeo && <Badge tone="brand">{S.company.ceo}</Badge>}
+ </span>
+ <span className="block truncate text-[11px] leading-4 text-gray-500 dark:text-gray-400">
+ {employee.title}
+ </span>
+ </span>
+ </span>
+ <span className="mt-2 flex items-center gap-1.5 text-[11px] leading-4 text-gray-600 dark:text-gray-300">
+ <ChartStateDot state={state} />
+ <span
+ className="flex min-w-0 flex-1 items-center gap-1 font-mono text-[10px] text-gray-400 dark:text-gray-500"
+ title={flag ?? employee.resolvedWorkspace ?? employee.workspace}
+ >
+ {flag !== undefined ? (
+ <span className={toneInk.danger}>
+ <GlyphIcon d={INVALID_ICON} size={10} />
+ </span>
+ ) : (
+ <GlyphIcon d={FOLDER_ICON} size={10} />
+ )}
+ <span className="truncate">{workspaceTail(employee.workspace)}</span>
+ </span>
+ <span
+ className={`shrink-0 tabular-nums ${
+ tone === "attention" || tone === "danger" ? `font-medium ${toneInk[tone]}` : ""
+ }`}
+ title={spendTitle}
+ >
+ {spend}
+ </span>
+ </span>
+ {/* The ratio bar: emerald under 80%, amber from 80%, red from 100%; an empty track without a budget. */}
+ <span
+ className="mt-1.5 block h-[3px] w-full overflow-hidden rounded-full bg-gray-100 dark:bg-gray-800"
+ aria-hidden
+ >
+ <span
+ className={`block h-full rounded-full ${toneDot[tone]}`}
+ style={{ width: `${fill}%` }}
+ />
+ </span>
+ </div>
+ {/* The personnel menu. Its own wrapper positions it — Dropdown's root is `relative` and
+ would otherwise sit in flow. The kebab is the Dropdown's own trigger rather than a
+ sibling of it, because the panel dismisses on any mousedown landing outside that
+ root: a trigger beside it would close the menu on press and reopen it on the click
+ that follows, instead of toggling. Placement comes from the gesture's anchor, not
+ from the wrapper — a secondary click hangs the same panel off the pointer. */}
+ <div className="absolute top-1.5 right-1.5">
+ <Dropdown
+ open={ctx.open}
+ setOpen={ctx.setOpen}
+ portal={{ direction: "down", align: "left" }}
+ anchorRect={ctx.anchor}
+ anchorOwner={ctx.anchorOwner}
+ returnFocus={ctx.returnFocus}
+ menuClass="w-48"
+ button={
+ <button
+ type="button"
+ title={S.company.chart.nodeMenu}
+ aria-label={`${employee.name} · ${S.company.chart.nodeMenu}`}
+ aria-haspopup="menu"
+ aria-expanded={ctx.open}
+ onClick={(e) => {
+ if (ctx.open) {
+ ctx.close();
+ return;
+ }
+ const r = e.currentTarget.getBoundingClientRect();
+ ctx.openAt({ top: r.top, bottom: r.bottom, left: r.left, right: r.right });
+ }}
+ className={`flex h-6 w-6 cursor-pointer items-center justify-center rounded-md text-gray-400 transition-[opacity,background-color,color] duration-150 group-hover:opacity-100 hover:bg-gray-100 hover:text-gray-700 focus-visible:opacity-100 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200 ${
+ ctx.open ? "opacity-100" : "opacity-70"
+ }`}
+ >
+ <GlyphIcon d={ELLIPSIS_ICON} size={ICON_SIZE.groupHeaderAction} filled />
+ </button>
+ }
+ >
+ {menu(() => {
+ ctx.returnFocus()?.focus();
+ ctx.close();
+ })}
+ </Dropdown>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/features/company/chart-view.ts b/packages/web/src/features/company/chart-view.ts
new file mode 100644
index 00000000..90569ab2
--- /dev/null
+++ b/packages/web/src/features/company/chart-view.ts
@@ -0,0 +1,12 @@
+/**
+ * The org chart's one shared reading of an employee's live state (pure, unit tested): the
+ * tone its dot, its label and its finance row take. The canvas's pan and zoom arithmetic
+ * lives in canvas-view.ts, the tree and its geometry in org-chart-tree.ts.
+ */
+import type { OrgEmployeeState } from "@prismshadow/penguin-server/api";
+import type { Tone } from "../../lib/tone";
+
+/** Busy while running, attention when its budget paused it, success on the desk — by meaning, as every status mark. */
+export function employeeStateTone(state: OrgEmployeeState): Tone {
+ return state === "running" ? "busy" : state === "paused" ? "attention" : "success";
+}
diff --git a/packages/web/src/features/company/company-nav-icons.ts b/packages/web/src/features/company/company-nav-icons.ts
new file mode 100644
index 00000000..6b24706f
--- /dev/null
+++ b/packages/web/src/features/company/company-nav-icons.ts
@@ -0,0 +1,16 @@
+/**
+ * The glyph of each company-mode nav entry, read off NAV_ICONS by manifest key so the pinned
+ * sidebar and the collapsed rail draw the same mark for the same page (kept apart from
+ * company-nav.ts, which stays free of any icon import so the route grammar is testable alone).
+ */
+import { NAV_ICONS } from "../../components/ui/icons";
+import type { CompanyNavKey } from "./company-nav";
+
+export const COMPANY_NAV_ICONS: Record<CompanyNavKey, string> = {
+ overview: NAV_ICONS.orgOverview,
+ chart: NAV_ICONS.orgChart,
+ calendar: NAV_ICONS.orgCalendar,
+ tickets: NAV_ICONS.orgTickets,
+ finance: NAV_ICONS.orgFinance,
+ handbook: NAV_ICONS.orgHandbook,
+};
diff --git a/packages/web/src/features/company/company-nav.ts b/packages/web/src/features/company/company-nav.ts
new file mode 100644
index 00000000..089ba9bb
--- /dev/null
+++ b/packages/web/src/features/company/company-nav.ts
@@ -0,0 +1,147 @@
+/**
+ * Company mode's navigation manifest and route grammar (pure, unit tested): the six page
+ * entries in rendered order, the `/org/:projectId/:orgId/<page>` paths they lead to, the
+ * `/channels/:channelId` path of a channel, the `<projectId>/<orgId>` key the shell remembers
+ * an organization by, where a freshly created one opens and which key the shell becomes
+ * current at when it does, and which organization `/org` resolves to when it is opened without
+ * naming one (the page it then opens is the overview, the first entry below). The sidebar,
+ * the collapsed rail and the router all derive their rows from this file, so the covered
+ * range is pinned here (and in the unit tests) rather than duplicated.
+ */
+
+/** The two work modes of the shell: development (the default) or company. */
+export type WorkMode = "dev" | "company";
+
+/**
+ * Company-mode page entries, in rendered order: each key names its route segment, its S.nav
+ * label (`S.nav.org.<key>`) and its NAV_ICONS glyph (`NAV_ICONS.org<Key>`). Channels are not
+ * among them — they are the sidebar's own list, the way conversations are in development
+ * mode, and they live under `/channels/:channelId` rather than behind a nav row.
+ */
+export const COMPANY_NAV_KEYS = [
+ "overview",
+ "chart",
+ "calendar",
+ "tickets",
+ "finance",
+ "handbook",
+] as const;
+export type CompanyNavKey = (typeof COMPANY_NAV_KEYS)[number];
+
+/** The route prefix every company-mode page lives under. */
+export const ORG_ROUTE_PREFIX = "/org";
+
+/** An organization's identity across Projects: `<projectId>/<orgId>` (both ids are semantic ids, so `/` never appears inside either). */
+export function orgKey(projectId: string, orgId: string): string {
+ return `${projectId}/${orgId}`;
+}
+
+/** The pair an org key names, or null for anything that is not one (a stale preference, an empty string). */
+export function parseOrgKey(
+ key: string | null | undefined,
+): { projectId: string; orgId: string } | null {
+ if (!key) return null;
+ const at = key.indexOf("/");
+ if (at <= 0 || at === key.length - 1) return null;
+ const projectId = key.slice(0, at);
+ const orgId = key.slice(at + 1);
+ if (orgId.includes("/")) return null;
+ return { projectId, orgId };
+}
+
+/** The `/org/<projectId>/<orgId>` prefix every surface of one organization hangs off. */
+function orgRoot(projectId: string, orgId: string): string {
+ return `${ORG_ROUTE_PREFIX}/${encodeURIComponent(projectId)}/${encodeURIComponent(orgId)}`;
+}
+
+/** Path of one company-mode page of one organization. */
+export function orgPagePath(projectId: string, orgId: string, page: CompanyNavKey): string {
+ return `${orgRoot(projectId, orgId)}/${page}`;
+}
+
+/**
+ * Path of one channel of one organization. A channel is reached from the sidebar's list, not
+ * from a landing: the organization switcher and a bare `/org/<projectId>/<orgId>` open the
+ * overview instead, which is the page that says what the whole organization is doing.
+ */
+export function orgChannelPath(projectId: string, orgId: string, channelId: string): string {
+ return `${orgRoot(projectId, orgId)}/channels/${encodeURIComponent(channelId)}`;
+}
+
+/**
+ * Where a newly created organization opens: the CEO's desk session, so the conversation
+ * about the mission starts in the same click that made the organization, and its overview
+ * when no desk session came back with it.
+ */
+export function orgCreatedPath(created: {
+ projectId: string;
+ orgId: string;
+ ceoDeskSessionId?: string;
+}): string {
+ return created.ceoDeskSessionId !== undefined
+ ? `/chat/${created.ceoDeskSessionId}`
+ : orgPagePath(created.projectId, created.orgId, "overview");
+}
+
+/**
+ * What the shell adopts when an organization has just been created: the
+ * `<projectId>/<orgId>` key it becomes current at, and the path it opens. The two travel
+ * together because a creation lands in the CEO's desk session, which lives at
+ * `/chat/:sessionId` — not one of the organization's own routes, and those routes are the
+ * only thing that otherwise announces which organization the shell is inside. Without the
+ * key the sidebar would keep listing the previous organization's channels around the
+ * conversation the new one just opened.
+ */
+export function orgCreatedTarget(created: {
+ projectId: string;
+ orgId: string;
+ ceoDeskSessionId?: string;
+}): { key: string; path: string } {
+ return { key: orgKey(created.projectId, created.orgId), path: orgCreatedPath(created) };
+}
+
+/** Whether a location is inside company mode's own routes (a Session's own page is shared by both modes and is not). */
+export function isOrgRoute(pathname: string): boolean {
+ return pathname === ORG_ROUTE_PREFIX || pathname.startsWith(`${ORG_ROUTE_PREFIX}/`);
+}
+
+/**
+ * Where `/org` lands when it names no organization: the one last opened if it still exists,
+ * else the first organization of the current Project, else the first organization anywhere —
+ * and null when the user has none, which is the empty landing's cue to offer creating one.
+ */
+export function resolveOrgLanding<T extends { projectId: string; orgId: string }>(
+ lastOrgKey: string | null | undefined,
+ organizations: readonly T[],
+ currentProjectId: string | null,
+): T | null {
+ const last = parseOrgKey(lastOrgKey);
+ if (last) {
+ const found = organizations.find(
+ (o) => o.projectId === last.projectId && o.orgId === last.orgId,
+ );
+ if (found) return found;
+ }
+ if (currentProjectId !== null) {
+ const inProject = organizations.find((o) => o.projectId === currentProjectId);
+ if (inProject) return inProject;
+ }
+ return organizations[0] ?? null;
+}
+
+/**
+ * Organizations grouped by Project for the switcher, in the order the Projects are listed
+ * (the Project list is the user's own order; an organization whose Project is not in the list
+ * — a stale cache after losing access — is dropped rather than shown under no heading).
+ */
+export function groupOrganizationsByProject<T extends { projectId: string }>(
+ organizations: readonly T[],
+ projectIds: readonly string[],
+): Array<{ projectId: string; organizations: T[] }> {
+ return projectIds
+ .map((projectId) => ({
+ projectId,
+ organizations: organizations.filter((o) => o.projectId === projectId),
+ }))
+ .filter((g) => g.organizations.length > 0);
+}
diff --git a/packages/web/src/features/company/desk-renew.ts b/packages/web/src/features/company/desk-renew.ts
new file mode 100644
index 00000000..a4050e73
--- /dev/null
+++ b/packages/web/src/features/company/desk-renew.ts
@@ -0,0 +1,24 @@
+/**
+ * What a desk-renewal confirm has to send, decided on its own so it can be unit tested
+ * without the dialog around it.
+ *
+ * The dialog merges two writes into one action: the workspace field is prefilled with the
+ * employee's current spec, and a renewal that leaves it alone must not rewrite the chart file
+ * — a PATCH would re-validate and re-create the directory for no change the reader asked for.
+ * The comparison is on the trimmed text, so re-typing the same spec with a stray space is
+ * still "unchanged". An empty field is refused here rather than sent as `.`, because clearing
+ * a workspace is a different intent from renewing a desk and the field is required.
+ */
+
+export interface DeskRenewPlan {
+ /** False when the field is empty: the dialog refuses and sends nothing at all. */
+ valid: boolean;
+ /** The workspace to PATCH before renewing, or null when the spec is unchanged. */
+ workspace: string | null;
+}
+
+export function deskRenewPlan(current: string, typed: string): DeskRenewPlan {
+ const next = typed.trim();
+ if (next === "") return { valid: false, workspace: null };
+ return { valid: true, workspace: next === current.trim() ? null : next };
+}
diff --git a/packages/web/src/features/company/employee-dialogs.tsx b/packages/web/src/features/company/employee-dialogs.tsx
new file mode 100644
index 00000000..e0fdf38b
--- /dev/null
+++ b/packages/web/src/features/company/employee-dialogs.tsx
@@ -0,0 +1,697 @@
+/**
+ * The org chart's personnel dialogs. Hire a subordinate — in two sections: the Agent (an
+ * existing one of the Project, or a new one: id, name, description, plugins defaulting to
+ * agent-company and agent-development) and the position (title, duties, workspace, budget)
+ * — the single-field edits, each showing the current value first: budget (a monthly cap,
+ * typed in the reader's own currency and stored in USD, or unbounded) and reporting line
+ * (anyone outside the employee's own subtree); and the desk renewal, which writes the
+ * workspace and opens a fresh desk session in one confirm. Every single-field edit stops at
+ * the shared ConfirmModal first (the confirmation names what the chart file will say), then
+ * calls the API; the renewal is its own confirmation and needs no second one.
+ */
+import { useEffect, useState } from "react";
+import type { OrgEmployeeItem, OrgHireRequest } from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { ApiError } from "../../api/client";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { SEMANTIC_ID_PATTERN } from "../../lib/semantic-id";
+import { formatMoney } from "../../lib/format";
+import { useCompany } from "../../state/company";
+import { agentDisplayName, useProject } from "../../state/project";
+import { useTheme } from "../../state/theme";
+import { Button } from "../../components/ui/button";
+import { Input, Textarea } from "../../components/ui/input";
+import { Select } from "../../components/ui/select";
+import { Segmented } from "../../components/ui/segmented";
+import { Modal } from "../../components/ui/modal";
+import { ConfirmModal } from "../../components/ui/confirm-modal";
+import { FormPicker } from "../../components/ui/form-picker";
+import { FieldError, FieldHint, FieldLabel } from "../../components/ui/field";
+import { toastError, toastSuccess } from "../../components/ui/toast";
+import { PLUGIN_ICON } from "../../components/ui/icons";
+import { SkillPickList } from "../skills/skill-pick-list";
+import type { PickableItem } from "../skills/skill-pick-list";
+import { addSkillNames, removeSkillNames, toggleSkillName } from "../skills/skill-selection";
+import { OrgSection } from "./org-layout";
+import { MoneyPerMonthInput } from "./shared";
+import { fromStoredUsd, isBudgetText, toStoredUsd } from "./budget-input";
+import { deskRenewPlan } from "./desk-renew";
+import { managerCandidates } from "./org-chart-tree";
+
+/** The plugins a new employee starts with: the organization procedures and the development skills. */
+const DEFAULT_EMPLOYEE_PLUGINS = ["agent-company", "agent-development"];
+
+/** The "what it is now" line at the top of an edit dialog. */
+function CurrentValue({ value }: { value: string }) {
+ return (
+ <p className="text-xs text-gray-500 dark:text-gray-400">
+ {S.company.chart.currentValue(value)}
+ </p>
+ );
+}
+
+export function HireDialog({
+ open,
+ projectId,
+ orgId,
+ manager,
+ employees,
+ onClose,
+ onHired,
+}: {
+ open: boolean;
+ projectId: string;
+ orgId: string;
+ /** The employee the new hire reports to. */
+ manager: OrgEmployeeItem;
+ employees: readonly OrgEmployeeItem[];
+ onClose: () => void;
+ onHired: () => void;
+}) {
+ const { agents } = useProject();
+ const { currency } = useTheme();
+ const company = useCompany();
+ const [source, setSource] = useState<"existing" | "new">("existing");
+ const [agentId, setAgentId] = useState("");
+ const [newId, setNewId] = useState("");
+ const [newName, setNewName] = useState("");
+ const [newDescription, setNewDescription] = useState("");
+ const [plugins, setPlugins] = useState<string[]>(DEFAULT_EMPLOYEE_PLUGINS);
+ const [pluginsOpen, setPluginsOpen] = useState(false);
+ const [library, setLibrary] = useState<PickableItem[] | null>(null);
+ const [title, setTitle] = useState("");
+ const [duties, setDuties] = useState("");
+ const [workspace, setWorkspace] = useState("");
+ const [budget, setBudget] = useState("");
+ const [errors, setErrors] = useState<{ agent?: string; title?: string; budget?: string }>({});
+ const [confirmOpen, setConfirmOpen] = useState(false);
+ const [busy, setBusy] = useState(false);
+
+ /** Agents of the Project not yet in the organization. */
+ const employed = new Set(employees.map((e) => e.agentId));
+ const candidates = agents.filter((a) => !employed.has(a.agentId));
+
+ useEffect(() => {
+ if (!open) return;
+ setSource(candidates.length > 0 ? "existing" : "new");
+ setAgentId(candidates[0]?.agentId ?? "");
+ setNewId("");
+ setNewName("");
+ setNewDescription("");
+ setPlugins(DEFAULT_EMPLOYEE_PLUGINS);
+ setTitle("");
+ setDuties("");
+ setWorkspace("");
+ setBudget("");
+ setErrors({});
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open]);
+
+ // The plugin library is fetched the first time the dialog opens, for the picker.
+ useEffect(() => {
+ if (!open || library !== null) return;
+ let cancelled = false;
+ void api
+ .getPluginLibrary()
+ .then((res) => {
+ if (cancelled) return;
+ setLibrary(
+ res.groups.flatMap((g) => g.plugins.map((p) => ({ ...p, fallbackIcon: PLUGIN_ICON }))),
+ );
+ })
+ .catch(() => {
+ if (!cancelled) setLibrary([]);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [open, library]);
+
+ const picked = agents.find((a) => a.agentId === agentId);
+ // Left empty, the server partitions the shared workspace by Agent id, so the placeholder
+ // shows the directory this hire will actually get rather than the root, which is nobody's desk.
+ const hireAgentId = (source === "existing" ? agentId : newId.trim()) || ".";
+ const hireName =
+ source === "existing"
+ ? picked !== undefined
+ ? agentDisplayName(picked)
+ : agentId
+ : newName.trim() || newId.trim();
+
+ const validate = (): boolean => {
+ const next: typeof errors = {};
+ if (source === "existing") {
+ if (!agentId) next.agent = S.common.requiredField;
+ } else if (!newId.trim()) {
+ next.agent = S.common.requiredField;
+ } else if (!SEMANTIC_ID_PATTERN.test(newId.trim())) {
+ next.agent = S.company.chart.agentIdHint;
+ }
+ if (!title.trim()) next.title = S.common.requiredField;
+ if (!isBudgetText(budget)) next.budget = S.company.chart.budgetHint;
+ setErrors(next);
+ return Object.keys(next).length === 0;
+ };
+
+ const hire = async () => {
+ setBusy(true);
+ try {
+ // The box speaks the reader's currency; the chart file holds USD.
+ const budgetUsd = toStoredUsd(budget, currency);
+ const body: OrgHireRequest = {
+ title: title.trim(),
+ reportsTo: manager.agentId,
+ ...(source === "existing"
+ ? { agentId }
+ : {
+ newAgent: {
+ agentId: newId.trim(),
+ ...(newName.trim() ? { name: newName.trim() } : {}),
+ ...(newDescription.trim() ? { description: newDescription.trim() } : {}),
+ plugins,
+ },
+ }),
+ ...(workspace.trim() ? { workspace: workspace.trim() } : {}),
+ ...(budgetUsd !== null ? { budget: budgetUsd } : {}),
+ ...(duties.trim() ? { duties: duties.trim() } : {}),
+ };
+ await api.hireOrgEmployee(projectId, orgId, body);
+ // The hire opened the newcomer's desk session: re-read the organization's sessions so
+ // the sidebar's 工位 row carries its real id straight away, rather than a row that
+ // cannot be opened or bound until some later event happens to refresh the cache.
+ void company.reloadOrgSessions();
+ toastSuccess(S.company.chart.hired(hireName));
+ setConfirmOpen(false);
+ onHired();
+ } catch (e) {
+ setConfirmOpen(false);
+ toastError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <>
+ <Modal
+ open={open}
+ title={S.company.chart.hireTitle(manager.name)}
+ onClose={onClose}
+ widthClass="sm:max-w-lg"
+ footer={
+ <>
+ <Button size="sm" onClick={onClose} disabled={busy}>
+ {S.common.cancel}
+ </Button>
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={busy}
+ onClick={() => {
+ if (validate()) setConfirmOpen(true);
+ }}
+ >
+ {S.company.chart.hire}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-5">
+ <OrgSection title={S.company.chart.hireAgentSection}>
+ <div className="space-y-3">
+ <div>
+ <FieldLabel>{S.company.chart.hireSource}</FieldLabel>
+ <Segmented
+ options={[
+ { value: "existing" as const, label: S.company.chart.hireExisting },
+ { value: "new" as const, label: S.company.chart.hireNew },
+ ]}
+ value={source}
+ onChange={setSource}
+ cols={2}
+ />
+ </div>
+ {source === "existing" ? (
+ <Select
+ size="sm"
+ label={S.company.chart.agent}
+ required
+ value={agentId}
+ hint={S.company.chart.agentHint}
+ {...(errors.agent !== undefined ? { error: errors.agent } : {})}
+ onChange={(e) => {
+ setAgentId(e.target.value);
+ setErrors((p) => ({ ...p, agent: undefined }));
+ }}
+ >
+ {candidates.length === 0 ? (
+ <option value="">{S.company.chart.noAgentsLeft}</option>
+ ) : (
+ candidates.map((a) => (
+ <option key={a.agentId} value={a.agentId}>
+ {agentDisplayName(a)} ({a.agentId})
+ </option>
+ ))
+ )}
+ </Select>
+ ) : (
+ <>
+ <Input
+ label={S.company.chart.agentId}
+ required
+ size="sm"
+ value={newId}
+ className="font-mono"
+ hint={S.company.chart.agentIdHint}
+ {...(errors.agent !== undefined ? { error: errors.agent } : {})}
+ onChange={(e) => {
+ setNewId(e.target.value);
+ setErrors((p) => ({ ...p, agent: undefined }));
+ }}
+ />
+ <Input
+ label={S.company.chart.agentName}
+ size="sm"
+ value={newName}
+ hint={S.company.chart.agentNameHint}
+ onChange={(e) => setNewName(e.target.value)}
+ />
+ <Textarea
+ label={S.company.chart.agentDescription}
+ size="sm"
+ rows={2}
+ value={newDescription}
+ onChange={(e) => setNewDescription(e.target.value)}
+ />
+ <div>
+ <FieldLabel>{S.company.chart.plugins}</FieldLabel>
+ <FormPicker
+ open={pluginsOpen}
+ setOpen={setPluginsOpen}
+ label={
+ plugins.length === 0
+ ? S.company.chart.pluginsPlaceholder
+ : S.company.chart.pluginsPicked(plugins.length)
+ }
+ muted={plugins.length === 0}
+ title={S.company.chart.plugins}
+ ariaLabel={S.company.chart.plugins}
+ disabled={busy}
+ menuClass="w-[26rem]"
+ >
+ <SkillPickList
+ skills={library ?? []}
+ selected={plugins}
+ onToggle={(name) => setPlugins((prev) => toggleSkillName(prev, name))}
+ onSelectAll={(names) => setPlugins((prev) => addSkillNames(prev, names))}
+ onSelectNone={(names) =>
+ setPlugins((prev) => removeSkillNames(prev, names))
+ }
+ emptyHint={
+ library === null ? S.common.loading : S.company.chart.pluginsEmpty
+ }
+ searchPlaceholder={S.plugins.searchPlaceholder}
+ />
+ </FormPicker>
+ <FieldHint>{S.company.chart.pluginsHint}</FieldHint>
+ </div>
+ </>
+ )}
+ </div>
+ </OrgSection>
+ <OrgSection title={S.company.chart.hirePositionSection}>
+ <div className="space-y-3">
+ <Input
+ label={S.company.chart.employeeTitle}
+ required
+ size="sm"
+ value={title}
+ placeholder={S.company.chart.employeeTitlePlaceholder}
+ {...(errors.title !== undefined ? { error: errors.title } : {})}
+ onChange={(e) => {
+ setTitle(e.target.value);
+ setErrors((p) => ({ ...p, title: undefined }));
+ }}
+ />
+ <Textarea
+ label={S.company.chart.duties}
+ size="sm"
+ rows={2}
+ value={duties}
+ hint={S.company.chart.dutiesHint}
+ onChange={(e) => setDuties(e.target.value)}
+ />
+ <Input
+ label={S.company.chart.workspace}
+ size="sm"
+ value={workspace}
+ className="font-mono"
+ hint={S.company.chart.hireWorkspaceHint}
+ placeholder={hireAgentId}
+ onChange={(e) => setWorkspace(e.target.value)}
+ />
+ <MoneyPerMonthInput
+ label={S.company.chart.budget}
+ currency={currency}
+ value={budget}
+ placeholder={S.company.chart.budgetPlaceholder}
+ hint={S.company.chart.budgetHint}
+ {...(errors.budget !== undefined ? { error: errors.budget } : {})}
+ onChange={(text) => {
+ setBudget(text);
+ setErrors((p) => ({ ...p, budget: undefined }));
+ }}
+ />
+ </div>
+ </OrgSection>
+ </div>
+ </Modal>
+ <ConfirmModal
+ open={confirmOpen}
+ title={S.company.chart.hire}
+ tone="primary"
+ confirmLabel={S.common.confirm}
+ busy={busy}
+ onClose={() => (busy ? undefined : setConfirmOpen(false))}
+ onConfirm={() => void hire()}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {S.company.chart.hireConfirm(hireName, manager.name)}
+ </p>
+ </ConfirmModal>
+ </>
+ );
+}
+
+/** Which single-field edit a dialog performs. */
+export type EmployeeEdit = "budget" | "reportsTo";
+
+export function EmployeeEditDialog({
+ edit,
+ projectId,
+ orgId,
+ employee,
+ employees,
+ onClose,
+ onSaved,
+}: {
+ /** Null closes the dialog. */
+ edit: EmployeeEdit | null;
+ projectId: string;
+ orgId: string;
+ employee: OrgEmployeeItem;
+ employees: readonly OrgEmployeeItem[];
+ onClose: () => void;
+ onSaved: () => void;
+}) {
+ const { currency } = useTheme();
+ const [value, setValue] = useState("");
+ const [error, setError] = useState<string | undefined>(undefined);
+ const [confirmOpen, setConfirmOpen] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const managers = managerCandidates(employees, employee.agentId);
+
+ useEffect(() => {
+ if (edit === null) return;
+ setError(undefined);
+ setValue(
+ edit === "budget"
+ ? fromStoredUsd(employee.budget, currency)
+ : (employee.reportsTo ?? managers[0]?.agentId ?? ""),
+ );
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [edit, employee]);
+
+ const managerName = (id: string) => employees.find((e) => e.agentId === id)?.name ?? id;
+ const title =
+ edit === "budget"
+ ? S.company.chart.budgetTitle(employee.name)
+ : S.company.chart.reportsToTitle(employee.name);
+ /** What the confirmation names: the typed amount as it will be stored, read back in the reader's currency. */
+ const budgetLabel = (raw: string) => {
+ const usd = toStoredUsd(raw, currency);
+ return usd === null ? S.company.noBudget : formatMoney(usd, currency);
+ };
+ const confirmText =
+ edit === "budget"
+ ? S.company.chart.budgetConfirm(employee.name, budgetLabel(value))
+ : S.company.chart.reportsToConfirm(employee.name, managerName(value));
+
+ const validate = (): boolean => {
+ if (edit === "budget" && !isBudgetText(value)) {
+ setError(S.company.chart.budgetHint);
+ return false;
+ }
+ if (edit === "reportsTo" && !managers.some((m) => m.agentId === value)) {
+ setError(S.company.chart.reportsToCycle);
+ return false;
+ }
+ return true;
+ };
+
+ const save = async () => {
+ if (edit === null) return;
+ setBusy(true);
+ try {
+ await api.patchOrgEmployee(
+ projectId,
+ orgId,
+ employee.agentId,
+ edit === "budget" ? { budget: toStoredUsd(value, currency) } : { reportsTo: value },
+ );
+ toastSuccess(S.company.chart.saved);
+ setConfirmOpen(false);
+ onSaved();
+ } catch (e) {
+ setConfirmOpen(false);
+ toastError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <>
+ <Modal
+ open={edit !== null}
+ title={title}
+ onClose={onClose}
+ footer={
+ <>
+ <Button size="sm" onClick={onClose} disabled={busy}>
+ {S.common.cancel}
+ </Button>
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={busy}
+ onClick={() => {
+ if (validate()) setConfirmOpen(true);
+ }}
+ >
+ {S.common.save}
+ </Button>
+ </>
+ }
+ >
+ {edit === "budget" && (
+ <div className="space-y-3">
+ <CurrentValue
+ value={
+ employee.budget === undefined
+ ? S.company.noBudget
+ : formatMoney(employee.budget, currency)
+ }
+ />
+ <MoneyPerMonthInput
+ label={S.company.chart.budget}
+ currency={currency}
+ value={value}
+ placeholder={S.company.chart.budgetPlaceholder}
+ hint={S.company.chart.budgetHint}
+ {...(error !== undefined ? { error } : {})}
+ autoFocus
+ onChange={(text) => {
+ setValue(text);
+ setError(undefined);
+ }}
+ />
+ <div className="flex justify-end">
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={busy || value.trim() === ""}
+ onClick={() => {
+ setValue("");
+ setError(undefined);
+ }}
+ >
+ {S.company.chart.clearBudget}
+ </Button>
+ </div>
+ </div>
+ )}
+ {edit === "reportsTo" && (
+ <div className="space-y-3">
+ <CurrentValue
+ value={employee.reportsTo === null ? "—" : managerName(employee.reportsTo)}
+ />
+ <div>
+ <Select
+ size="sm"
+ label={S.company.chart.manager}
+ value={value}
+ hint={S.company.chart.reportsToHint}
+ {...(error !== undefined ? { error } : {})}
+ onChange={(e) => {
+ setValue(e.target.value);
+ setError(undefined);
+ }}
+ >
+ {managers.map((m) => (
+ <option key={m.agentId} value={m.agentId}>
+ {m.name} · {m.title}
+ </option>
+ ))}
+ </Select>
+ {managers.length === 0 && <FieldError>{S.company.chart.reportsToCycle}</FieldError>}
+ </div>
+ </div>
+ )}
+ </Modal>
+ <ConfirmModal
+ open={confirmOpen}
+ title={title}
+ tone="primary"
+ confirmLabel={S.common.save}
+ busy={busy}
+ onClose={() => (busy ? undefined : setConfirmOpen(false))}
+ onConfirm={() => void save()}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">{confirmText}</p>
+ </ConfirmModal>
+ </>
+ );
+}
+
+/**
+ * The desk renewal: one confirm that both re-points the workspace and opens a fresh desk
+ * session.
+ *
+ * The two were separate menu rows, but the pair a reader wants is "give this employee a
+ * different working directory, then start its desk over there" — a workspace change reaches
+ * the employee at its next desk session anyway. The field is prefilled with the current spec,
+ * so confirming without touching it is the plain renewal (desk-renew.ts decides); a changed
+ * spec is written first and its 400 lands under the field, leaving the desk alone. A renewal
+ * that fails after the chart was already rewritten keeps the dialog open and asks the page to
+ * reload, so what is on screen never disagrees with the file.
+ */
+export function DeskRenewDialog({
+ open,
+ projectId,
+ orgId,
+ employee,
+ onClose,
+ onChartChanged,
+ onRenewed,
+}: {
+ open: boolean;
+ projectId: string;
+ orgId: string;
+ employee: OrgEmployeeItem;
+ onClose: () => void;
+ /** The workspace patch went through: the chart file changed and the page has to re-read it. */
+ onChartChanged: () => void;
+ /** Both writes went through; carries the new desk session's id. */
+ onRenewed: (sessionId: string) => void;
+}) {
+ const [workspace, setWorkspace] = useState("");
+ const [error, setError] = useState<string | undefined>(undefined);
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ if (!open) return;
+ setWorkspace(employee.workspace);
+ setError(undefined);
+ }, [open, employee]);
+
+ const confirm = async () => {
+ const plan = deskRenewPlan(employee.workspace, workspace);
+ if (!plan.valid) {
+ setError(S.common.requiredField);
+ return;
+ }
+ setBusy(true);
+ let patched = false;
+ try {
+ if (plan.workspace !== null) {
+ await api.patchOrgEmployee(projectId, orgId, employee.agentId, {
+ workspace: plan.workspace,
+ });
+ patched = true;
+ }
+ } catch (e) {
+ // A refused workspace is the field's own error, not a toast: the reader has to see it
+ // beside the box they must fix. Its code is the server's; anything else is its message.
+ setError(
+ e instanceof ApiError && e.code === "invalid_workspace"
+ ? S.company.chart.workspaceInvalid
+ : apiErrorText(e),
+ );
+ setBusy(false);
+ return;
+ }
+ try {
+ const desk = await api.renewOrgDesk(projectId, orgId, employee.agentId);
+ toastSuccess(S.company.chart.renewed);
+ onRenewed(desk.sessionId);
+ } catch (e) {
+ toastError(apiErrorText(e));
+ if (patched) onChartChanged();
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <Modal
+ open={open}
+ title={S.company.chart.renewDeskTitle(employee.name)}
+ onClose={() => (busy ? undefined : onClose())}
+ footer={
+ <>
+ <Button size="sm" onClick={onClose} disabled={busy}>
+ {S.common.cancel}
+ </Button>
+ <Button size="sm" variant="primary" disabled={busy} onClick={() => void confirm()}>
+ {S.company.chart.renewDesk}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ {/* This dialog is its own confirmation, so what it will do stays on screen instead of
+ hiding behind a "?" the reader would have to open before deciding. */}
+ <p className="text-xs text-gray-500 dark:text-gray-400">
+ {S.company.chart.renewDeskExplain}
+ </p>
+ <Input
+ label={S.company.chart.workspace}
+ required
+ size="sm"
+ value={workspace}
+ className="font-mono"
+ placeholder="."
+ hint={S.company.chart.workspaceHint}
+ {...(error !== undefined ? { error } : {})}
+ autoFocus
+ onChange={(e) => {
+ setWorkspace(e.target.value);
+ setError(undefined);
+ }}
+ />
+ </div>
+ </Modal>
+ );
+}
diff --git a/packages/web/src/features/company/finance-gauge.tsx b/packages/web/src/features/company/finance-gauge.tsx
new file mode 100644
index 00000000..4bf4f789
--- /dev/null
+++ b/packages/web/src/features/company/finance-gauge.tsx
@@ -0,0 +1,124 @@
+/**
+ * The finance page's two spend-against-budget pictures. Both ink themselves in the budget tone
+ * — success below 80%, attention from 80%, danger from 100% — and both leave the amounts to
+ * the text beside them, carrying the full statement in the accessible name and the tooltip.
+ *
+ * `FinanceGauge` is the KPI row's ring: one arc from 12 o'clock, filled to the ratio and
+ * capped at a full circle when spend is over the budget; without a budget the track stands
+ * alone. `SpendMeter` is the spend tree's bar, which carries its own percent.
+ */
+import { formatPercent } from "../../lib/format";
+import { toneDot, toneInk } from "../../lib/tone";
+import { budgetTone } from "./finance-tree";
+
+export function FinanceGauge({
+ ratio,
+ label,
+ size = 64,
+}: {
+ /** cost / budget; absent without a budget. */
+ ratio?: number;
+ /** The full statement ("$6.20 / $10 · 62%"), for the tooltip and screen readers. */
+ label: string;
+ size?: number;
+}) {
+ const tone = budgetTone(ratio);
+ const strokeWidth = Math.max(3, Math.round(size * 0.11));
+ const center = size / 2;
+ const r = (size - strokeWidth) / 2;
+ const c = 2 * Math.PI * r;
+ const fraction = ratio === undefined ? 0 : Math.min(1, Math.max(0, ratio));
+ return (
+ <svg
+ width={size}
+ height={size}
+ viewBox={`0 0 ${size} ${size}`}
+ role="img"
+ aria-label={label}
+ className={`block shrink-0 ${toneInk[tone]}`}
+ >
+ <title>{label}</title>
+ <circle
+ cx={center}
+ cy={center}
+ r={r}
+ fill="none"
+ strokeWidth={strokeWidth}
+ className="stroke-gray-200 dark:stroke-gray-800"
+ />
+ {fraction > 0 && (
+ <circle
+ cx={center}
+ cy={center}
+ r={r}
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={strokeWidth}
+ strokeLinecap={fraction < 1 ? "round" : "butt"}
+ strokeDasharray={`${fraction * c} ${c}`}
+ transform={`rotate(-90 ${center} ${center})`}
+ />
+ )}
+ </svg>
+ );
+}
+
+/**
+ * The share of the track a fill needs before the percent can sit inside it. The widest label,
+ * "100%" at 10px with its padding, is about 30px, and the bar is 80px wide in the one column
+ * that draws it — so 45% of the track holds the label, and below that there is room for it to
+ * stand past the fill's end without leaving the track.
+ */
+const PERCENT_INSIDE_MIN = 45;
+
+/**
+ * Spend against a budget as a bar with its percent drawn on it: the percent rides inside the
+ * fill once the fill is wide enough to hold it, and just past the fill's end on the track when
+ * it is not, so the number is never printed on a colour it cannot be read against. Inside, the
+ * ink is a fixed near-black rather than white: the fills are one value across both themes
+ * (lib/tone.ts explains why the dots are), and white on amber-500 measures 2.1 : 1, while
+ * gray-900 on emerald-500, amber-500 and red-500 measures 6.7, 8.1 and 4.6 : 1 in light and
+ * higher in dark, where gray-900 is darker still. Without a budget there is no percent to draw
+ * and the track stands empty.
+ */
+export function SpendMeter({
+ ratio,
+ label,
+}: {
+ /** cost / budget; absent without a budget. */
+ ratio?: number;
+ /** The full statement ("$41.00 / $100.00 · 41%"), for the tooltip and screen readers. */
+ label: string;
+}) {
+ const tone = budgetTone(ratio);
+ const width = ratio === undefined ? 0 : Math.min(100, Math.max(0, ratio * 100));
+ const inside = width >= PERCENT_INSIDE_MIN;
+ return (
+ <span
+ role="progressbar"
+ aria-label={label}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={Math.round(width)}
+ title={label}
+ className="relative block h-4 w-full overflow-hidden rounded-full bg-gray-100 dark:bg-gray-800"
+ >
+ <span
+ aria-hidden
+ className={`absolute inset-y-0 left-0 rounded-full ${toneDot[tone]}`}
+ style={{ width: `${width}%` }}
+ />
+ {ratio !== undefined && (
+ <span
+ aria-hidden
+ className={`absolute inset-y-0 flex items-center text-[10px] font-medium tabular-nums ${
+ inside ? "pr-1.5 text-gray-900" : `pl-1.5 ${toneInk[tone]}`
+ }`}
+ style={inside ? { right: `${100 - width}%` } : { left: `${width}%` }}
+ >
+ {formatPercent(ratio)}
+ </span>
+ )}
+ </span>
+ );
+}
diff --git a/packages/web/src/features/company/finance-page.tsx b/packages/web/src/features/company/finance-page.tsx
new file mode 100644
index 00000000..d4e36df4
--- /dev/null
+++ b/packages/web/src/features/company/finance-page.tsx
@@ -0,0 +1,827 @@
+/**
+ * Finance: budgets and spend for one period, as a grid of bordered cards. The top row reads
+ * the period — the KPI panel, four tiles two by two (the total against the CEO's budget with
+ * the ring riding in it, the ratio in its threshold tone, the head count and the alert count),
+ * beside the trend chart the daily costs draw. The middle row says where the spend sat, in two
+ * tables that stand side by side on a wide screen and stack on a narrow one, each cut to the
+ * columns a reader needs at a glance with the rest in the row's tooltip: the spend tree walks
+ * the reporting line in three columns — who they are, how they stand, and cumulative against
+ * budget as one meter carrying its own percent with the amounts after it and the budget edited
+ * in place (typed in the reader's currency, written to the employee in USD) — and the ticket
+ * ledger rolls costs up along parent tickets, opening on its roots alone with each parent's
+ * children behind a chevron that says how many it hides, and every title a text button that
+ * opens the ticket's detail dialog over this page (the rest of the row reads; nothing here
+ * carries the reader to another page). The period's warnings and
+ * pauses close the page full width, listed by state with how a pause is lifted. `?period=yyyy-mm`
+ * switches between this period and the previous one.
+ *
+ * Every panel here is a card and not a ruled section: the KPI tiles are bordered, and a rule
+ * standing among them reads as a different kind of thing rather than as the same thing without
+ * a border.
+ *
+ * Loading discipline: the skeleton stands only until the first response; a failed first
+ * fetch is an error with a retry; a failed refetch keeps the last good data on screen and
+ * says so in a strip above it. Two joins decorate the rows and are fetched best effort, so
+ * neither can hold the page: the employees' live states come from the org chart, the ticket
+ * owners from the board.
+ */
+import { useCallback, useEffect, useRef, useState } from "react";
+import type { ReactNode } from "react";
+import { useSearchParams } from "react-router";
+import type {
+ OrgBudgetAlert,
+ OrgEmployeeState,
+ OrgFinanceResponse,
+} from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { formatDateTime, formatMoney, formatPercent } from "../../lib/format";
+import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
+import { STAT_ICONS } from "../../lib/stat-icons";
+import { useDocumentTitle } from "../../lib/use-document-title";
+import { toneDot, toneInk, toneStrip } from "../../lib/tone";
+import type { Tone } from "../../lib/tone";
+import { useCompany } from "../../state/company";
+import { useTheme } from "../../state/theme";
+import type { Currency } from "../../state/theme";
+import { AgentAvatar } from "../../components/ui/agent-avatar";
+import { Badge } from "../../components/ui/badge";
+import { Button } from "../../components/ui/button";
+import { Chevron } from "../../components/ui/chevron";
+import { EmptyState } from "../../components/ui/empty-state";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { CloseIcon, NAV_ICONS } from "../../components/ui/icons";
+import { InfoPopover } from "../../components/ui/info-popover";
+import { noAutofill } from "../../components/ui/input";
+import { Segmented } from "../../components/ui/segmented";
+import { toastError, toastSuccess } from "../../components/ui/toast";
+import { TrendChart } from "../usage/trend-chart";
+import { OrgPage, OrgPageSkeleton, useOrg } from "./org-layout";
+import {
+ INVALID_ICON,
+ MoneyPerMonthUnit,
+ PrincipalChip,
+ StatTile,
+ StoredUsdNote,
+ TicketStatusBadge,
+ TitleButton,
+ principalLabel,
+} from "./shared";
+import { fromStoredUsd, isBudgetText, toStoredUsd } from "./budget-input";
+import { FinanceGauge, SpendMeter } from "./finance-gauge";
+import {
+ budgetTone,
+ dailyBreaks,
+ financeKpis,
+ financeSeries,
+ groupAlerts,
+ shiftPeriod,
+ spendRowTooltip,
+ spendStateMarks,
+ spendTreeRows,
+ ticketRowTooltip,
+ ticketTreeRows,
+ visibleLedgerRows,
+} from "./finance-tree";
+import type { SpendStateKey } from "./finance-tree";
+import { agentPrincipal } from "./principals";
+
+/** Pencil (lucide): the budget cell's edit affordance. */
+const PENCIL_ICON =
+ "M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497zM15 5l4 4";
+
+/** Percent (lucide percent): the ratio tile's glyph. */
+const PERCENT_ICON =
+ "M19 5 5 19M6.5 9a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5zM17.5 20a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5z";
+
+const cellClass = "px-2 py-2 text-right tabular-nums";
+const headClass = "px-2 py-1.5 text-[11px] font-medium text-gray-500 dark:text-gray-400";
+const iconButtonClass =
+ "inline-flex items-center justify-center rounded p-0.5 text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 disabled:opacity-50 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200";
+
+/** The tree's indentation step per reporting depth, and the elbow that joins a child to the row above. */
+const INDENT_PX = 20;
+
+/**
+ * The ledger's fold toggle, and the box a childless row leaves in its place so every title in
+ * the column starts on the same x whether or not its row can open.
+ */
+const FOLD_BOX = "h-4 w-4 shrink-0";
+
+function TreeElbow() {
+ return (
+ <span
+ aria-hidden
+ className="mt-0.5 h-2.5 w-2.5 shrink-0 self-start rounded-bl-sm border-b border-l border-gray-300 dark:border-gray-700"
+ />
+ );
+}
+
+/** A tone dot with its meaning beside it: the marks in the spend tree's state column. */
+function StateMark({ tone, children }: { tone: Tone; children: string }) {
+ return (
+ <span
+ className={`inline-flex shrink-0 items-center ${ICON_GAP.tight} text-[11px] ${toneInk[tone]}`}
+ >
+ <span className={`block h-1.5 w-1.5 rounded-full ${toneDot[tone]}`} />
+ {children}
+ </span>
+ );
+}
+
+/** What a state mark says: an employee's live state, or what its budget has done to it. */
+function stateMarkLabel(key: SpendStateKey): string {
+ if (key === "paused") return S.company.finance.paused;
+ if (key === "warned") return S.company.finance.warned;
+ return S.company.employeeStates[key] ?? key;
+}
+
+/**
+ * One panel of the finance page: a bordered card with its title inside it and the "?" anchored
+ * to that title — the shape the KPI tiles and the cost centre's charts already use. The
+ * period switch is the page's, not a panel's, so a card carries no controls of its own.
+ */
+function FinanceCard({
+ title,
+ info,
+ children,
+ className = "",
+}: {
+ title: string;
+ info?: string;
+ children: ReactNode;
+ className?: string;
+}) {
+ return (
+ <section
+ className={`min-w-0 rounded-md border border-gray-200 bg-white p-3 dark:border-gray-800 dark:bg-gray-900 ${className}`}
+ >
+ <h2
+ className={`mb-2 flex min-w-0 items-center ${ICON_GAP.row} text-xs font-medium text-gray-500 dark:text-gray-400`}
+ >
+ {title}
+ {info !== undefined && <InfoPopover label={title}>{info}</InfoPopover>}
+ </h2>
+ {children}
+ </section>
+ );
+}
+
+/**
+ * The budget cell while it is being typed: a number box in the reader's own currency with the
+ * unit after it (empty = unbounded, said beneath it while typing), save and cancel. Enter
+ * saves, Escape cancels, and focus leaving the editor saves too — the two buttons keep focus
+ * on mousedown so clicking cancel never saves first. What goes out is USD, which is what the
+ * chart file holds, and a box in another currency says so under itself.
+ */
+function BudgetEditor({
+ initial,
+ name,
+ currency,
+ busy,
+ onSave,
+ onCancel,
+}: {
+ /** The stored budget in USD; undefined is unbounded. */
+ initial: number | undefined;
+ name: string;
+ currency: Currency;
+ busy: boolean;
+ /** The new budget in USD, or null for unbounded. */
+ onSave: (value: number | null) => void;
+ onCancel: () => void;
+}) {
+ const [text, setText] = useState(() => fromStoredUsd(initial, currency));
+ const wrapRef = useRef<HTMLSpanElement>(null);
+ const commit = () => {
+ if (!isBudgetText(text)) {
+ toastError(S.company.chart.budgetHint);
+ return;
+ }
+ onSave(toStoredUsd(text, currency));
+ };
+ return (
+ <span
+ ref={wrapRef}
+ className="inline-flex flex-col items-end gap-0.5"
+ onBlur={(e) => {
+ if (!wrapRef.current?.contains(e.relatedTarget as Node | null)) commit();
+ }}
+ >
+ <span className={`inline-flex items-center ${ICON_GAP.tight}`}>
+ <input
+ autoFocus
+ type="number"
+ inputMode="decimal"
+ min={0}
+ step="any"
+ value={text}
+ placeholder={S.company.finance.budgetPlaceholder}
+ aria-label={S.company.finance.editBudgetOf(name)}
+ disabled={busy}
+ {...noAutofill}
+ onChange={(e) => setText(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ commit();
+ } else if (e.key === "Escape") {
+ e.preventDefault();
+ onCancel();
+ }
+ }}
+ className="w-24 rounded-md border border-gray-300 bg-white px-1.5 py-0.5 text-right text-xs tabular-nums focus:border-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-400/30 dark:border-gray-700 dark:bg-gray-900"
+ />
+ <MoneyPerMonthUnit currency={currency} />
+ <button
+ type="button"
+ title={S.company.finance.saveBudget}
+ aria-label={S.company.finance.saveBudget}
+ disabled={busy}
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={commit}
+ className={iconButtonClass}
+ >
+ <GlyphIcon d={STAT_ICONS.check} size={ICON_SIZE.inlineGlyph} />
+ </button>
+ <button
+ type="button"
+ title={S.company.finance.cancelEdit}
+ aria-label={S.company.finance.cancelEdit}
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={onCancel}
+ className={iconButtonClass}
+ >
+ <CloseIcon />
+ </button>
+ </span>
+ <span className="text-[10px] text-gray-400 dark:text-gray-500">
+ {S.company.finance.budgetEmptyHint}
+ </span>
+ <StoredUsdNote usd={toStoredUsd(text, currency)} currency={currency} />
+ </span>
+ );
+}
+
+/** One alert line: the employee, and when it crossed the threshold. */
+function AlertRow({
+ alert,
+ tone,
+ names,
+}: {
+ alert: OrgBudgetAlert;
+ tone: Tone;
+ names: ReadonlyMap<string, string>;
+}) {
+ const at = tone === "danger" ? alert.pausedAt : alert.warnedAt;
+ const when = at === undefined ? "" : formatDateTime(at);
+ return (
+ <li className={`flex flex-wrap items-center ${ICON_GAP.menu} py-1 text-xs`}>
+ <span className={`block h-1.5 w-1.5 shrink-0 rounded-full ${toneDot[tone]}`} />
+ <PrincipalChip
+ principal={agentPrincipal(alert.agentId)}
+ names={names}
+ size={ICON_SIZE.rowLead}
+ />
+ <span className="text-gray-500 dark:text-gray-400">
+ {tone === "danger" ? S.company.finance.pausedAt(when) : S.company.finance.warnedAt(when)}
+ </span>
+ </li>
+ );
+}
+
+export function FinancePage() {
+ const { projectId, orgId, org } = useOrg();
+ const company = useCompany();
+ const { currency } = useTheme();
+ const [params, setParams] = useSearchParams();
+ useDocumentTitle(org ? `${org.name} · ${S.nav.org.finance}` : S.nav.org.finance);
+ const [data, setData] = useState<OrgFinanceResponse | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ /** Ticket owners, joined from the board (best effort: the finance rows carry none). */
+ const [owners, setOwners] = useState<ReadonlyMap<string, string>>(new Map());
+ /** Live employee states, joined from the org chart (best effort, for the state column). */
+ const [states, setStates] = useState<ReadonlyMap<string, OrgEmployeeState>>(new Map());
+ /** The employee whose budget is being typed. */
+ const [editingId, setEditingId] = useState<string | null>(null);
+ /**
+ * The ticket ledger's opened parents. Deliberately not persisted and not a URL parameter: a
+ * fold is how the reader is looking at the table right now, and a ledger that reopened
+ * yesterday's branches would hide today's roots behind them.
+ */
+ const [expandedTickets, setExpandedTickets] = useState<ReadonlySet<string>>(() => new Set());
+ const [busy, setBusy] = useState(false);
+ const requested = params.get("period");
+ /** Sequence of the newest request: a slower, older response must not overwrite a newer one. */
+ const seq = useRef(0);
+
+ const load = useCallback(async () => {
+ const my = ++seq.current;
+ void api
+ .listOrgTickets(projectId, orgId)
+ .then((res) => {
+ if (my !== seq.current) return;
+ const map = new Map<string, string>();
+ for (const column of Object.values(res.columns)) {
+ for (const t of column) if (t.owner !== undefined) map.set(t.ticketId, t.owner);
+ }
+ setOwners(map);
+ })
+ .catch(() => undefined);
+ void api
+ .getOrgChart(projectId, orgId)
+ .then((res) => {
+ if (my !== seq.current) return;
+ setStates(new Map(res.employees.map((e) => [e.agentId, e.state])));
+ })
+ .catch(() => undefined);
+ try {
+ const res = await api.getOrgFinance(projectId, orgId, requested ?? undefined);
+ if (my !== seq.current) return;
+ setData(res);
+ setError(null);
+ } catch (e) {
+ if (my !== seq.current) return;
+ setError(apiErrorText(e));
+ }
+ }, [projectId, orgId, requested]);
+ const { budget: budgetVersion, runs } = company.versions;
+ useEffect(() => {
+ void load();
+ }, [load, budgetVersion, runs]);
+
+ const names = new Map((data?.employees ?? []).map((e) => [e.agentId, e.name]));
+ // The current period is the organization's (its summary is computed in its timezone); the
+ // response's period only stands in before the summary is known.
+ const currentPeriod = org?.spend.period ?? (requested === null ? (data?.period ?? "") : "");
+ const previous = currentPeriod === "" ? null : shiftPeriod(currentPeriod, -1);
+ const target = requested ?? currentPeriod;
+ const setPeriod = (p: string) => {
+ const next = new URLSearchParams(params);
+ if (p === currentPeriod) next.delete("period");
+ else next.set("period", p);
+ setParams(next, { replace: true });
+ };
+
+ const saveBudget = async (agentId: string, value: number | null) => {
+ const row = data?.employees.find((e) => e.agentId === agentId);
+ if (row !== undefined && (row.budget ?? null) === value) {
+ setEditingId(null);
+ return;
+ }
+ setBusy(true);
+ try {
+ await api.patchOrgEmployee(projectId, orgId, agentId, { budget: value });
+ toastSuccess(S.company.finance.budgetSaved);
+ setEditingId(null);
+ void load();
+ void company.reloadOrganizations();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const periodSwitch =
+ previous !== null ? (
+ <Segmented
+ options={[
+ { value: previous, label: `${S.company.finance.prevPeriod} ${previous}` },
+ { value: currentPeriod, label: `${S.company.finance.thisPeriod} ${currentPeriod}` },
+ ]}
+ value={target === previous ? previous : currentPeriod}
+ onChange={setPeriod}
+ cols={2}
+ />
+ ) : undefined;
+
+ if (data === null) {
+ return (
+ <OrgPage title={S.nav.org.finance} info={S.company.finance.info} actions={periodSwitch}>
+ {error !== null ? (
+ <EmptyState
+ title={error}
+ action={<Button onClick={() => void load()}>{S.common.retry}</Button>}
+ />
+ ) : (
+ <OrgPageSkeleton />
+ )}
+ </OrgPage>
+ );
+ }
+
+ const kpis = financeKpis(data);
+ const ratioTone = budgetTone(kpis.ratio);
+ /** Spend against a budget as one sentence — what the ring and every meter carry as their name. */
+ const spendLabel = (
+ cost: number,
+ budget: number | undefined,
+ ratio: number | undefined,
+ ): string =>
+ budget === undefined
+ ? `${formatMoney(cost, currency)} · ${S.company.noBudget}`
+ : `${S.company.spendOfBudget(formatMoney(cost, currency), formatMoney(budget, currency))} · ${formatPercent(ratio)}`;
+ const gaugeLabel = spendLabel(kpis.total, kpis.budget, kpis.ratio);
+ const rows = spendTreeRows(data.employees);
+ const ticketRows = visibleLedgerRows(ticketTreeRows(data.tickets), expandedTickets);
+ const toggleTicket = (ticketId: string) =>
+ setExpandedTickets((prev) => {
+ const next = new Set(prev);
+ if (!next.delete(ticketId)) next.add(ticketId);
+ return next;
+ });
+ const series = financeSeries(data.daily);
+ const alerts = groupAlerts(data.alerts);
+ // A period switch keeps the last data on screen, dimmed, until the new one lands.
+ const stale = target !== "" && data.period !== target;
+ const openTicket = (ticketId: string) => company.openTicket(projectId, orgId, ticketId);
+
+ return (
+ <OrgPage title={S.nav.org.finance} info={S.company.finance.info} actions={periodSwitch}>
+ {error !== null && (
+ <div
+ className={`mb-4 flex items-center justify-between gap-2 rounded-md border px-3 py-1.5 text-xs ${toneStrip.danger}`}
+ >
+ <span>
+ {S.company.finance.refreshFailed} · {error}
+ </span>
+ <Button size="sm" onClick={() => void load()}>
+ {S.common.retry}
+ </Button>
+ </div>
+ )}
+ <div className={stale ? "opacity-60 transition-opacity" : "transition-opacity"}>
+ {/* Top row: what the period cost against the budget, beside how it accumulated. */}
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
+ {/* The KPI panel: four bordered tiles two by two, the ring riding in the first. */}
+ <div className="min-w-0">
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
+ <StatTile
+ icon={STAT_ICONS.cost}
+ label={S.company.finance.kpiTotal}
+ value={formatMoney(kpis.total, currency)}
+ detail={`${S.company.finance.orgBudget} · ${
+ kpis.budget === undefined
+ ? S.company.noBudget
+ : formatMoney(kpis.budget, currency)
+ }`}
+ >
+ {/* Small: the tile is a quarter of the KPI panel, and the ring is the
+ picture of a number that is already spelled out beside it. */}
+ <FinanceGauge ratio={kpis.ratio} label={gaugeLabel} size={40} />
+ </StatTile>
+ <StatTile
+ icon={PERCENT_ICON}
+ label={S.company.finance.ratio}
+ value={formatPercent(kpis.ratio)}
+ detail={S.company.finance.thresholds}
+ {...(ratioTone === "muted" ? {} : { tone: ratioTone })}
+ />
+ <StatTile
+ icon={NAV_ICONS.orgChart}
+ label={S.company.finance.kpiEmployees}
+ value={kpis.employees}
+ detail={S.company.finance.budgetsSet(kpis.budgeted)}
+ />
+ <StatTile
+ icon={INVALID_ICON}
+ label={S.company.finance.kpiAlerts}
+ value={data.alerts.length}
+ detail={S.company.finance.alertsSummary(kpis.warned, kpis.paused)}
+ {...(kpis.paused > 0
+ ? { tone: "danger" as const }
+ : kpis.warned > 0
+ ? { tone: "attention" as const }
+ : {})}
+ />
+ </div>
+ {data.unpriced && (
+ <p className="mt-3 text-xs text-gray-400 dark:text-gray-500">
+ {S.company.finance.unpriced}
+ </p>
+ )}
+ </div>
+ <FinanceCard title={S.company.finance.trend} info={S.company.finance.trendInfo}>
+ {series.length === 0 ? (
+ <p className="py-2 text-xs text-gray-400 dark:text-gray-500">
+ {S.company.finance.trendEmpty}
+ </p>
+ ) : (
+ <TrendChart
+ series={series}
+ granularity="day"
+ currency={currency}
+ breaks={dailyBreaks(data.daily)}
+ />
+ )}
+ </FinanceCard>
+ </div>
+
+ {/* Middle row: where the spend sat — by employee, and by ticket; each table scrolls in its own half. */}
+ {/* The two tables sit side by side only from 1536px: a three-column spend tree with its
+ meter needs about 560px, and half of a laptop's content column is less than that —
+ below the threshold they stack rather than scroll sideways. */}
+ <div className="mt-4 grid grid-cols-1 gap-4 2xl:grid-cols-2">
+ <FinanceCard title={S.company.finance.spendTree} info={S.company.finance.spendTreeInfo}>
+ <div className="overflow-x-auto">
+ <table className="w-full min-w-[20rem] text-xs">
+ <thead>
+ <tr>
+ <th className={`${headClass} text-left`}>{S.company.overview.employees}</th>
+ <th className={`${headClass} text-left`}>{S.company.status}</th>
+ <th className={`${headClass} text-right`}>
+ <span className={`inline-flex items-center ${ICON_GAP.tight}`}>
+ {S.company.finance.cumulativeBudget}
+ <InfoPopover label={S.company.finance.cumulativeBudget}>
+ {S.company.finance.cumulativeInfo}
+ </InfoPopover>
+ </span>
+ </th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-gray-100 dark:divide-gray-800/60">
+ {rows.map(({ employee, depth }) => {
+ const editing = editingId === employee.agentId;
+ const marks = spendStateMarks(employee, states.get(employee.agentId));
+ return (
+ <tr
+ key={employee.agentId}
+ title={spendRowTooltip(
+ employee,
+ {
+ own: S.company.finance.own,
+ cumulative: S.company.finance.cumulative,
+ budget: S.company.finance.budget,
+ noBudget: S.company.noBudget,
+ },
+ (value) => formatMoney(value, currency),
+ )}
+ >
+ <td className="px-2 py-2" style={{ paddingLeft: 8 + depth * INDENT_PX }}>
+ <span className={`flex min-w-0 items-center ${ICON_GAP.row}`}>
+ {depth > 0 && <TreeElbow />}
+ <AgentAvatar
+ id={employee.agentId}
+ name={employee.name}
+ size={ICON_SIZE.navRow}
+ className="shrink-0 rounded"
+ />
+ <span className="truncate font-medium text-gray-900 dark:text-gray-100">
+ {employee.name}
+ </span>
+ {employee.reportsTo === null &&
+ employee.title.trim().toLowerCase() !== "ceo" && (
+ <Badge tone="gray">{S.company.ceo}</Badge>
+ )}
+ <span className="truncate text-gray-400 dark:text-gray-500">
+ {employee.title}
+ </span>
+ </span>
+ </td>
+ {/* How the employee stands: what it is doing right now, and what its
+ budget has done to it. Empty while the chart join is in flight and
+ nothing has crossed a threshold — an empty cell says exactly that. */}
+ <td className="whitespace-nowrap px-2 py-2">
+ <span className={`flex flex-wrap items-center ${ICON_GAP.menu}`}>
+ {marks.map((mark) => (
+ <StateMark key={mark.key} tone={mark.tone}>
+ {stateMarkLabel(mark.key)}
+ </StateMark>
+ ))}
+ </span>
+ </td>
+ {/* The meter carries the percent, the amounts follow it, and the budget
+ half of them is the button that edits it — so the pencil still sits
+ on the number it changes. Own spend rides in the row's tooltip. */}
+ <td className={`${cellClass} whitespace-nowrap`}>
+ {editing ? (
+ <BudgetEditor
+ initial={employee.budget}
+ name={employee.name}
+ currency={currency}
+ busy={busy}
+ onSave={(value) => void saveBudget(employee.agentId, value)}
+ onCancel={() => setEditingId(null)}
+ />
+ ) : (
+ <span className={`flex items-center ${ICON_GAP.menu}`}>
+ {/* Fixed width, first in the cell: every meter then starts at the
+ same x and the column reads as one chart. */}
+ <span className="w-20 shrink-0">
+ <SpendMeter
+ label={spendLabel(
+ employee.cumulative,
+ employee.budget,
+ employee.ratio,
+ )}
+ {...(employee.ratio !== undefined
+ ? { ratio: employee.ratio }
+ : {})}
+ />
+ </span>
+ <span className="flex-1 text-right">
+ <span className="font-semibold text-gray-900 dark:text-gray-100">
+ {formatMoney(employee.cumulative, currency)}
+ </span>
+ <span aria-hidden className="px-1 text-gray-300 dark:text-gray-600">
+ {employee.budget === undefined ? "·" : "/"}
+ </span>
+ <button
+ type="button"
+ title={S.company.finance.editBudget}
+ aria-label={S.company.finance.editBudgetOf(employee.name)}
+ onClick={() => setEditingId(employee.agentId)}
+ className={`group inline-flex items-center ${ICON_GAP.tight} rounded px-1 py-0.5 tabular-nums transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800`}
+ >
+ <span
+ className={
+ employee.budget === undefined
+ ? "text-gray-400 dark:text-gray-500"
+ : "text-gray-900 dark:text-gray-100"
+ }
+ >
+ {employee.budget === undefined
+ ? S.company.noBudget
+ : formatMoney(employee.budget, currency)}
+ </span>
+ <GlyphIcon
+ d={PENCIL_ICON}
+ size={ICON_SIZE.inlineGlyph}
+ className="text-gray-300 transition-colors duration-150 group-hover:text-gray-600 dark:text-gray-600 dark:group-hover:text-gray-300"
+ />
+ </button>
+ </span>
+ </span>
+ )}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ </FinanceCard>
+
+ <FinanceCard title={S.company.finance.ticketsTable} info={S.company.finance.ticketsInfo}>
+ {ticketRows.length === 0 ? (
+ <p className="py-2 text-xs text-gray-400 dark:text-gray-500">
+ {S.company.finance.ticketsEmpty}
+ </p>
+ ) : (
+ <div className="overflow-x-auto">
+ <table className="w-full min-w-[17rem] text-xs">
+ <thead>
+ <tr>
+ <th className={`${headClass} text-left`}>{S.nav.org.tickets}</th>
+ <th className={`${headClass} text-left`}>{S.company.status}</th>
+ <th className={`${headClass} text-right`}>
+ <span className={`inline-flex items-center ${ICON_GAP.tight}`}>
+ {S.company.finance.rolledUp}
+ <InfoPopover label={S.company.finance.rolledUp}>
+ {S.company.finance.rolledUpInfo}
+ </InfoPopover>
+ </span>
+ </th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-gray-100 dark:divide-gray-800/60">
+ {ticketRows.map(({ ticket, depth, children }) => {
+ const owner = owners.get(ticket.ticketId);
+ const open = expandedTickets.has(ticket.ticketId);
+ return (
+ // The id, the owner and the ticket's own cost ride in the row's
+ // tooltip: three columns the table cannot afford beside the spend tree.
+ <tr
+ key={ticket.ticketId}
+ title={ticketRowTooltip(
+ ticket,
+ owner === undefined ? undefined : principalLabel(owner, names),
+ {
+ owner: S.company.tickets.owner,
+ noOwner: S.company.tickets.noOwner,
+ cost: S.company.tickets.cost,
+ rolledUp: S.company.finance.rolledUp,
+ },
+ (value) => formatMoney(value, currency),
+ )}
+ >
+ <td className="px-2 py-2" style={{ paddingLeft: 8 + depth * INDENT_PX }}>
+ <span className={`flex min-w-0 items-center ${ICON_GAP.row}`}>
+ {depth > 0 && <TreeElbow />}
+ {children > 0 ? (
+ <button
+ type="button"
+ aria-expanded={open}
+ title={
+ open
+ ? S.company.finance.collapseChildren
+ : S.company.finance.expandChildren
+ }
+ aria-label={`${
+ open
+ ? S.company.finance.collapseChildren
+ : S.company.finance.expandChildren
+ } · ${ticket.title}`}
+ onClick={() => toggleTicket(ticket.ticketId)}
+ className={`${iconButtonClass} ${FOLD_BOX}`}
+ >
+ <Chevron open={open} size={ICON_SIZE.chevronDense} />
+ </button>
+ ) : (
+ <span aria-hidden className={FOLD_BOX} />
+ )}
+ {/* The title is the link; the rest of the row reads. */}
+ <TitleButton
+ className="truncate font-medium text-gray-900 dark:text-gray-100"
+ title={S.company.finance.openTicket}
+ onClick={() => openTicket(ticket.ticketId)}
+ >
+ {ticket.title}
+ </TitleButton>
+ {children > 0 && !open && (
+ <span className="shrink-0 text-[11px] text-gray-400 dark:text-gray-500">
+ {S.company.finance.childCount(children)}
+ </span>
+ )}
+ </span>
+ </td>
+ <td className="whitespace-nowrap px-2 py-2">
+ <TicketStatusBadge status={ticket.status} />
+ </td>
+ <td
+ className={`${cellClass} whitespace-nowrap font-semibold text-gray-900 dark:text-gray-100`}
+ >
+ {formatMoney(ticket.rolledUp, currency)}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </FinanceCard>
+ </div>
+
+ <FinanceCard
+ title={S.company.finance.alerts}
+ info={S.company.finance.alertsInfo}
+ className="mt-4"
+ >
+ {data.alerts.length === 0 ? (
+ <p className="py-2 text-xs text-gray-400 dark:text-gray-500">
+ {S.company.finance.alertsEmpty}
+ </p>
+ ) : (
+ <div className="grid gap-x-8 gap-y-3 sm:grid-cols-2">
+ <AlertGroup
+ title={S.company.finance.pausedGroup}
+ tone="danger"
+ alerts={alerts.paused}
+ names={names}
+ />
+ <AlertGroup
+ title={S.company.finance.warnedGroup}
+ tone="attention"
+ alerts={alerts.warned}
+ names={names}
+ />
+ </div>
+ )}
+ <p className="mt-3 text-[11px] text-gray-400 dark:text-gray-500">
+ {S.company.finance.alertsHint}
+ </p>
+ </FinanceCard>
+ </div>
+ </OrgPage>
+ );
+}
+
+/** One state's alerts: a small title with the count, then the rows; nothing when the group is empty. */
+function AlertGroup({
+ title,
+ tone,
+ alerts,
+ names,
+}: {
+ title: string;
+ tone: Tone;
+ alerts: readonly OrgBudgetAlert[];
+ names: ReadonlyMap<string, string>;
+}) {
+ if (alerts.length === 0) return null;
+ return (
+ <div>
+ <p className={`text-[11px] font-medium ${toneInk[tone]}`}>
+ {title} · {alerts.length}
+ </p>
+ <ul className="mt-1 divide-y divide-gray-100 dark:divide-gray-800/60">
+ {alerts.map((a) => (
+ <AlertRow key={`${a.agentId}/${a.period}`} alert={a} tone={tone} names={names} />
+ ))}
+ </ul>
+ </div>
+ );
+}
diff --git a/packages/web/src/features/company/finance-tree.ts b/packages/web/src/features/company/finance-tree.ts
new file mode 100644
index 00000000..8844411b
--- /dev/null
+++ b/packages/web/src/features/company/finance-tree.ts
@@ -0,0 +1,282 @@
+/**
+ * The finance page's shaping (pure, unit tested): the spend tree in reporting-line order with
+ * depths, the ticket ledger along parent tickets and which of its rows a fold leaves visible,
+ * period arithmetic for the this / previous switch, the tone a budget ratio takes, the marks an
+ * employee's state column carries, the daily series in the trend chart's shape (with the axis
+ * breaks where days were skipped), the KPI row's numbers, the alert list grouped by state, and
+ * the two row tooltips that carry the figures the tables no longer spend a column on.
+ */
+import type {
+ OrgBudgetAlert,
+ OrgEmployeeState,
+ OrgFinanceEmployee,
+ OrgFinanceResponse,
+ OrgFinanceTicket,
+ UsageSeriesPoint,
+} from "@prismshadow/penguin-server/api";
+import type { Tone } from "../../lib/tone";
+import { employeeStateTone } from "./chart-view";
+
+/** Employees in DFS order from the root(s), each with its depth; a row whose manager is missing starts a tree of its own. */
+export function spendTreeRows(
+ employees: readonly OrgFinanceEmployee[],
+): Array<{ employee: OrgFinanceEmployee; depth: number }> {
+ const ids = new Set(employees.map((e) => e.agentId));
+ const childrenOf = new Map<string | null, OrgFinanceEmployee[]>();
+ for (const e of employees) {
+ const parent = e.reportsTo !== null && ids.has(e.reportsTo) ? e.reportsTo : null;
+ const list = childrenOf.get(parent);
+ if (list) list.push(e);
+ else childrenOf.set(parent, [e]);
+ }
+ const out: Array<{ employee: OrgFinanceEmployee; depth: number }> = [];
+ const seen = new Set<string>();
+ const walk = (parent: string | null, depth: number): void => {
+ for (const e of childrenOf.get(parent) ?? []) {
+ if (seen.has(e.agentId)) continue;
+ seen.add(e.agentId);
+ out.push({ employee: e, depth });
+ walk(e.agentId, depth + 1);
+ }
+ };
+ walk(null, 0);
+ return out;
+}
+
+/** Tickets in parent-first order with depths (a child under its parent, an unknown parent starting at the top). */
+export function ticketTreeRows(
+ tickets: readonly OrgFinanceTicket[],
+): Array<{ ticket: OrgFinanceTicket; depth: number }> {
+ const ids = new Set(tickets.map((t) => t.ticketId));
+ const childrenOf = new Map<string | null, OrgFinanceTicket[]>();
+ for (const t of tickets) {
+ const parent = t.parent !== undefined && ids.has(t.parent) ? t.parent : null;
+ const list = childrenOf.get(parent);
+ if (list) list.push(t);
+ else childrenOf.set(parent, [t]);
+ }
+ const out: Array<{ ticket: OrgFinanceTicket; depth: number }> = [];
+ const seen = new Set<string>();
+ const walk = (parent: string | null, depth: number): void => {
+ for (const t of childrenOf.get(parent) ?? []) {
+ if (seen.has(t.ticketId)) continue;
+ seen.add(t.ticketId);
+ out.push({ ticket: t, depth });
+ walk(t.ticketId, depth + 1);
+ }
+ };
+ walk(null, 0);
+ return out;
+}
+
+/** A ledger row on screen: the ticket, its depth, and how many children hang directly under it. */
+export interface LedgerRow {
+ ticket: OrgFinanceTicket;
+ depth: number;
+ /** Direct children only — what a folded parent reports, and 0 on a leaf (which wears no chevron). */
+ children: number;
+}
+
+/**
+ * The ticket ledger's rows as the table draws them: a parent's subtree is hidden unless the
+ * parent's id is in `expanded`, so a board of a hundred tickets opens as a short list of roots
+ * and grows only where the reader asks. A row is dropped when *any* ancestor is folded, not
+ * just its own parent, which is what makes expanding a grandchild's parent enough on its own.
+ *
+ * `rows` is `ticketTreeRows`' output: parent-first depth-first, so a row's subtree is exactly
+ * the run of deeper rows that follows it. Expansion is the caller's state and deliberately not
+ * persisted — a fold is how the reader looks at the table now, not a setting.
+ */
+export function visibleLedgerRows(
+ rows: ReadonlyArray<{ ticket: OrgFinanceTicket; depth: number }>,
+ expanded: ReadonlySet<string>,
+): LedgerRow[] {
+ const out: LedgerRow[] = [];
+ /** The depth of the shallowest folded parent whose subtree is being skipped; null while none is. */
+ let folded: number | null = null;
+ for (let i = 0; i < rows.length; i++) {
+ const row = rows[i]!;
+ if (folded !== null && row.depth > folded) continue;
+ folded = null;
+ let children = 0;
+ for (let j = i + 1; j < rows.length && rows[j]!.depth > row.depth; j++) {
+ if (rows[j]!.depth === row.depth + 1) children++;
+ }
+ out.push({ ticket: row.ticket, depth: row.depth, children });
+ if (children > 0 && !expanded.has(row.ticket.ticketId)) folded = row.depth;
+ }
+ return out;
+}
+
+/**
+ * The tooltip an employee row of the spend tree carries: own spend, cumulative spend and the
+ * budget, each named. The table shows cumulative against budget in one cell and leaves own
+ * spend to this line, so the reader still reaches it without a column of its own. `money`
+ * formats an amount in the reader's currency; `labels.noBudget` stands in for an unbounded one.
+ */
+export function spendRowTooltip(
+ row: { own: number; cumulative: number; budget?: number },
+ labels: { own: string; cumulative: string; budget: string; noBudget: string },
+ money: (value: number) => string,
+): string {
+ return [
+ `${labels.own} ${money(row.own)}`,
+ `${labels.cumulative} ${money(row.cumulative)}`,
+ `${labels.budget} ${row.budget === undefined ? labels.noBudget : money(row.budget)}`,
+ ].join(" · ");
+}
+
+/**
+ * The tooltip a ticket row carries: its id, its owner, its own cost and its rolled-up cost —
+ * the three the table dropped so it fits beside the spend tree. `owner` is the display name of
+ * whoever owns it, absent when nobody does.
+ */
+export function ticketRowTooltip(
+ row: { ticketId: string; cost: number; rolledUp: number },
+ owner: string | undefined,
+ labels: { owner: string; noOwner: string; cost: string; rolledUp: string },
+ money: (value: number) => string,
+): string {
+ return [
+ row.ticketId,
+ `${labels.owner} ${owner ?? labels.noOwner}`,
+ `${labels.cost} ${money(row.cost)}`,
+ `${labels.rolledUp} ${money(row.rolledUp)}`,
+ ].join(" · ");
+}
+
+/** `yyyy-mm` shifted by whole months (a negative delta goes back). Null for anything not of that shape. */
+export function shiftPeriod(period: string, delta: number): string | null {
+ const m = /^(\d{4})-(\d{2})$/.exec(period);
+ if (!m) return null;
+ const year = Number(m[1]);
+ const month0 = Number(m[2]) - 1;
+ if (month0 < 0 || month0 > 11) return null;
+ const total = year * 12 + month0 + delta;
+ const y = Math.floor(total / 12);
+ const mo = total - y * 12;
+ return `${String(y).padStart(4, "0")}-${String(mo + 1).padStart(2, "0")}`;
+}
+
+/** The tone a spend-against-budget ratio takes: attention from 80%, danger from 100%, success below; muted without a budget. */
+export function budgetTone(ratio: number | undefined): Tone {
+ if (ratio === undefined || !Number.isFinite(ratio)) return "muted";
+ if (ratio >= 1) return "danger";
+ if (ratio >= 0.8) return "attention";
+ return "success";
+}
+
+/** What a mark in the spend tree's state column says; the caller spells each one's label. */
+export type SpendStateKey = "running" | "idle" | "warned" | "paused";
+
+export interface SpendStateMark {
+ tone: Tone;
+ key: SpendStateKey;
+}
+
+/**
+ * The state column's marks for one employee: its live state first — running, or on the desk —
+ * then what its budget has to say about it. A budget pause is the *reason* a live state reads
+ * `paused`, so the two collapse into the single danger mark that names it; a row never says
+ * "paused" twice. The live state is joined from the org chart, which the finance page fetches
+ * best effort, so an absent one leaves the budget marks standing alone rather than blocking
+ * the table on a second request.
+ */
+export function spendStateMarks(
+ row: { warned: boolean; paused: boolean },
+ live: OrgEmployeeState | undefined,
+): SpendStateMark[] {
+ const out: SpendStateMark[] = [];
+ if (live !== undefined && live !== "paused")
+ out.push({ tone: employeeStateTone(live), key: live });
+ if (row.paused || live === "paused") out.push({ tone: "danger", key: "paused" });
+ else if (row.warned) out.push({ tone: "attention", key: "warned" });
+ return out;
+}
+
+/** The finance page's daily costs in the cost trend chart's series shape (tokens unknown here, so zero). */
+export function financeSeries(
+ daily: ReadonlyArray<{ date: string; cost: number }>,
+): UsageSeriesPoint[] {
+ return daily.map((d) => ({
+ bucket: d.date,
+ cacheRead: 0,
+ cacheWrite: 0,
+ output: 0,
+ total: 0,
+ cost: d.cost,
+ requests: 0,
+ completed: 0,
+ denominator: 0,
+ }));
+}
+
+/** `yyyy-mm-dd` as a UTC day number; null for anything else. */
+function dayNumber(date: string): number | null {
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date);
+ if (!m) return null;
+ const ms = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
+ return Number.isNaN(ms) ? null : Math.round(ms / 86_400_000);
+}
+
+/**
+ * Indices after which the daily series skips at least one calendar day: the server lists
+ * only the days that recorded a cost, so the chart marks the gaps on its axis rather than
+ * drawing the remaining days as neighbours.
+ */
+export function dailyBreaks(daily: ReadonlyArray<{ date: string }>): number[] {
+ const out: number[] = [];
+ for (let i = 0; i + 1 < daily.length; i++) {
+ const a = dayNumber(daily[i]!.date);
+ const b = dayNumber(daily[i + 1]!.date);
+ if (a !== null && b !== null && b - a > 1) out.push(i);
+ }
+ return out;
+}
+
+/** The KPI row: the organization's total against the root's (CEO's) budget, head counts and alert counts. */
+export interface FinanceKpis {
+ total: number;
+ /** The root employee's budget, which covers the whole organization; absent = unbounded. */
+ budget?: number;
+ ratio?: number;
+ employees: number;
+ /** Employees with a budget of their own. */
+ budgeted: number;
+ /** Warned but not (yet) paused. */
+ warned: number;
+ paused: number;
+}
+
+export function financeKpis(data: Pick<OrgFinanceResponse, "employees" | "total">): FinanceKpis {
+ const root = data.employees.find((e) => e.reportsTo === null) ?? data.employees[0];
+ const budget = root?.budget;
+ const ratio = budget !== undefined && budget > 0 ? data.total / budget : undefined;
+ return {
+ total: data.total,
+ ...(budget !== undefined ? { budget } : {}),
+ ...(ratio !== undefined ? { ratio } : {}),
+ employees: data.employees.length,
+ budgeted: data.employees.filter((e) => e.budget !== undefined).length,
+ warned: data.employees.filter((e) => e.warned && !e.paused).length,
+ paused: data.employees.filter((e) => e.paused).length,
+ };
+}
+
+/**
+ * Alerts grouped by state, newest first inside each group: a pause outranks the warning
+ * that preceded it, so an alert carrying both timestamps lists under `paused` only.
+ */
+export function groupAlerts(alerts: readonly OrgBudgetAlert[]): {
+ paused: OrgBudgetAlert[];
+ warned: OrgBudgetAlert[];
+} {
+ const paused = alerts.filter((a) => a.pausedAt !== undefined);
+ const warned = alerts.filter((a) => a.pausedAt === undefined && a.warnedAt !== undefined);
+ const newestFirst = (key: "pausedAt" | "warnedAt") => (a: OrgBudgetAlert, b: OrgBudgetAlert) =>
+ (b[key] ?? "").localeCompare(a[key] ?? "");
+ return {
+ paused: paused.sort(newestFirst("pausedAt")),
+ warned: warned.sort(newestFirst("warnedAt")),
+ };
+}
diff --git a/packages/web/src/features/company/handbook-explorer.tsx b/packages/web/src/features/company/handbook-explorer.tsx
new file mode 100644
index 00000000..6768d5dc
--- /dev/null
+++ b/packages/web/src/features/company/handbook-explorer.tsx
@@ -0,0 +1,80 @@
+/**
+ * The handbook's file list, drawn by the app's shared `FileTree` — the same tree the
+ * conversation page's Workspace panel and the plugin library's file browser draw, so a reader
+ * who knows one knows this one: the same row height and indent, the same chevrons and folder /
+ * document glyphs, the same selection treatment, the same WAI-ARIA keyboard walk with one
+ * roving tab stop, and the same subtree animation on open and close.
+ *
+ * What this file adds is the handbook's own semantics, which is all that is left once the
+ * drawing is shared: the index (`README.md`, the page every trigger makes the employee read
+ * first) leads the rows rather than sorting into them, and it is the one row whose accessible
+ * name says why — its visible text is only a file name. Beside a document's name sits how long
+ * ago it was written, beside a folder's how many documents it holds, and the whole path, the
+ * exact time and the size ride in the tooltip: a second line under one row's name would cost
+ * every row the same height for a fact about that one.
+ *
+ * The rows themselves are `handbook-tree.ts`'s (`handbookTreeRows`); folders start collapsed and
+ * the page expands the ones above the selected document.
+ */
+import type { OrgHandbookFile } from "@prismshadow/penguin-server/api";
+import { S } from "../../lib/strings";
+import { formatBytes, formatDateTime, formatRelativeShort } from "../../lib/format";
+import type { Locale } from "../../state/locale";
+import { FileTree } from "../../components/ui/file-tree";
+import type { TreeToggle } from "../../components/ui/file-tree";
+import type { HandbookRow } from "./handbook-tree";
+
+/** Collapse-all mark (lucide chevrons-down-up): two chevrons closing on each other. */
+export const COLLAPSE_ALL_ICON = "m7 20 5-5 5 5M7 4l5 5 5-5";
+
+/** How a row's tooltip spells "written then, this big"; empty for a row the listing has lost. */
+function writtenAt(file: OrgHandbookFile | null): string[] {
+ if (file === null) return [];
+ return [S.company.handbook.updatedAt(formatDateTime(file.updatedAt), formatBytes(file.size))];
+}
+
+export function HandbookExplorer({
+ rows,
+ selected,
+ locale,
+ toggled,
+ onSelect,
+ onToggle,
+}: {
+ rows: readonly HandbookRow[];
+ selected: string;
+ locale: Locale;
+ /** The folder last opened or closed, whose subtree animates. Null: nothing to animate. */
+ toggled: TreeToggle | null;
+ onSelect: (path: string) => void;
+ onToggle: (path: string) => void;
+}) {
+ const tooltip = (row: HandbookRow): string =>
+ (row.kind === "dir"
+ ? [row.path, S.company.handbook.documentsInFolder(row.docs)]
+ : [row.path, ...(row.isIndex ? [S.company.handbook.indexLabel] : []), ...writtenAt(row.file)]
+ ).join(" · ");
+
+ return (
+ <FileTree
+ rows={rows}
+ label={S.company.handbook.documents}
+ selectedPath={selected}
+ toggled={toggled}
+ rowTitle={tooltip}
+ // Only the index overrides its name: every other row says on screen everything it means.
+ rowLabel={(row) => (row.isIndex ? tooltip(row) : undefined)}
+ rowTrailing={(row) => (
+ <span className="shrink-0 text-[11px] tabular-nums text-gray-400 dark:text-gray-500">
+ {row.kind === "dir"
+ ? row.docs
+ : row.file === null
+ ? ""
+ : formatRelativeShort(row.file.updatedAt, locale)}
+ </span>
+ )}
+ onToggleDir={onToggle}
+ onOpenFile={onSelect}
+ />
+ );
+}
diff --git a/packages/web/src/features/company/handbook-page.tsx b/packages/web/src/features/company/handbook-page.tsx
new file mode 100644
index 00000000..7dc900a6
--- /dev/null
+++ b/packages/web/src/features/company/handbook-page.tsx
@@ -0,0 +1,584 @@
+/**
+ * The organization handbook — `handbook/` in the organization directory, the company's
+ * knowledge base — as two panes. Left, the app's shared file tree over the directory
+ * (handbook-explorer.tsx, the same tree the Workspace panel and the plugin browser draw): the
+ * index (`README.md`, the page every trigger makes the employee read first) leading the rows,
+ * then folders and documents nested as they are on disk, with one button that collapses them
+ * all. Right, the selected document rendered as Markdown (anything else preformatted),
+ * edited in place through a monospace textarea with save and cancel, and — for every document
+ * but the index — deleted behind the shared confirmation. The new-document dialog refuses a
+ * path the server would, starts from the selected document's own folder so a document lands
+ * beside its siblings, then creates the file with a one-line title and selects it. A relative
+ * link inside a document opens the document it names in the same pane, so the index works as
+ * the handbook's own navigation.
+ *
+ * Loading discipline: the skeleton stands only until the first listing or its failure; a
+ * failed refresh keeps the list on screen under one error line with its retry; a document
+ * that fails to load says so inside its pane with the list still usable. The selection is
+ * component state — the URL stays at the page.
+ */
+import { useCallback, useEffect, useMemo, useState } from "react";
+import type { KeyboardEvent as ReactKeyboardEvent, MouseEvent as ReactMouseEvent } from "react";
+import type { OrgHandbookFile, OrgHandbookFileResponse } from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { formatBytes, formatDateTime, formatRelativeShort } from "../../lib/format";
+import { useDocumentTitle } from "../../lib/use-document-title";
+import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
+import { useLocale } from "../../state/locale";
+import { Button } from "../../components/ui/button";
+import { ConfirmModal } from "../../components/ui/confirm-modal";
+import { EmptyState } from "../../components/ui/empty-state";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { Input, Textarea } from "../../components/ui/input";
+import { Modal } from "../../components/ui/modal";
+import { Skeleton } from "../../components/ui/skeleton";
+import type { TreeToggle } from "../../components/ui/file-tree";
+import { toastError, toastSuccess } from "../../components/ui/toast";
+import { Md } from "../chat/md";
+import { OrgEmptyLine, OrgPage, OrgSection, useOrg } from "./org-layout";
+import { ErrorLine } from "./shared";
+import { COLLAPSE_ALL_ICON, HandbookExplorer } from "./handbook-explorer";
+import {
+ HANDBOOK_INDEX,
+ ancestorFolders,
+ buildHandbookTree,
+ completeHandbookPath,
+ handbookTreeRows,
+ isHandbookPath,
+ isMarkdownPath,
+ newDocumentBody,
+ resolveHandbookLink,
+} from "./handbook-tree";
+
+/** The two panes: a fixed list column beside the document, stacked on a narrow screen. */
+const PANES_CLASS = "grid grid-cols-1 gap-x-10 gap-y-8 lg:grid-cols-[17rem_minmax(0,1fr)]";
+
+/** The size a listing row would report for content just written, before the listing is re-read. */
+const byteLength = (text: string) => new TextEncoder().encode(text).length;
+
+export function HandbookPage() {
+ const { projectId, orgId, org } = useOrg();
+ const { locale } = useLocale();
+ useDocumentTitle(org ? `${org.name} · ${S.nav.org.handbook}` : S.nav.org.handbook);
+ const [files, setFiles] = useState<OrgHandbookFile[] | null>(null);
+ const [listError, setListError] = useState<string | null>(null);
+ const [selected, setSelected] = useState(HANDBOOK_INDEX);
+ /** The open folders of the tree, by path: a folder starts closed and is opened by hand. */
+ const [expanded, setExpanded] = useState<ReadonlySet<string>>(() => new Set<string>());
+ /** The folder last opened or closed, so the tree animates that subtree and no other. */
+ const [toggled, setToggled] = useState<TreeToggle | null>(null);
+ const [doc, setDoc] = useState<OrgHandbookFileResponse | null>(null);
+ const [docError, setDocError] = useState<string | null>(null);
+ /** Bumped to re-read the selected document (its retry) without changing the selection. */
+ const [docAttempt, setDocAttempt] = useState(0);
+ const [editing, setEditing] = useState(false);
+ const [draft, setDraft] = useState("");
+ const [saving, setSaving] = useState(false);
+ const [createOpen, setCreateOpen] = useState(false);
+ const [deleteOpen, setDeleteOpen] = useState(false);
+ const [deleting, setDeleting] = useState(false);
+
+ // Another organization's handbook must not linger while this one loads.
+ useEffect(() => {
+ setFiles(null);
+ setListError(null);
+ setSelected(HANDBOOK_INDEX);
+ setExpanded(new Set<string>());
+ setToggled(null);
+ setEditing(false);
+ }, [projectId, orgId]);
+
+ const loadList = useCallback(async () => {
+ try {
+ const res = await api.listOrgHandbookFiles(projectId, orgId);
+ setFiles(res.files);
+ setListError(null);
+ } catch (e) {
+ setListError(apiErrorText(e));
+ }
+ }, [projectId, orgId]);
+ useEffect(() => {
+ void loadList();
+ }, [loadList]);
+
+ // The pane follows the selection. A response for a document the user has already left
+ // must not land in it, hence the cancellation.
+ useEffect(() => {
+ let cancelled = false;
+ setDoc(null);
+ setDocError(null);
+ setEditing(false);
+ api
+ .getOrgHandbookFile(projectId, orgId, selected)
+ .then((res) => {
+ if (cancelled) return;
+ setDoc(res);
+ setDocError(null);
+ })
+ .catch((e: unknown) => {
+ if (!cancelled) setDocError(apiErrorText(e));
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [projectId, orgId, selected, docAttempt]);
+
+ // A document that vanished from the listing (deleted elsewhere) gives way to the index.
+ useEffect(() => {
+ if (files !== null && selected !== HANDBOOK_INDEX && !files.some((f) => f.path === selected)) {
+ setSelected(HANDBOOK_INDEX);
+ }
+ }, [files, selected]);
+
+ // The selected document is always in view: whatever selects it — the first load, a link
+ // followed inside another document, a document just created — opens the folders above it.
+ // Collapsing them all afterwards is the reader's to do, and stays done.
+ useEffect(() => {
+ const parents = ancestorFolders(selected);
+ if (parents.length === 0) return;
+ setExpanded((prev) => {
+ if (parents.every((p) => prev.has(p))) return prev;
+ const next = new Set(prev);
+ for (const p of parents) next.add(p);
+ return next;
+ });
+ }, [selected]);
+
+ const toggleFolder = (path: string) => {
+ // The serial makes toggling the same folder again a new event for the tree to animate.
+ setToggled((last) => ({
+ dir: path,
+ open: !expanded.has(path),
+ serial: (last?.serial ?? 0) + 1,
+ }));
+ setExpanded((prev) => {
+ const next = new Set(prev);
+ if (!next.delete(path)) next.add(path);
+ return next;
+ });
+ };
+
+ /** A write's effect on the listing, ahead of the re-read that confirms it. */
+ const upsertFile = (file: OrgHandbookFile) =>
+ setFiles((prev) =>
+ prev === null ? [file] : [...prev.filter((f) => f.path !== file.path), file],
+ );
+
+ const startEdit = () => {
+ if (doc === null) return;
+ setDraft(doc.content);
+ setEditing(true);
+ };
+
+ const save = async () => {
+ if (doc === null || saving) return;
+ setSaving(true);
+ try {
+ const res = await api.putOrgHandbookFile(projectId, orgId, doc.path, draft);
+ setDoc(res);
+ setEditing(false);
+ upsertFile({
+ path: res.path,
+ size: byteLength(res.content),
+ updatedAt: new Date().toISOString(),
+ });
+ toastSuccess(S.common.saved);
+ void loadList();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const create = async (path: string) => {
+ const res = await api.putOrgHandbookFile(projectId, orgId, path, newDocumentBody(path));
+ upsertFile({
+ path: res.path,
+ size: byteLength(res.content),
+ updatedAt: new Date().toISOString(),
+ });
+ setCreateOpen(false);
+ setSelected(res.path);
+ toastSuccess(S.company.handbook.documentCreated);
+ void loadList();
+ };
+
+ const remove = async () => {
+ if (doc === null || deleting) return;
+ const path = doc.path;
+ setDeleting(true);
+ try {
+ await api.deleteOrgHandbookFile(projectId, orgId, path);
+ setDeleteOpen(false);
+ setFiles((prev) => (prev === null ? prev : prev.filter((f) => f.path !== path)));
+ setSelected(HANDBOOK_INDEX);
+ toastSuccess(S.company.handbook.documentDeleted);
+ void loadList();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setDeleting(false);
+ }
+ };
+
+ // A relative link inside the rendered document is another document of the handbook: it
+ // opens in this pane rather than in the new tab the Markdown renderer's links default to.
+ const onBodyClick = (e: ReactMouseEvent<HTMLDivElement>) => {
+ if (doc === null) return;
+ const anchor = (e.target as HTMLElement).closest("a");
+ if (anchor === null) return;
+ const target = resolveHandbookLink(doc.path, anchor.getAttribute("href") ?? "");
+ if (target === null) return;
+ e.preventDefault();
+ setSelected(target);
+ };
+
+ const onEditorKey = (e: ReactKeyboardEvent<HTMLTextAreaElement>) => {
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "s") {
+ e.preventDefault();
+ void save();
+ }
+ };
+
+ const tree = useMemo(() => (files === null ? null : buildHandbookTree(files)), [files]);
+ const rows = useMemo(
+ () => (tree === null ? [] : handbookTreeRows(tree, expanded)),
+ [tree, expanded],
+ );
+ const existing = useMemo(() => new Set((files ?? []).map((f) => f.path)), [files]);
+ const selectedFile = files?.find((f) => f.path === selected) ?? null;
+ const isIndex = selected === HANDBOOK_INDEX;
+ // A new document starts in the selected one's folder: that is where its siblings are.
+ const selectedFolders = ancestorFolders(selected);
+ const newDocumentFolder =
+ selectedFolders.length === 0 ? "" : `${selectedFolders[selectedFolders.length - 1]!}/`;
+
+ const title = S.nav.org.handbook;
+ const info = S.company.handbook.info;
+
+ if (tree === null) {
+ return (
+ <OrgPage title={title} info={info}>
+ {listError !== null ? (
+ <EmptyState
+ title={S.company.handbook.loadFailed}
+ description={listError}
+ action={<Button onClick={() => void loadList()}>{S.common.retry}</Button>}
+ />
+ ) : (
+ <HandbookSkeleton />
+ )}
+ </OrgPage>
+ );
+ }
+
+ return (
+ <OrgPage title={title} info={info}>
+ {listError !== null && (
+ <ErrorLine
+ message={S.company.handbook.loadFailed}
+ detail={listError}
+ onRetry={() => void loadList()}
+ className="mb-4"
+ />
+ )}
+ <div className={PANES_CLASS}>
+ {/* The create button sits in the section's action slot rather than the page's: it
+ is the list's own action, and a button in both headers keeps their rules level. */}
+ <OrgSection
+ title={S.company.handbook.documents}
+ count={files?.length ?? 0}
+ actions={
+ <>
+ <button
+ type="button"
+ title={S.company.handbook.collapseAll}
+ aria-label={S.company.handbook.collapseAll}
+ disabled={expanded.size === 0}
+ onClick={() => {
+ // Every folder at once is not one subtree shrinking: nothing to animate.
+ setToggled(null);
+ setExpanded(new Set<string>());
+ }}
+ className="inline-flex items-center justify-center rounded p-0.5 text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 disabled:opacity-40 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ >
+ <GlyphIcon d={COLLAPSE_ALL_ICON} size={ICON_SIZE.groupHeaderAction} />
+ </button>
+ <Button size="sm" onClick={() => setCreateOpen(true)}>
+ {S.company.handbook.newDocument}
+ </Button>
+ </>
+ }
+ >
+ <HandbookExplorer
+ rows={rows}
+ selected={selected}
+ locale={locale}
+ toggled={toggled}
+ onSelect={setSelected}
+ onToggle={toggleFolder}
+ />
+ {tree.nodes.length === 0 && (
+ <OrgEmptyLine>{S.company.handbook.noOtherDocuments}</OrgEmptyLine>
+ )}
+ </OrgSection>
+
+ <section className="min-w-0" aria-label={selected}>
+ {/* The document's own header: its path (a file name, not a heading, so no
+ uppercase), the index mark, when it was written, and the pane's controls. */}
+ <div className="mb-3 flex flex-wrap items-center justify-between gap-x-3 gap-y-2 border-b border-gray-200 pb-2 dark:border-gray-800">
+ <div className={`flex min-w-0 items-center ${ICON_GAP.row}`}>
+ <span className="truncate font-mono text-xs font-semibold text-gray-700 dark:text-gray-200">
+ {selected}
+ </span>
+ {/* The one place the index's reason for being pinned is on screen — it says what
+ the document open in this pane is, so it belongs to the document, not to a row
+ in a list of them. The explorer row carries the same sentence in its tooltip
+ and its accessible name. */}
+ {isIndex && (
+ <span className="shrink-0 rounded-full bg-gray-100 px-1.5 text-[10px] font-semibold text-gray-500 dark:bg-gray-800 dark:text-gray-400">
+ {S.company.handbook.indexLabel}
+ </span>
+ )}
+ {selectedFile !== null && (
+ <span
+ className="hidden shrink-0 text-[11px] text-gray-400 sm:inline dark:text-gray-500"
+ title={S.company.handbook.updatedAt(
+ formatDateTime(selectedFile.updatedAt),
+ formatBytes(selectedFile.size),
+ )}
+ >
+ {formatRelativeShort(selectedFile.updatedAt, locale)}
+ </span>
+ )}
+ </div>
+ <div className="flex shrink-0 items-center gap-1.5">
+ {editing ? (
+ <>
+ <span className="hidden text-[11px] text-gray-400 sm:inline dark:text-gray-500">
+ {S.company.handbook.editorHint}
+ </span>
+ <Button size="sm" disabled={saving} onClick={() => setEditing(false)}>
+ {S.common.cancel}
+ </Button>
+ <Button size="sm" variant="primary" disabled={saving} onClick={() => void save()}>
+ {saving ? S.common.saving : S.common.save}
+ </Button>
+ </>
+ ) : (
+ <>
+ <Button size="sm" disabled={doc === null} onClick={startEdit}>
+ {S.common.edit}
+ </Button>
+ {!isIndex && (
+ <Button
+ size="sm"
+ variant="danger"
+ disabled={doc === null}
+ onClick={() => setDeleteOpen(true)}
+ >
+ {S.common.delete}
+ </Button>
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ {docError !== null ? (
+ <EmptyState
+ title={S.company.handbook.documentLoadFailed}
+ description={docError}
+ action={<Button onClick={() => setDocAttempt((n) => n + 1)}>{S.common.retry}</Button>}
+ />
+ ) : doc === null ? (
+ <DocumentSkeleton />
+ ) : editing ? (
+ <Textarea
+ mono
+ size="sm"
+ aria-label={selected}
+ value={draft}
+ rows={24}
+ spellCheck={false}
+ autoFocus
+ disabled={saving}
+ className="min-h-[50vh]"
+ onChange={(e) => setDraft(e.target.value)}
+ onKeyDown={onEditorKey}
+ />
+ ) : doc.content.trim() === "" ? (
+ <OrgEmptyLine>{S.company.handbook.emptyDocument}</OrgEmptyLine>
+ ) : isMarkdownPath(doc.path) ? (
+ <div
+ className="md-body text-sm leading-relaxed text-gray-800 dark:text-gray-100"
+ onClick={onBodyClick}
+ >
+ <Md text={doc.content} />
+ </div>
+ ) : (
+ <pre className="overflow-x-auto whitespace-pre-wrap rounded-md border border-gray-200 bg-gray-50 p-3 font-mono text-xs leading-relaxed text-gray-800 dark:border-gray-800 dark:bg-gray-900 dark:text-gray-200">
+ {doc.content}
+ </pre>
+ )}
+ </section>
+ </div>
+
+ <NewDocumentDialog
+ open={createOpen}
+ folder={newDocumentFolder}
+ existing={existing}
+ onClose={() => setCreateOpen(false)}
+ onCreate={create}
+ />
+ <ConfirmModal
+ open={deleteOpen}
+ title={S.company.handbook.deleteDocument}
+ confirmLabel={S.common.delete}
+ busy={deleting}
+ onClose={() => (deleting ? undefined : setDeleteOpen(false))}
+ onConfirm={() => void remove()}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {S.company.handbook.deleteConfirm(selected)}
+ </p>
+ </ConfirmModal>
+ </OrgPage>
+ );
+}
+
+/**
+ * The new-document dialog: one path field, checked here before the request — the server's
+ * own rule, a name already taken — so the failure lands under the field; anything the server
+ * still refuses lands in a strip above the footer with its retry.
+ */
+function NewDocumentDialog({
+ open,
+ folder,
+ existing,
+ onClose,
+ onCreate,
+}: {
+ open: boolean;
+ /** What the field starts with: the selected document's folder as a `<folder>/` prefix, or "". */
+ folder: string;
+ /** Every path the listing holds, so a duplicate is refused before it overwrites. */
+ existing: ReadonlySet<string>;
+ onClose: () => void;
+ /** Creates the file; a rejection is shown in the dialog. */
+ onCreate: (path: string) => Promise<void>;
+}) {
+ const [path, setPath] = useState("");
+ const [pathError, setPathError] = useState<string | undefined>(undefined);
+ const [formError, setFormError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+
+ // No draft is kept: the field starts from the selected document's folder every time the
+ // dialog opens, so a document lands beside its siblings unless the path is typed over.
+ useEffect(() => {
+ if (!open) return;
+ setPath(folder);
+ setPathError(undefined);
+ setFormError(null);
+ }, [open, folder]);
+
+ const submit = async () => {
+ const rel = completeHandbookPath(path);
+ // A path that is only a folder names no document: the field starts as one, and completing
+ // `decisions/` to `decisions.md` would create a file beside the folder rather than in it.
+ if (rel === "" || path.trim().endsWith("/")) {
+ setPathError(S.common.requiredField);
+ return;
+ }
+ if (!isHandbookPath(rel)) {
+ setPathError(S.company.handbook.pathInvalid);
+ return;
+ }
+ if (existing.has(rel)) {
+ setPathError(S.company.handbook.pathExists);
+ return;
+ }
+ setBusy(true);
+ setFormError(null);
+ try {
+ await onCreate(rel);
+ } catch (e) {
+ setFormError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <Modal
+ open={open}
+ title={S.company.handbook.newDocument}
+ onClose={busy ? () => undefined : onClose}
+ footer={
+ <>
+ <Button size="sm" onClick={onClose} disabled={busy}>
+ {S.common.cancel}
+ </Button>
+ <Button size="sm" variant="primary" disabled={busy} onClick={() => void submit()}>
+ {busy ? S.company.handbook.creating : S.common.create}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ <Input
+ label={S.company.handbook.pathField}
+ required
+ size="sm"
+ value={path}
+ error={pathError}
+ hint={S.company.handbook.pathHint}
+ placeholder={S.company.handbook.pathPlaceholder}
+ className="font-mono"
+ autoFocus
+ disabled={busy}
+ onChange={(e) => {
+ setPath(e.target.value);
+ setPathError(undefined);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ void submit();
+ }
+ }}
+ />
+ {formError !== null && <ErrorLine message={formError} onRetry={() => void submit()} />}
+ </div>
+ </Modal>
+ );
+}
+
+/** The two panes as placeholder bands, until the first listing arrives. */
+function HandbookSkeleton() {
+ return (
+ <div className={PANES_CLASS} aria-busy="true">
+ <div className="space-y-2">
+ <Skeleton className="h-3 w-16" />
+ {[0, 1, 2, 3, 4].map((i) => (
+ <Skeleton key={i} className="h-8" />
+ ))}
+ </div>
+ <DocumentSkeleton />
+ </div>
+ );
+}
+
+/** The document pane's placeholder: a title band over three lines. */
+function DocumentSkeleton() {
+ return (
+ <div className="space-y-3" aria-busy="true">
+ <Skeleton className="h-6 w-2/3" />
+ <Skeleton className="h-4" />
+ <Skeleton className="h-4 w-5/6" />
+ <Skeleton className="h-4 w-3/4" />
+ </div>
+ );
+}
diff --git a/packages/web/src/features/company/handbook-tree.ts b/packages/web/src/features/company/handbook-tree.ts
new file mode 100644
index 00000000..ae371f3d
--- /dev/null
+++ b/packages/web/src/features/company/handbook-tree.ts
@@ -0,0 +1,236 @@
+/**
+ * The handbook page's pure model (unit tested): the file listing shaped into the pinned index
+ * and an explorer tree of folders and documents, then flattened into the shared file tree's
+ * rows (`lib/file-tree.ts`) for an expanded set — the index leading, a collapsed folder
+ * contributing one row and no children — plus the folders above a document and how many
+ * documents a subtree holds; the path rule the server enforces, mirrored so the new-document
+ * dialog refuses a bad path before the request; the body a new document starts with; and how a
+ * relative link inside one document resolves to another document of the handbook.
+ */
+import type { OrgHandbookFile } from "@prismshadow/penguin-server/api";
+import type { FileTreeRow } from "../../lib/file-tree";
+
+/** The index, `handbook/README.md`: pinned first in the list, and the one file that cannot be deleted. */
+export const HANDBOOK_INDEX = "README.md";
+
+/**
+ * The server's rule for a path inside `handbook/`: plain `/`-separated segments, each starting
+ * with a letter or digit and made of letters, digits, `.`, `_` and `-` (so no hidden files and
+ * no `.` / `..`), at most eight levels deep.
+ */
+export const HANDBOOK_PATH_PATTERN =
+ /^(?:[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/){0,7}[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
+
+export function isHandbookPath(rel: string): boolean {
+ return HANDBOOK_PATH_PATTERN.test(rel);
+}
+
+/**
+ * What the dialog sends for what was typed: surrounding whitespace, a leading `/` or `./` and
+ * a trailing `/` dropped, `.md` appended when the file name carries no extension. Whether the
+ * result is a handbook path is the caller's check (isHandbookPath).
+ */
+export function completeHandbookPath(input: string): string {
+ let rel = input
+ .trim()
+ .replace(/^(?:\.\/|\/)+/, "")
+ .replace(/\/+$/, "");
+ if (rel !== "" && !fileName(rel).includes(".")) rel += ".md";
+ return rel;
+}
+
+/** The last segment of a path. */
+export function fileName(path: string): string {
+ return path.slice(path.lastIndexOf("/") + 1);
+}
+
+/** Whether the page renders the file as Markdown; anything else shows as preformatted text. */
+export function isMarkdownPath(path: string): boolean {
+ return /\.(?:md|markdown)$/i.test(path);
+}
+
+/** The one-line body a new document starts with: a title made of its file name without the extension. */
+export function newDocumentBody(path: string): string {
+ return `# ${fileName(path).replace(/\.[^.]+$/, "")}\n`;
+}
+
+/** One row of the explorer: a folder holding more rows, or a document of the listing. */
+export type HandbookNode =
+ | { kind: "folder"; name: string; path: string; children: HandbookNode[] }
+ | { kind: "file"; name: string; path: string; file: OrgHandbookFile };
+
+export interface HandbookTree {
+ /** The index, or null when the listing lacks it (a handbook directory someone emptied by hand). */
+ index: OrgHandbookFile | null;
+ /** Everything else, nested: folders before files at every level. */
+ nodes: HandbookNode[];
+}
+
+/**
+ * Two names of one level, ordered the way a file explorer orders them: case-insensitively,
+ * with case deciding only a tie, so `Brand.md` sits beside `brand.md` rather than above every
+ * lowercase name. Locale-independent on purpose — the same listing must order the same way
+ * whichever language the app is in.
+ */
+function byName(a: string, b: string): number {
+ const la = a.toLowerCase();
+ const lb = b.toLowerCase();
+ if (la !== lb) return la < lb ? -1 : 1;
+ return a < b ? -1 : a > b ? 1 : 0;
+}
+
+/** A folder while the tree is being built: its subfolders by name, and the documents directly in it. */
+interface Level {
+ folders: Map<string, Level>;
+ files: OrgHandbookFile[];
+}
+
+function levelNodes(level: Level, prefix: string): HandbookNode[] {
+ const folders: HandbookNode[] = [...level.folders.entries()]
+ .sort(([a], [b]) => byName(a, b))
+ .map(([name, child]) => ({
+ kind: "folder",
+ name,
+ path: `${prefix}${name}`,
+ children: levelNodes(child, `${prefix}${name}/`),
+ }));
+ const files: HandbookNode[] = level.files
+ .map((file) => ({ kind: "file" as const, name: fileName(file.path), path: file.path, file }))
+ .sort((a, b) => byName(a.name, b.name));
+ return [...folders, ...files];
+}
+
+/**
+ * The listing as the explorer draws it: the index apart, everything else nested by its path,
+ * folders before files at every level. The listing's own order does not matter.
+ */
+export function buildHandbookTree(files: readonly OrgHandbookFile[]): HandbookTree {
+ const index = files.find((f) => f.path === HANDBOOK_INDEX) ?? null;
+ const root: Level = { folders: new Map(), files: [] };
+ for (const file of files) {
+ if (file.path === HANDBOOK_INDEX) continue;
+ const segments = file.path.split("/");
+ let level = root;
+ for (const name of segments.slice(0, -1)) {
+ let child = level.folders.get(name);
+ if (child === undefined) {
+ child = { folders: new Map(), files: [] };
+ level.folders.set(name, child);
+ }
+ level = child;
+ }
+ level.files.push(file);
+ }
+ return { index, nodes: levelNodes(root, "") };
+}
+
+/** The folder paths above a document, root first: `a/b/c.md` sits under `a` and then `a/b`. */
+export function ancestorFolders(path: string): string[] {
+ const segments = path.split("/");
+ const out: string[] = [];
+ for (let i = 1; i < segments.length; i += 1) out.push(segments.slice(0, i).join("/"));
+ return out;
+}
+
+/** One rendered row: a shared file-tree row plus what the handbook shows beside a name. */
+export interface HandbookRow extends FileTreeRow {
+ /** The listing entry a document row stands for; null on a folder row. */
+ file: OrgHandbookFile | null;
+ /** Documents in a folder's subtree, however deep; 0 on a document row. */
+ docs: number;
+ /** The pinned index, which belongs to no folder and leads the list. */
+ isIndex: boolean;
+}
+
+/**
+ * The rows the explorer draws, top to bottom: the index first — it is the page every trigger
+ * makes the employee read, so it leads the top level rather than sorting into it — then a
+ * depth-first walk into every expanded folder. A collapsed folder is one row and its children
+ * are none, which is what lets a deep handbook cost nothing to render while it is closed.
+ *
+ * Nothing here is fetched per folder: the whole listing arrived in one response, so every
+ * folder row is loaded.
+ */
+export function handbookTreeRows(tree: HandbookTree, expanded: ReadonlySet<string>): HandbookRow[] {
+ const rows: HandbookRow[] = [];
+ // The index shares the top level with the first folders and documents, so it counts in that
+ // level's set: a flat run of treeitems has to state its own position and size.
+ const topSize = tree.nodes.length + (tree.index === null ? 0 : 1);
+ if (tree.index !== null) {
+ rows.push({
+ path: HANDBOOK_INDEX,
+ name: HANDBOOK_INDEX,
+ kind: "file",
+ depth: 0,
+ posInSet: 1,
+ setSize: topSize,
+ expanded: false,
+ loaded: true,
+ empty: false,
+ file: tree.index,
+ docs: 0,
+ isIndex: true,
+ });
+ }
+ const walk = (nodes: readonly HandbookNode[], depth: number, offset: number): void => {
+ for (const [index, node] of nodes.entries()) {
+ const open = node.kind === "folder" && expanded.has(node.path);
+ rows.push({
+ path: node.path,
+ name: node.name,
+ kind: node.kind === "folder" ? "dir" : "file",
+ depth,
+ posInSet: offset + index + 1,
+ setSize: depth === 0 ? topSize : nodes.length,
+ expanded: open,
+ loaded: true,
+ empty: node.kind === "folder" && node.children.length === 0,
+ file: node.kind === "file" ? node.file : null,
+ docs: node.kind === "folder" ? countDocuments(node.children) : 0,
+ isIndex: false,
+ });
+ if (open && node.kind === "folder") walk(node.children, depth + 1, 0);
+ }
+ };
+ walk(tree.nodes, 0, tree.index === null ? 0 : 1);
+ return rows;
+}
+
+/** How many documents a set of nodes holds, however deep — what a folder row counts. */
+export function countDocuments(nodes: readonly HandbookNode[]): number {
+ let n = 0;
+ for (const node of nodes) n += node.kind === "file" ? 1 : countDocuments(node.children);
+ return n;
+}
+
+/**
+ * Where a relative link inside a document points: another document of the handbook, as its
+ * handbook path — or null for anything that is not one (an absolute URL, a bare `#anchor`, a
+ * path that climbs out of `handbook/`). Resolved against the linking document's folder the way
+ * a browser would, a leading `/` meaning the handbook's root; a `#fragment` or `?query` on the
+ * target is dropped.
+ */
+export function resolveHandbookLink(from: string, href: string): string | null {
+ if (href === "" || href.startsWith("#") || href.startsWith("//")) return null;
+ if (/^[a-z][a-z0-9+.-]*:/i.test(href)) return null;
+ let target = href.replace(/[?#].*$/, "");
+ try {
+ target = decodeURIComponent(target);
+ } catch {
+ return null;
+ }
+ if (target === "") return null;
+ const base = from.includes("/") ? from.slice(0, from.lastIndexOf("/")).split("/") : [];
+ const out = target.startsWith("/") ? [] : [...base];
+ for (const segment of target.split("/")) {
+ if (segment === "" || segment === ".") continue;
+ if (segment === "..") {
+ if (out.length === 0) return null;
+ out.pop();
+ continue;
+ }
+ out.push(segment);
+ }
+ const rel = out.join("/");
+ return isHandbookPath(rel) ? rel : null;
+}
diff --git a/packages/web/src/features/company/id-suggest-notice.ts b/packages/web/src/features/company/id-suggest-notice.ts
new file mode 100644
index 00000000..47c71847
--- /dev/null
+++ b/packages/web/src/features/company/id-suggest-notice.ts
@@ -0,0 +1,38 @@
+/**
+ * What the id field says about the id a proposal just handed it (pure, unit tested).
+ *
+ * `POST /organizations/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
+ * gets an attention-toned one: it names nothing, it says why the two real paths produced
+ * nothing, and it asks to be replaced before the dialog is submitted.
+ *
+ * A `reason` this build does not know (a newer server) still renders a sentence — the note is
+ * how the user learns the id in the box is a placeholder, and losing it over an unrecognized
+ * code would be the worse failure.
+ */
+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"];
+
+/** A line under the field, with the tone it is drawn in; null when the id speaks for itself. */
+export interface IdSuggestNotice {
+ tone: "attention" | "muted";
+ text: string;
+}
+
+export function idSuggestNotice(
+ res: SemanticIdSuggestResponse,
+ s: IdSuggestStrings,
+): IdSuggestNotice | null {
+ if (res.source === "placeholder") {
+ const known: Record<string, string> = s.reasons;
+ const why = (res.reason !== undefined ? known[res.reason] : undefined) ?? s.reasonUnknown;
+ return { tone: "attention", text: s.placeholder(why) };
+ }
+ if (res.source === "fallback") return { tone: "muted", text: s.fromName };
+ return null;
+}
diff --git a/packages/web/src/features/company/org-chart-page.tsx b/packages/web/src/features/company/org-chart-page.tsx
new file mode 100644
index 00000000..ea0f44ef
--- /dev/null
+++ b/packages/web/src/features/company/org-chart-page.tsx
@@ -0,0 +1,611 @@
+/**
+ * The org chart: the reporting line as a top-down tree with the CEO at the top centre
+ * (layout in org-chart-tree.ts), each node an employee card (chart-card.tsx). The card has
+ * one menu and no other action: it opens the desk session, and holds the personnel actions
+ * below that — hire a subordinate, set budget, change the reporting line, renew the desk (a
+ * fresh desk session, and the workspace it runs in), leave. Every one of the personnel actions
+ * confirms before it writes the chart file. The card owns when that menu is open (three
+ * gestures reach it — see chart-card.tsx); this page only supplies the rows, against the
+ * panel's own close, and bumps `viewEpoch` whenever the canvas moves the cards out from under
+ * an open one.
+ *
+ * A card's state dot is NOT the chart's own `state`: that snapshot is re-read on organization
+ * events, and a run ending publishes none of them, so an employee that finished would keep its
+ * running dot until something unrelated moved. The dots read the session list's live statuses
+ * instead (org-sessions.ts, liveEmployeeStates), falling back to the snapshot per employee.
+ *
+ * The drawing is a canvas, not a page section: the frame fills what is left of the window and
+ * clips, and the whole tree is one absolutely positioned layer placed by a single transform,
+ * so panning and zooming never re-layout a card. It opens fitted — the whole tree visible and
+ * centred — and from there the wheel zooms around the cursor, a drag anywhere that is not a
+ * control pans, and the header's − / + step around the frame's centre while the percent
+ * readout goes back to the fit. The fit is re-taken as the drawing or the frame changes size
+ * (a hire widens the tree, a sidebar collapse widens the frame) until the reader moves the
+ * view themselves; from then on it is theirs, and only the percent button gives it back.
+ * The arithmetic is in canvas-view.ts.
+ */
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import type { KeyboardEvent as ReactKeyboardEvent } from "react";
+import { useNavigate } from "react-router";
+import type { OrgChartResponse, OrgEmployeeItem } from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { useDocumentTitle } from "../../lib/use-document-title";
+import { ICON_SIZE } from "../../lib/icon-scale";
+import { toneInk, toneStrip } from "../../lib/tone";
+import { useCompany } from "../../state/company";
+import { useLiveSessionStatuses } from "../../state/sessions";
+import { useTheme } from "../../state/theme";
+import { Button } from "../../components/ui/button";
+import { ConfirmModal } from "../../components/ui/confirm-modal";
+import { EmptyState } from "../../components/ui/empty-state";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { toastError, toastSuccess } from "../../components/ui/toast";
+import {
+ overflowMenuDangerClass,
+ overflowMenuGlyph,
+ overflowMenuRowClass,
+} from "../../components/ui/session-row-menu";
+import { usePointerDrag } from "../dock/use-pointer-drag";
+import { OrgPage, OrgPageSkeleton, useOrg } from "./org-layout";
+import { orgKey } from "./company-nav";
+import { liveEmployeeStates } from "./org-sessions";
+import { DESK_ICON } from "./channel-header";
+import { CHART_DETACHED_LABEL_H, layoutOrgTree } from "./org-chart-tree";
+import {
+ ZOOM_MAX,
+ ZOOM_MIN,
+ ZOOM_STEP,
+ clampView,
+ fitView,
+ panBy,
+ viewTransform,
+ wheelZoomFactor,
+ zoomAt,
+} from "./canvas-view";
+import type { CanvasSize, CanvasView } from "./canvas-view";
+import { ChartCard, ChartLegend } from "./chart-card";
+import { DeskRenewDialog, EmployeeEditDialog, HireDialog } from "./employee-dialogs";
+import type { EmployeeEdit } from "./employee-dialogs";
+
+/** Node-menu glyphs (24x24 line paths): the open door of a desk session, a plus person for hiring, a coin for budget, an arrow for the line, a refresh for a fresh desk, a door out for leaving. */
+const MENU_ICONS = {
+ openDesk: DESK_ICON,
+ hire: "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM19 8v6M22 11h-6",
+ budget: "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8M12 18V6",
+ reportsTo: "M4 17V7l4 4 4-4v10M16 7h4v4m0-4-6 6",
+ renewDesk: "M21 12a9 9 0 1 1-3-6.7M21 3v6h-6",
+ leave: "M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9",
+} as const;
+
+/** The header's zoom buttons (24x24 line paths): a minus and a plus. */
+const ZOOM_ICONS = { out: "M5 12h14", in: "M12 5v14M5 12h14" } as const;
+
+/** The canvas never collapses below this, however little of the window the rows above it leave. */
+const CANVAS_MIN_H = 240;
+/** One arrow-key press, in frame pixels: the canvas has to be navigable without a pointer. */
+const CANVAS_KEY_PAN = 48;
+
+/**
+ * A press that landed on a control is that control's own: the cards' kebabs must open their
+ * menu rather than start a pan, and a press inside an open menu belongs to the menu.
+ */
+function isInteractive(target: EventTarget | null): boolean {
+ return target instanceof Element && target.closest("button, a, input, select, textarea") !== null;
+}
+
+/**
+ * The lowest edge the canvas may reach: the inside of the scrolling column the page sits in,
+ * its bottom padding kept. Measured rather than written as a `calc()` — what stands between
+ * the window's top and the canvas is a title row plus however many notices the chart has
+ * raised, which is not a height CSS can know. The window's edge is the fallback when the walk
+ * finds no scroller, which only leaves the canvas one padding too tall.
+ */
+function columnBottom(el: HTMLElement): number {
+ for (let node = el.parentElement; node !== null; node = node.parentElement) {
+ const style = getComputedStyle(node);
+ if (style.overflowY === "auto" || style.overflowY === "scroll") {
+ return node.getBoundingClientRect().bottom - (parseFloat(style.paddingBottom) || 0);
+ }
+ }
+ return window.innerHeight;
+}
+
+export function OrgChartPage() {
+ const { projectId, orgId, org } = useOrg();
+ const navigate = useNavigate();
+ const company = useCompany();
+ const { currency } = useTheme();
+ useDocumentTitle(org ? `${org.name} · ${S.nav.org.chart}` : S.nav.org.chart);
+ const [chart, setChart] = useState<OrgChartResponse | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [hireFor, setHireFor] = useState<OrgEmployeeItem | null>(null);
+ const [editFor, setEditFor] = useState<{ employee: OrgEmployeeItem; edit: EmployeeEdit } | null>(
+ null,
+ );
+ const [renewFor, setRenewFor] = useState<OrgEmployeeItem | null>(null);
+ const [leaveFor, setLeaveFor] = useState<OrgEmployeeItem | null>(null);
+ const [busy, setBusy] = useState(false);
+ /** The view the reader moved to; null follows the fit, which is what the chart opens at. */
+ const [view, setView] = useState<CanvasView | null>(null);
+ /**
+ * Bumped by every move of the view. A card's menu is anchored at a viewport point, and a
+ * pan or a zoom slides the card out from under it — neither a scroll nor a resize, so the
+ * panel cannot notice on its own; the cards close theirs when this moves.
+ */
+ const [viewEpoch, setViewEpoch] = useState(0);
+ const [frame, setFrame] = useState<CanvasSize>({ width: 0, height: 0 });
+ const [panning, setPanning] = useState(false);
+ /** The canvas frame, held as state rather than in a ref: it mounts only once the chart has arrived, and the listeners below attach to it. */
+ const [frameEl, setFrameEl] = useState<HTMLDivElement | null>(null);
+
+ const load = useCallback(async () => {
+ try {
+ setChart(await api.getOrgChart(projectId, orgId));
+ setError(null);
+ } catch (e) {
+ setError(apiErrorText(e));
+ }
+ }, [projectId, orgId]);
+ // A run starting moves a state dot, a ticket change can attach a session to an employee, and
+ // a budget event pauses one: reload on those, never on a timer. A run ENDING publishes
+ // nothing at all, which is why the dots are drawn from the live statuses below rather than
+ // from the state this response carries.
+ const { runs, tickets, budget } = company.versions;
+ useEffect(() => {
+ void load();
+ }, [load, runs, tickets, budget]);
+
+ const layout = useMemo(
+ () => (chart === null ? null : layoutOrgTree(chart.employees, chart.ceoAgentId)),
+ [chart],
+ );
+
+ // The dots' states: the live session list first, the chart's own state for an employee whose
+ // Sessions that list has not loaded. The ticket sessions come from the organization's own
+ // snapshot, which is the only listing that says which employee is working which ticket.
+ const liveStatuses = useLiveSessionStatuses();
+ const orgSessions = company.orgSessions.get(orgKey(projectId, orgId));
+ const employeeStates = useMemo(
+ () => liveEmployeeStates(chart?.employees ?? [], orgSessions, liveStatuses),
+ [chart, orgSessions, liveStatuses],
+ );
+ const drawing = useMemo<CanvasSize>(
+ () => ({ width: layout?.width ?? 0, height: layout?.height ?? 0 }),
+ [layout],
+ );
+ const fit = useMemo(() => fitView(frame, drawing), [frame, drawing]);
+ const current = view ?? fit;
+ const percent = Math.round(current.scale * 100);
+
+ // The wheel listener and the pan gesture outlive the render that created them, so they read
+ // the view and the two boxes it is clamped against from here rather than from their closure.
+ const live = useRef({ view: current, frame, drawing });
+ live.current = { view: current, frame, drawing };
+
+ /** Every move of the view goes through here, so none of them can push the drawing off the frame. */
+ const applyView = useCallback((next: CanvasView) => {
+ setViewEpoch((n) => n + 1);
+ setView(clampView(next, live.current.frame, live.current.drawing));
+ }, []);
+
+ /** −/+ and their keys step around the frame's centre: what the reader is looking at is what stays put. */
+ const zoomStep = useCallback(
+ (direction: 1 | -1) => {
+ const { view: from, frame: box } = live.current;
+ const centre = { x: box.width / 2, y: box.height / 2 };
+ applyView(zoomAt(from, centre, direction === 1 ? ZOOM_STEP : 1 / ZOOM_STEP));
+ },
+ [applyView],
+ );
+
+ // The canvas fills the rest of the scrolling column, which has to be measured: see
+ // columnBottom. Re-measured after every render as well as on a resize, because the notices
+ // above the canvas come and go and each one moves its top edge without changing its own box,
+ // which is a move no ResizeObserver reports.
+ const measure = useCallback(() => {
+ if (frameEl === null) return;
+ const rect = frameEl.getBoundingClientRect();
+ const height = Math.max(CANVAS_MIN_H, columnBottom(frameEl) - rect.top);
+ setFrame((prev) =>
+ Math.abs(prev.width - rect.width) < 0.5 && Math.abs(prev.height - height) < 0.5
+ ? prev
+ : { width: rect.width, height },
+ );
+ }, [frameEl]);
+ useLayoutEffect(measure);
+ useEffect(() => {
+ if (frameEl === null) return;
+ window.addEventListener("resize", measure);
+ const ro = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => measure());
+ ro?.observe(frameEl);
+ return () => {
+ window.removeEventListener("resize", measure);
+ ro?.disconnect();
+ };
+ }, [frameEl, measure]);
+
+ // Wheel zooms around the cursor, and a trackpad pinch — which arrives as a ctrl+wheel —
+ // needs no branch of its own. A native listener registered non-passive: React's synthetic
+ // onWheel is passive, so a preventDefault there cannot stop the column scrolling instead.
+ useEffect(() => {
+ if (frameEl === null) return;
+ const onWheel = (event: WheelEvent) => {
+ event.preventDefault();
+ // clientLeft/clientTop take the frame's border off: the drawing layer is placed from the
+ // inside of that border, and an anchor a border's width out drifts as the wheel repeats.
+ const rect = frameEl.getBoundingClientRect();
+ const pointer = {
+ x: event.clientX - rect.left - frameEl.clientLeft,
+ y: event.clientY - rect.top - frameEl.clientTop,
+ };
+ applyView(zoomAt(live.current.view, pointer, wheelZoomFactor(event.deltaY, event.deltaMode)));
+ };
+ frameEl.addEventListener("wheel", onWheel, { passive: false });
+ return () => frameEl.removeEventListener("wheel", onWheel);
+ }, [frameEl, applyView]);
+
+ // Drag pans, from anywhere on the canvas that is not a control — the cards are inert, so
+ // grabbing one is grabbing the canvas under it. Pointer capture, so a fast pull that leaves
+ // the frame (or the window) keeps panning and still ends cleanly.
+ const panDrag = usePointerDrag<{ x: number; y: number; view: CanvasView }>({
+ threshold: 0,
+ begin: (event) => {
+ if (isInteractive(event.target)) return null;
+ // The keyboard shortcuts act on the focused canvas, and a click is how a pointer user
+ // gets there; Safari does not focus a tabindex'd div on its own.
+ event.currentTarget.focus();
+ setPanning(true);
+ return { x: event.clientX, y: event.clientY, view: live.current.view };
+ },
+ onMove: (event, start) =>
+ applyView(panBy(start.view, event.clientX - start.x, event.clientY - start.y)),
+ onEnd: () => setPanning(false),
+ onCancel: () => setPanning(false),
+ });
+
+ /** The canvas's own keys: zoom in, out, back to fit, and the arrows for a pan without a pointer. */
+ const onCanvasKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
+ // A key pressed on a card's kebab is the menu's business, not the canvas's.
+ if (event.target !== event.currentTarget) return;
+ const from = live.current.view;
+ switch (event.key) {
+ case "+":
+ case "=":
+ zoomStep(1);
+ break;
+ case "-":
+ case "_":
+ zoomStep(-1);
+ break;
+ case "0":
+ setViewEpoch((n) => n + 1);
+ setView(null);
+ break;
+ case "ArrowLeft":
+ applyView(panBy(from, CANVAS_KEY_PAN, 0));
+ break;
+ case "ArrowRight":
+ applyView(panBy(from, -CANVAS_KEY_PAN, 0));
+ break;
+ case "ArrowUp":
+ applyView(panBy(from, 0, CANVAS_KEY_PAN));
+ break;
+ case "ArrowDown":
+ applyView(panBy(from, 0, -CANVAS_KEY_PAN));
+ break;
+ default:
+ return;
+ }
+ event.preventDefault();
+ };
+
+ const openDesk = async (employee: OrgEmployeeItem) => {
+ try {
+ const desk = await api.getOrgDesk(projectId, orgId, employee.agentId);
+ // The call may have CREATED the desk: the sidebar's 工位 group has to learn its
+ // Session id, or it cannot mark the row the shell is about to be on.
+ if (desk.created) {
+ void company.reloadOrgChart();
+ void company.reloadOrgSessions();
+ }
+ navigate(`/chat/${desk.sessionId}`);
+ } catch (e) {
+ toastError(apiErrorText(e));
+ }
+ };
+
+ const runLeave = async () => {
+ if (leaveFor === null) return;
+ setBusy(true);
+ try {
+ await api.leaveOrganization(projectId, orgId, leaveFor.agentId);
+ toastSuccess(S.company.chart.left(leaveFor.name));
+ setLeaveFor(null);
+ void load();
+ void company.reloadOrganizations();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ if (error !== null && chart === null) {
+ return (
+ <OrgPage title={S.nav.org.chart} info={S.company.chart.info}>
+ <EmptyState
+ title={error}
+ action={<Button onClick={() => void load()}>{S.common.retry}</Button>}
+ />
+ </OrgPage>
+ );
+ }
+ if (chart === null || layout === null) {
+ return (
+ <OrgPage title={S.nav.org.chart} info={S.company.chart.info}>
+ <OrgPageSkeleton />
+ </OrgPage>
+ );
+ }
+
+ const byId = new Map(chart.employees.map((e) => [e.agentId, e]));
+
+ const menuRow = (
+ close: () => void,
+ icon: string,
+ label: string,
+ onClick: () => void,
+ danger = false,
+ disabled = false,
+ ) => (
+ <button
+ type="button"
+ className={danger ? overflowMenuDangerClass : overflowMenuRowClass}
+ disabled={disabled}
+ onClick={() => {
+ close();
+ onClick();
+ }}
+ >
+ {danger ? (
+ <span className="shrink-0">
+ <GlyphIcon d={icon} size={ICON_SIZE.inlineGlyph} />
+ </span>
+ ) : (
+ overflowMenuGlyph(icon)
+ )}
+ {label}
+ </button>
+ );
+
+ /* Opening the desk sits first and apart: it is where the reader goes, while everything
+ below it rewrites the chart file. `close` is the card's own panel dismissal — the card
+ owns the menu, since only it sees the gesture that opened one. */
+ const nodeMenu = (employee: OrgEmployeeItem, isCeo: boolean, close: () => void) => (
+ <>
+ {menuRow(close, MENU_ICONS.openDesk, S.company.openDesk, () => void openDesk(employee))}
+ <div className="my-1 border-t border-gray-100 dark:border-gray-800" />
+ {menuRow(close, MENU_ICONS.hire, S.company.chart.hire, () => setHireFor(employee))}
+ {menuRow(close, MENU_ICONS.budget, S.company.chart.setBudget, () =>
+ setEditFor({ employee, edit: "budget" }),
+ )}
+ {!isCeo &&
+ menuRow(close, MENU_ICONS.reportsTo, S.company.chart.changeReportsTo, () =>
+ setEditFor({ employee, edit: "reportsTo" }),
+ )}
+ {menuRow(close, MENU_ICONS.renewDesk, S.company.chart.renewDesk, () => setRenewFor(employee))}
+ <div className="my-1 border-t border-gray-100 dark:border-gray-800" />
+ {isCeo ? (
+ <span className="block px-2.5 py-1.5 text-xs text-gray-400 dark:text-gray-500">
+ {S.company.chart.ceoCannotLeave}
+ </span>
+ ) : (
+ menuRow(close, MENU_ICONS.leave, S.company.chart.leave, () => setLeaveFor(employee), true)
+ )}
+ </>
+ );
+
+ const zoomControl = (
+ <div className="flex items-center" role="group" aria-label={S.company.chart.zoom}>
+ <Button
+ size="icon"
+ variant="ghost"
+ title={S.company.chart.zoomOut}
+ aria-label={S.company.chart.zoomOut}
+ disabled={current.scale <= ZOOM_MIN}
+ onClick={() => zoomStep(-1)}
+ >
+ <GlyphIcon d={ZOOM_ICONS.out} size={ICON_SIZE.iconButton} />
+ </Button>
+ <button
+ type="button"
+ title={S.company.chart.zoomFit}
+ aria-label={`${S.company.chart.zoomFit} · ${percent}%`}
+ onClick={() => {
+ setViewEpoch((n) => n + 1);
+ setView(null);
+ }}
+ className="min-w-11 rounded-md px-1 py-1 text-center text-xs text-gray-600 tabular-nums transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100"
+ >
+ {percent}%
+ </button>
+ <Button
+ size="icon"
+ variant="ghost"
+ title={S.company.chart.zoomIn}
+ aria-label={S.company.chart.zoomIn}
+ disabled={current.scale >= ZOOM_MAX}
+ onClick={() => zoomStep(1)}
+ >
+ <GlyphIcon d={ZOOM_ICONS.in} size={ICON_SIZE.iconButton} />
+ </Button>
+ </div>
+ );
+
+ return (
+ <OrgPage
+ title={S.nav.org.chart}
+ info={S.company.chart.info}
+ wide
+ {...(layout.nodes.length > 0 ? { actions: zoomControl } : {})}
+ >
+ {/* A refresh that failed while a chart is on screen: say so above it, keep the chart. */}
+ {error !== null && (
+ <div
+ className={`mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border px-3 py-1.5 text-xs ${toneStrip.danger}`}
+ >
+ <span>{S.company.chart.refreshFailed(error)}</span>
+ <Button size="sm" onClick={() => void load()}>
+ {S.common.retry}
+ </Button>
+ </div>
+ )}
+ {layout.detached.length > 0 && (
+ <div className={`mb-3 rounded-md border px-3 py-1.5 text-xs ${toneStrip.attention}`}>
+ {S.company.chart.detachedNotice(layout.detached.length)}
+ </div>
+ )}
+ {layout.nodes.length === 0 ? (
+ <EmptyState title={S.company.chart.empty} />
+ ) : (
+ <>
+ <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
+ <ChartLegend />
+ <span className="text-[11px] text-gray-500 dark:text-gray-400">
+ {S.company.chart.employeeCount(chart.employees.length)}
+ </span>
+ </div>
+ {/* The canvas: a clipping frame that fills the window, and one transformed layer
+ inside it. `select-none` because a drag across the cards is a pan, not a
+ selection; `touch-action: none` because it is a one-finger pan, not a scroll. */}
+ <div
+ ref={setFrameEl}
+ role="group"
+ aria-label={S.company.chart.canvas}
+ tabIndex={0}
+ onKeyDown={onCanvasKeyDown}
+ {...panDrag}
+ style={{ height: frame.height, touchAction: "none" }}
+ className={`relative select-none overflow-hidden rounded-lg border border-gray-200 bg-gray-50/60 outline-none focus-visible:border-gray-400 dark:border-gray-800 dark:bg-gray-900/40 dark:focus-visible:border-gray-600 ${
+ panning ? "cursor-grabbing" : "cursor-grab"
+ }`}
+ >
+ <div
+ className="absolute top-0 left-0 origin-top-left"
+ style={{
+ width: layout.width,
+ height: layout.height,
+ transform: viewTransform(current),
+ }}
+ >
+ <svg
+ width={layout.width}
+ height={layout.height}
+ className="absolute inset-0 text-gray-300 dark:text-gray-700"
+ aria-hidden
+ >
+ {layout.edges.map((edge) => (
+ <path
+ key={`${edge.fromId}>${edge.toId}`}
+ d={edge.path}
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ />
+ ))}
+ </svg>
+ {layout.detachedTop !== null && (
+ <p
+ className={`absolute right-0 left-0 text-center text-[11px] font-medium ${toneInk.danger}`}
+ style={{ top: layout.detachedTop - CHART_DETACHED_LABEL_H }}
+ >
+ {S.company.chart.detached}
+ </p>
+ )}
+ {layout.nodes.map((node) => {
+ const employee = byId.get(node.id);
+ if (employee === undefined) return null;
+ const isCeo = employee.agentId === chart.ceoAgentId;
+ return (
+ <ChartCard
+ key={node.id}
+ employee={employee}
+ state={employeeStates.get(employee.agentId) ?? employee.state}
+ isCeo={isCeo}
+ currency={currency}
+ x={node.x}
+ y={node.y}
+ detached={node.detached}
+ viewEpoch={viewEpoch}
+ menu={(close) => nodeMenu(employee, isCeo, close)}
+ />
+ );
+ })}
+ </div>
+ </div>
+ </>
+ )}
+
+ {hireFor !== null && (
+ <HireDialog
+ open
+ projectId={projectId}
+ orgId={orgId}
+ manager={hireFor}
+ employees={chart.employees}
+ onClose={() => setHireFor(null)}
+ onHired={() => {
+ setHireFor(null);
+ void load();
+ void company.reloadOrganizations();
+ }}
+ />
+ )}
+ {editFor !== null && (
+ <EmployeeEditDialog
+ edit={editFor.edit}
+ projectId={projectId}
+ orgId={orgId}
+ employee={editFor.employee}
+ employees={chart.employees}
+ onClose={() => setEditFor(null)}
+ onSaved={() => {
+ setEditFor(null);
+ void load();
+ }}
+ />
+ )}
+ {renewFor !== null && (
+ <DeskRenewDialog
+ open
+ projectId={projectId}
+ orgId={orgId}
+ employee={renewFor}
+ onClose={() => setRenewFor(null)}
+ onChartChanged={() => void load()}
+ onRenewed={(sessionId) => {
+ setRenewFor(null);
+ void company.reloadOrgChart();
+ void company.reloadOrgSessions();
+ navigate(`/chat/${sessionId}`);
+ }}
+ />
+ )}
+ <ConfirmModal
+ open={leaveFor !== null}
+ title={S.company.chart.leave}
+ tone="danger"
+ confirmLabel={S.common.confirm}
+ busy={busy}
+ onClose={() => (busy ? undefined : setLeaveFor(null))}
+ onConfirm={() => void runLeave()}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {leaveFor === null ? "" : S.company.chart.leaveConfirm(leaveFor.name)}
+ </p>
+ </ConfirmModal>
+ </OrgPage>
+ );
+}
diff --git a/packages/web/src/features/company/org-chart-tree.ts b/packages/web/src/features/company/org-chart-tree.ts
new file mode 100644
index 00000000..2cc75350
--- /dev/null
+++ b/packages/web/src/features/company/org-chart-tree.ts
@@ -0,0 +1,252 @@
+/**
+ * The org chart's tree and layout (pure, unit tested): the reporting line as a tree rooted at
+ * the CEO, laid out top-down the way an org chart reads — the root at the top centre, each
+ * depth one row lower, siblings side by side, a parent centred over its children. Every
+ * subtree owns a horizontal band as wide as its widest generation, so bands never overlap
+ * and a deep subtree pushes its cousins outward instead of stacking on them. Node boxes are
+ * fixed-size, so the layout needs no text measurement and is the same in a test as on screen.
+ *
+ * Employees whose reporting line never reaches the CEO — the manager left, or the line loops —
+ * are not dropped: they go to a "detached" row under the tree, without edges, so the page can
+ * mark them and offer the reporting-line fix.
+ */
+
+export interface ChartTreeNode {
+ id: string;
+ parentId: string | null;
+ depth: number;
+}
+
+/**
+ * The tree in DFS preorder from the CEO (children in the chart's own order), plus the
+ * employees whose reporting chain never reaches the CEO — a cycle, or a manager that left
+ * the chart — listed apart. A missing CEO leaves everyone detached rather than inventing a
+ * root.
+ */
+export function buildChartTree(
+ employees: ReadonlyArray<{ agentId: string; reportsTo: string | null }>,
+ ceoAgentId: string,
+): { nodes: ChartTreeNode[]; detached: string[] } {
+ const childrenOf = new Map<string, string[]>();
+ for (const e of employees) {
+ if (e.reportsTo === null || e.agentId === ceoAgentId) continue;
+ const list = childrenOf.get(e.reportsTo);
+ if (list) list.push(e.agentId);
+ else childrenOf.set(e.reportsTo, [e.agentId]);
+ }
+ const nodes: ChartTreeNode[] = [];
+ const seen = new Set<string>();
+ const hasCeo = employees.some((e) => e.agentId === ceoAgentId);
+ const walk = (id: string, parentId: string | null, depth: number): void => {
+ if (seen.has(id)) return;
+ seen.add(id);
+ nodes.push({ id, parentId, depth });
+ for (const child of childrenOf.get(id) ?? []) walk(child, id, depth + 1);
+ };
+ if (hasCeo) walk(ceoAgentId, null, 0);
+ const detached = employees.map((e) => e.agentId).filter((id) => !seen.has(id));
+ return { nodes, detached };
+}
+
+/** Every employee in `rootId`'s subtree, itself included — the ids a reporting-line change must not pick as the new manager. */
+export function subtreeIds(
+ employees: ReadonlyArray<{ agentId: string; reportsTo: string | null }>,
+ rootId: string,
+): Set<string> {
+ const out = new Set<string>([rootId]);
+ let grew = true;
+ while (grew) {
+ grew = false;
+ for (const e of employees) {
+ if (e.reportsTo !== null && out.has(e.reportsTo) && !out.has(e.agentId)) {
+ out.add(e.agentId);
+ grew = true;
+ }
+ }
+ }
+ return out;
+}
+
+/** Managers an employee may be moved under: anyone outside its own subtree (a report cannot manage its manager's manager's… self). */
+export function managerCandidates<T extends { agentId: string; reportsTo: string | null }>(
+ employees: readonly T[],
+ agentId: string,
+): T[] {
+ const excluded = subtreeIds(employees, agentId);
+ return employees.filter((e) => !excluded.has(e.agentId));
+}
+
+/** Card box (px). Fixed so the layout is text-free; the card fits name + title, state + workspace + spend, and a ratio bar. */
+export const CHART_NODE_W = 240;
+export const CHART_NODE_H = 92;
+/** Between sibling cards, and between one generation's bottom and the next one's top. */
+export const CHART_GAP_X = 48;
+export const CHART_GAP_Y = 64;
+/** Breathing room around the whole drawing. */
+export const CHART_PAD = 16;
+/** Corner radius of a connector's two elbows (shrinks when the horizontal run is shorter). */
+export const CHART_EDGE_RADIUS = 8;
+/** Room above the detached row for its label. */
+export const CHART_DETACHED_LABEL_H = 24;
+
+export interface OrgTreeNode extends ChartTreeNode {
+ /** Top-left corner of the card. */
+ x: number;
+ y: number;
+ /** In the detached row rather than the tree. */
+ detached: boolean;
+}
+
+export interface OrgTreeEdge {
+ fromId: string;
+ toId: string;
+ /** SVG path: parent bottom centre, down to the rail, along it, down to the child's top centre. */
+ path: string;
+}
+
+export interface OrgTreeLayout {
+ width: number;
+ height: number;
+ nodes: OrgTreeNode[];
+ edges: OrgTreeEdge[];
+ /** Ids in the detached row, in chart order (empty when every employee hangs off the CEO). */
+ detached: string[];
+ /** The detached row's top edge; null without one. */
+ detachedTop: number | null;
+}
+
+/** An orthogonal connector with rounded elbows: down from (x1, y1) to the rail, along it, down to (x2, y2). */
+export function connectorPath(
+ x1: number,
+ y1: number,
+ x2: number,
+ y2: number,
+ railY: number,
+): string {
+ if (x1 === x2) return `M ${x1} ${y1} V ${y2}`;
+ const dir = x2 > x1 ? 1 : -1;
+ const r = Math.min(CHART_EDGE_RADIUS, Math.abs(x2 - x1) / 2, (railY - y1) / 2, (y2 - railY) / 2);
+ return (
+ `M ${x1} ${y1} V ${railY - r} Q ${x1} ${railY} ${x1 + dir * r} ${railY}` +
+ ` H ${x2 - dir * r} Q ${x2} ${railY} ${x2} ${railY + r} V ${y2}`
+ );
+}
+
+/**
+ * Top-down layout of the reporting tree. Widths first: a leaf is one card wide, a parent as
+ * wide as its children's bands plus the gaps between them. Then positions: children are
+ * placed left to right inside the parent's band, and the parent's x is the midpoint of its
+ * first and last child's, so its stem meets the rail in the middle. The tree and the
+ * detached row are each centred on the wider of the two.
+ */
+export function layoutOrgTree(
+ employees: ReadonlyArray<{ agentId: string; reportsTo: string | null }>,
+ ceoAgentId: string,
+): OrgTreeLayout {
+ const { nodes, detached } = buildChartTree(employees, ceoAgentId);
+ const childrenOf = new Map<string, ChartTreeNode[]>();
+ for (const n of nodes) {
+ if (n.parentId === null) continue;
+ const list = childrenOf.get(n.parentId);
+ if (list) list.push(n);
+ else childrenOf.set(n.parentId, [n]);
+ }
+
+ const bandOf = new Map<string, number>();
+ const measure = (node: ChartTreeNode): number => {
+ const kids = childrenOf.get(node.id) ?? [];
+ const band =
+ kids.length === 0
+ ? CHART_NODE_W
+ : kids.reduce((acc, k) => acc + measure(k), 0) + (kids.length - 1) * CHART_GAP_X;
+ bandOf.set(node.id, band);
+ return band;
+ };
+ const root = nodes.find((n) => n.parentId === null);
+ const treeW = root === undefined ? 0 : measure(root);
+ const maxDepth = nodes.reduce((acc, n) => Math.max(acc, n.depth), 0);
+ const treeH = root === undefined ? 0 : (maxDepth + 1) * CHART_NODE_H + maxDepth * CHART_GAP_Y;
+
+ const rowW =
+ detached.length === 0
+ ? 0
+ : detached.length * CHART_NODE_W + (detached.length - 1) * CHART_GAP_X;
+ const innerW = Math.max(treeW, rowW);
+ const treeLeft = CHART_PAD + (innerW - treeW) / 2;
+ const rowLeft = CHART_PAD + (innerW - rowW) / 2;
+
+ const xOf = new Map<string, number>();
+ const place = (node: ChartTreeNode, left: number): void => {
+ const kids = childrenOf.get(node.id) ?? [];
+ if (kids.length === 0) {
+ xOf.set(node.id, left);
+ return;
+ }
+ let cursor = left;
+ for (const k of kids) {
+ place(k, cursor);
+ cursor += bandOf.get(k.id)! + CHART_GAP_X;
+ }
+ const first = xOf.get(kids[0]!.id)!;
+ const last = xOf.get(kids[kids.length - 1]!.id)!;
+ xOf.set(node.id, (first + last) / 2);
+ };
+ if (root !== undefined) place(root, treeLeft);
+
+ const detachedTop =
+ detached.length === 0
+ ? null
+ : CHART_PAD + treeH + (treeH > 0 ? CHART_GAP_Y : 0) + CHART_DETACHED_LABEL_H;
+
+ const placed: OrgTreeNode[] = nodes.map((node) => ({
+ ...node,
+ x: Math.round(xOf.get(node.id) ?? treeLeft),
+ y: CHART_PAD + node.depth * (CHART_NODE_H + CHART_GAP_Y),
+ detached: false,
+ }));
+ detached.forEach((id, i) => {
+ placed.push({
+ id,
+ parentId: null,
+ depth: maxDepth + 1,
+ x: Math.round(rowLeft + i * (CHART_NODE_W + CHART_GAP_X)),
+ y: detachedTop!,
+ detached: true,
+ });
+ });
+
+ const byId = new Map(placed.map((p) => [p.id, p]));
+ const edges: OrgTreeEdge[] = [];
+ for (const p of placed) {
+ if (p.parentId === null) continue;
+ const from = byId.get(p.parentId);
+ if (!from) continue;
+ const x1 = from.x + CHART_NODE_W / 2;
+ const y1 = from.y + CHART_NODE_H;
+ const x2 = p.x + CHART_NODE_W / 2;
+ const y2 = p.y;
+ edges.push({
+ fromId: from.id,
+ toId: p.id,
+ path: connectorPath(x1, y1, x2, y2, y1 + CHART_GAP_Y / 2),
+ });
+ }
+
+ const bottom = detachedTop === null ? CHART_PAD + treeH : detachedTop + CHART_NODE_H;
+ return {
+ width: innerW + CHART_PAD * 2,
+ height: (innerW === 0 ? 0 : bottom) + CHART_PAD,
+ nodes: placed,
+ edges,
+ detached,
+ detachedTop,
+ };
+}
+
+/** The last path segment of a workspace (`.` and the root stay as they are): the node's workspace tail. */
+export function workspaceTail(workspace: string): string {
+ const trimmed = workspace.trim();
+ if (trimmed === "" || trimmed === ".") return ".";
+ const parts = trimmed.split(/[/\\]+/).filter(Boolean);
+ return parts[parts.length - 1] ?? "/";
+}
diff --git a/packages/web/src/features/company/org-dialogs.tsx b/packages/web/src/features/company/org-dialogs.tsx
new file mode 100644
index 00000000..a6729b05
--- /dev/null
+++ b/packages/web/src/features/company/org-dialogs.tsx
@@ -0,0 +1,792 @@
+/**
+ * Organization dialogs, invoked from the sidebar's organization switcher (and the empty
+ * landing): create an organization — display name, the id (still required, generated from
+ * that name by the field's own button), a one-sentence mission with three examples under it,
+ * the Project it belongs to when the user has several, the model its sessions run on (the
+ * Project default unless chosen), the company workspace (the organization's own directory
+ * unless one is picked) and the CEO's monthly budget, which is the whole company's and is
+ * typed in the currency the reader reads money in but stored in USD — and an organization's
+ * settings: name, mission, model, workspace, timezone, working language, approval mode, and
+ * pause / resume — the one lifecycle control there is, since an organization is never deleted
+ * through the App. Pause / resume writes its own PATCH the moment it is clicked; everything
+ * else is a draft until Save.
+ *
+ * What the create dialog holds is kept as a draft (org-draft.ts) per user and Project, so an
+ * accidental close, a reload or a switch back to development mode does not cost the mission
+ * someone spent minutes writing; it is restored on reopen and dropped on a successful create
+ * or an explicit "clear draft". A caller that opens the dialog from a proposal (the empty
+ * landing's cards) passes that proposal as `initial`: it fills the name and the mission over
+ * whatever the draft held, and is then written through to the draft exactly as typed text is.
+ *
+ * Failures stay inside the dialog: a rejected id lands under the id field, anything else in
+ * a strip above the footer, and a settings load that fails offers its retry in place — the
+ * fields never sit disabled behind a toast that has already gone.
+ *
+ * `useOrganizationCreated` is the other half of creating one: what every host of the create
+ * dialog does once it succeeds — adopt the organization as the shell's current one, then open
+ * where the creation leads.
+ */
+import { useCallback, useEffect, useState } from "react";
+import { useNavigate } from "react-router";
+import type {
+ ModelRefDto,
+ ModelsResponse,
+ OrgApprovalMode,
+ OrgLanguage,
+ OrganizationCreateRequest,
+ OrganizationDetail,
+ OrganizationPatchRequest,
+ OrganizationSettings,
+} from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { ApiError } from "../../api/client";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { SEMANTIC_ID_PATTERN } from "../../lib/semantic-id";
+import { useAuth } from "../../state/auth";
+import { useCompany } from "../../state/company";
+import { projectDisplayName, useProject } from "../../state/project";
+import { useTheme } from "../../state/theme";
+import { Button } from "../../components/ui/button";
+import { Input, Textarea } from "../../components/ui/input";
+import { Select } from "../../components/ui/select";
+import { FieldError, FieldHint, FieldLabel } from "../../components/ui/field";
+import { Modal } from "../../components/ui/modal";
+import { InfoPopover } from "../../components/ui/info-popover";
+import { toastError, toastSuccess } from "../../components/ui/toast";
+import { ICON_GAP } from "../../lib/icon-scale";
+import { ModelSelect, modelLabel } from "../chat/model-select";
+import { WorkspaceSelect } from "../chat/workspace-select";
+import { sameModelRef } from "../models/model-grouping";
+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 {
+ EMPTY_ORG_DRAFT,
+ clearOrgDraft,
+ hasContent,
+ loadOrgDraft,
+ orgDraftKey,
+ saveOrgDraft,
+} from "./org-draft";
+
+const APPROVAL_MODES: readonly OrgApprovalMode[] = ["allow-all", "read-only", "deny-all"];
+
+/**
+ * The working languages an organization can be set to. An organization written before the
+ * field existed carries none, which the server reads as English — so does this dialog, or
+ * saving an unrelated field would silently re-declare the language.
+ */
+const ORG_LANGUAGES: readonly OrgLanguage[] = ["zh", "en"];
+const DEFAULT_ORG_LANGUAGE: OrgLanguage = "en";
+
+/**
+ * The CEO's monthly budget the dialog offers, in USD — the field shows it in the reader's own
+ * currency. It is the whole company's ceiling: the chart's budgets are cumulative over an
+ * employee and its subordinates, and everyone reports to the CEO. The server applies the same
+ * default when the field is left empty.
+ */
+const DEFAULT_CEO_BUDGET_USD = 100;
+
+/** The error codes that are about the id the user typed; every other failure is the form's. */
+const ID_ERROR_CODES = new Set(["org_exists", "invalid_org_id"]);
+
+/** The Project's configured models, loaded once per open; null until they arrive, with the failure kept beside them. */
+function useProjectModels(projectId: string, open: boolean) {
+ const [models, setModels] = useState<ModelsResponse | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ useEffect(() => {
+ if (!open || !projectId) return;
+ let cancelled = false;
+ setModels(null);
+ setError(null);
+ api
+ .getModels(projectId)
+ .then((res) => {
+ if (!cancelled) setModels(res);
+ })
+ .catch((e: unknown) => {
+ if (!cancelled) setError(apiErrorText(e));
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [open, projectId]);
+ return { models, error };
+}
+
+/**
+ * The model field: the App's own model picker (ModelSelect in its form shape — the same
+ * searchable, grouped, key-configured-first panel the chat composer and the Project's
+ * default-model setting open), with this field's two extra states around it.
+ *
+ * Empty is a choice here, not a gap: it means "follow the Project's default", named after
+ * that default when the list says which model it is. The panel offers models only, so the
+ * way back to empty is the field's own control, which stands where the hint that describes
+ * it otherwise stands. A stored model that is no longer configured is kept rather than
+ * silently replaced — the trigger names the id as stored, with a line underneath saying the
+ * Project no longer lists it.
+ */
+function ModelField({
+ models,
+ loadError,
+ value,
+ onChange,
+ disabled,
+}: {
+ models: ModelsResponse | null;
+ loadError: string | null;
+ value: ModelRefDto | null;
+ onChange: (ref: ModelRefDto | null) => void;
+ disabled: boolean;
+}) {
+ const list = models?.models ?? [];
+ // Only once the list has actually arrived: an empty list is also what "still loading" and
+ // "could not be read" look like, and neither is evidence that the stored model is gone.
+ const stale = models !== null && value !== null && !list.some((m) => sameModelRef(m, value));
+ const defaultInfo =
+ models?.defaultModel === undefined
+ ? undefined
+ : list.find((m) => sameModelRef(m, models.defaultModel));
+ const defaultLabel =
+ defaultInfo !== undefined
+ ? S.company.modelProjectDefaultNamed(modelLabel(defaultInfo))
+ : S.company.modelProjectDefault;
+ const loading = models === null && loadError === null;
+ return (
+ <div>
+ {/* The "?" sits beside the field's own title (the picker carries no info slot). */}
+ <span className="mb-1 flex items-center gap-1">
+ <FieldLabel block={false}>{S.company.modelField}</FieldLabel>
+ <InfoPopover label={S.company.modelField}>{S.company.modelInfo}</InfoPopover>
+ </span>
+ <ModelSelect
+ models={list}
+ value={value}
+ {...(models?.defaultModel !== undefined ? { defaultModel: models.defaultModel } : {})}
+ onChange={onChange}
+ disabled={disabled || loading}
+ variant="form"
+ emptyLabel={loading ? S.common.loading : defaultLabel}
+ />
+ {loadError !== null ? (
+ <FieldError>{S.company.modelsLoadFailed}</FieldError>
+ ) : value === null ? (
+ <FieldHint>{S.company.modelHint}</FieldHint>
+ ) : (
+ <span className="mt-1 flex flex-wrap items-baseline gap-x-2">
+ {stale && (
+ <span className="text-xs text-gray-500 dark:text-gray-500">{S.company.modelStale}</span>
+ )}
+ {/* The hint's instruction, as the action that carries it out. */}
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={() => onChange(null)}
+ className="text-xs text-gray-500 underline decoration-gray-300 underline-offset-2 transition-colors duration-150 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-60 dark:text-gray-400 dark:hover:text-gray-200"
+ >
+ {S.company.modelClear}
+ </button>
+ </span>
+ )}
+ </div>
+ );
+}
+
+/** The company workspace: the chat draft's directory browser in its form shape; empty means the organization's own directory. */
+function WorkspaceField({
+ projectId,
+ value,
+ onChange,
+}: {
+ projectId: string;
+ value: string;
+ onChange: (path: string) => void;
+}) {
+ return (
+ <div>
+ <span className="mb-1 flex items-center gap-1">
+ <FieldLabel block={false}>{S.company.workspaceField}</FieldLabel>
+ <InfoPopover label={S.company.workspaceField}>{S.company.workspaceInfo}</InfoPopover>
+ </span>
+ <WorkspaceSelect
+ projectId={projectId}
+ workspace={value}
+ onChange={onChange}
+ variant="form"
+ fieldLabel={S.company.workspaceField}
+ emptyLabel={S.company.workspaceEmpty}
+ menuHint={S.company.workspaceMenuHint}
+ clearLabel={S.company.workspaceClear}
+ />
+ <FieldHint>{S.company.workspaceHint}</FieldHint>
+ </div>
+ );
+}
+
+/**
+ * The three example missions under the mission field. A click takes the mission whole (the
+ * click asks for THIS mission) and the display name only while the name is still empty, so
+ * an example never overwrites what someone typed; the id is left to the generate button
+ * beside it. One line each — the mission is long enough that a card of it would push the
+ * rest of the form off the dialog, so the row carries the names and the tooltips carry what
+ * each one actually says.
+ *
+ * The row is rendered inside the mission field and sits against it, not a field's distance
+ * below: it fills that field in, and an unlabelled row a whole gap away reads as a field of
+ * its own with its title missing.
+ */
+function MissionExamples({
+ disabled,
+ onPick,
+}: {
+ disabled: boolean;
+ onPick: (example: { name: string; mission: string }) => void;
+}) {
+ return (
+ <div className="mt-1.5 grid grid-cols-2 gap-1.5">
+ {ORG_EXAMPLES.map((example) => {
+ const copy = S.company.missionExamples[example.id];
+ return (
+ <button
+ key={example.id}
+ type="button"
+ title={`${copy.mission}\n${S.company.missionExampleHint}`}
+ disabled={disabled}
+ onClick={() => onPick(copy)}
+ className="min-w-0 truncate rounded-md border border-gray-200 px-2 py-1 text-left text-[11px] text-gray-600 transition-colors duration-150 hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 disabled:cursor-not-allowed disabled:opacity-60 dark:border-gray-700 dark:text-gray-400 dark:hover:border-gray-600 dark:hover:bg-gray-800 dark:hover:text-gray-100"
+ >
+ {copy.name}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+/**
+ * What a host of the create dialog does with a creation, in one place because all four of
+ * them — the switcher's menu, the empty sidebar, the empty landing and the "organization is
+ * gone" page — owe the shell the same two things.
+ *
+ * The new organization becomes the shell's current one BEFORE the navigation: creation opens
+ * the CEO's desk session, which lives at `/chat/:sessionId` and is therefore not one of the
+ * organization's own routes — and those routes are the only other thing that announces which
+ * organization the shell is inside. Without this the sidebar would go on listing the previous
+ * organization's channels and desks around the conversation the new one just opened.
+ *
+ * The organization list is refreshed first, and awaited: `setCurrentOrg` only says which key
+ * is open, and the switcher's label, the status dot and the page header all read the summary
+ * out of that list. A key the list does not hold yet would leave the shell naming nothing for
+ * as long as the refresh takes, and the settled-list check that forgets deleted organizations
+ * reads the same list.
+ */
+export function useOrganizationCreated(): (detail: OrganizationDetail) => Promise<void> {
+ const navigate = useNavigate();
+ const { reloadOrganizations, setCurrentOrg } = useCompany();
+ return useCallback(
+ async (detail: OrganizationDetail) => {
+ await reloadOrganizations();
+ const target = orgCreatedTarget(detail);
+ setCurrentOrg(target.key);
+ navigate(target.path);
+ },
+ [navigate, reloadOrganizations, setCurrentOrg],
+ );
+}
+
+export function CreateOrganizationDialog({
+ open,
+ initial,
+ onClose,
+ onCreated,
+}: {
+ open: boolean;
+ /** A proposal the dialog opens filled in with (the empty landing's cards); the id is still generated. */
+ initial?: { name: string; mission: string };
+ onClose: () => void;
+ onCreated: (detail: OrganizationDetail) => void;
+}) {
+ const { projects, currentProject } = useProject();
+ const { user } = useAuth();
+ const { currency } = useTheme();
+ const [projectId, setProjectId] = useState("");
+ const [orgId, setOrgId] = useState("");
+ const [name, setName] = useState("");
+ const [mission, setMission] = useState("");
+ const [modelRef, setModelRef] = useState<ModelRefDto | null>(null);
+ const [workspace, setWorkspace] = useState("");
+ const [ceoBudget, setCeoBudget] = useState(() => fromStoredUsd(DEFAULT_CEO_BUDGET_USD, currency));
+ const [idError, setIdError] = useState<string | undefined>(undefined);
+ const [missionError, setMissionError] = useState<string | undefined>(undefined);
+ const [budgetError, setBudgetError] = useState<string | undefined>(undefined);
+ const [formError, setFormError] = useState<string | null>(null);
+ /** A stored draft was put back into the fields: the notice above them says so and offers to drop it. */
+ const [restored, setRestored] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const { models, error: modelsError } = useProjectModels(projectId, open);
+
+ // The Project the organization is being created in: the current one on open, changeable
+ // below when the user has several.
+ useEffect(() => {
+ if (!open) return;
+ setProjectId(currentProject?.projectId ?? projects[0]?.projectId ?? "");
+ }, [open, currentProject, projects]);
+
+ /** The draft's key; null before the target Project is known (nothing to store against). */
+ const draftKey = projectId === "" ? null : orgDraftKey(user?.userId ?? null, projectId);
+
+ const resetForm = (draft = EMPTY_ORG_DRAFT) => {
+ setOrgId(draft.orgId);
+ setName(draft.name);
+ setMission(draft.mission);
+ setModelRef(draft.model);
+ setWorkspace(draft.workspace);
+ setCeoBudget(
+ draft.ceoBudget === "" ? fromStoredUsd(DEFAULT_CEO_BUDGET_USD, currency) : draft.ceoBudget,
+ );
+ setIdError(undefined);
+ setMissionError(undefined);
+ setBudgetError(undefined);
+ setFormError(null);
+ };
+
+ // Restore on open, and again when the target Project changes: a draft belongs to the
+ // Project it was aimed at, since its Workspace and model are that Project's. This also
+ // subsumes the old "switching Projects drops the model pick" rule.
+ //
+ // A proposal outranks the draft's own name and mission — the click asked for THIS one — and
+ // the notice above the fields is then not the truth about what is on screen, so it stays
+ // down. The two texts are the effect's dependencies rather than the object holding them: a
+ // caller building it inline would otherwise reset the form on every render.
+ const initialName = initial?.name ?? null;
+ const initialMission = initial?.mission ?? null;
+ useEffect(() => {
+ if (!open) return;
+ const draft = draftKey === null ? null : loadOrgDraft(draftKey);
+ const base = draft ?? EMPTY_ORG_DRAFT;
+ resetForm(
+ initialMission === null
+ ? base
+ : { ...base, name: initialName ?? base.name, mission: initialMission },
+ );
+ setRestored(draft !== null && initialMission === null);
+ // resetForm is a plain setter bundle; re-running on its identity would reset on every render.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open, draftKey, initialName, initialMission]);
+
+ // Every edit is written straight through: the draft exists for the close nobody meant.
+ useEffect(() => {
+ if (!open || draftKey === null) return;
+ saveOrgDraft(draftKey, { orgId, name, mission, workspace, model: modelRef, ceoBudget });
+ }, [open, draftKey, orgId, name, mission, workspace, modelRef, ceoBudget]);
+
+ /** Whether there is anything in the form a "clear draft" would remove. */
+ const draftContent = hasContent({
+ orgId,
+ name,
+ mission,
+ workspace,
+ model: modelRef,
+ ceoBudget,
+ });
+
+ const dropDraft = () => {
+ if (draftKey !== null) clearOrgDraft(draftKey);
+ setRestored(false);
+ resetForm();
+ };
+
+ const submit = async () => {
+ const id = orgId.trim();
+ const budget = ceoBudget.trim();
+ let bad = false;
+ if (!id) {
+ setIdError(S.common.requiredField);
+ bad = true;
+ } else if (!SEMANTIC_ID_PATTERN.test(id)) {
+ setIdError(S.company.orgIdHint);
+ bad = true;
+ }
+ if (!mission.trim()) {
+ setMissionError(S.common.requiredField);
+ bad = true;
+ }
+ if (!isBudgetText(budget)) {
+ setBudgetError(S.company.ceoBudgetHint);
+ bad = true;
+ }
+ if (bad || !projectId) return;
+ setBusy(true);
+ setFormError(null);
+ try {
+ // An omitted budget is the server's own default (100 USD a month); what was typed is in
+ // the reader's currency and goes out in USD, which is what the chart file holds.
+ const ceoBudgetUsd = toStoredUsd(budget, currency);
+ const body: OrganizationCreateRequest = {
+ orgId: id,
+ mission: mission.trim(),
+ ...(name.trim() ? { name: name.trim() } : {}),
+ ...(workspace.trim() ? { workspace: workspace.trim() } : {}),
+ ...(modelRef !== null ? { model: modelRef } : {}),
+ ...(ceoBudgetUsd !== null ? { ceoBudget: ceoBudgetUsd } : {}),
+ };
+ const detail = await api.createOrganization(projectId, body);
+ // The draft did its job: what it held is now an organization.
+ if (draftKey !== null) clearOrgDraft(draftKey);
+ setRestored(false);
+ toastSuccess(S.company.createdOpeningCeo);
+ onCreated(detail);
+ } catch (e) {
+ const text = apiErrorText(e);
+ if (e instanceof ApiError && ID_ERROR_CODES.has(e.code)) setIdError(text);
+ else setFormError(text);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <Modal
+ open={open}
+ title={S.company.createTitle}
+ onClose={busy ? () => undefined : onClose}
+ widthClass="sm:max-w-lg"
+ footer={
+ <>
+ {/* Dropping the draft is a form action, not a dialog verdict: it sits away from
+ Cancel / Create so a click on it can never be mistaken for either. */}
+ {draftContent && (
+ <Button size="sm" onClick={dropDraft} disabled={busy} className="mr-auto">
+ {S.company.clearDraft}
+ </Button>
+ )}
+ <Button size="sm" onClick={onClose} disabled={busy}>
+ {S.common.cancel}
+ </Button>
+ <Button size="sm" variant="primary" disabled={busy} onClick={() => void submit()}>
+ {busy ? S.company.creating : S.common.create}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ {restored && (
+ <p className="rounded-md bg-gray-100 px-2.5 py-1.5 text-xs text-gray-600 dark:bg-gray-800 dark:text-gray-300">
+ {S.company.draftRestored}
+ </p>
+ )}
+ {projects.length > 1 && (
+ <Select
+ size="sm"
+ label={S.project.switcher}
+ value={projectId}
+ disabled={busy}
+ onChange={(e) => setProjectId(e.target.value)}
+ >
+ {projects.map((p) => (
+ <option key={p.projectId} value={p.projectId}>
+ {projectDisplayName(p)}
+ </option>
+ ))}
+ </Select>
+ )}
+ {/* 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. */}
+ <Input
+ label={S.company.displayName}
+ size="sm"
+ value={name}
+ hint={S.company.displayNameHint}
+ autoFocus
+ disabled={busy}
+ onChange={(e) => setName(e.target.value)}
+ />
+ <SemanticIdField
+ projectId={projectId}
+ kind="org"
+ label={S.company.orgId}
+ hint={S.company.orgIdHint}
+ value={orgId}
+ source={name.trim() || mission}
+ error={idError}
+ disabled={busy}
+ onChange={(id) => {
+ setOrgId(id);
+ setIdError(undefined);
+ }}
+ />
+ <div>
+ <Textarea
+ label={S.company.mission}
+ required
+ size="sm"
+ rows={3}
+ value={mission}
+ error={missionError}
+ hint={S.company.missionHint}
+ placeholder={S.company.missionPlaceholder}
+ disabled={busy}
+ onChange={(e) => {
+ setMission(e.target.value);
+ setMissionError(undefined);
+ }}
+ />
+ <MissionExamples
+ disabled={busy}
+ onPick={(example) => {
+ setMission(example.mission);
+ setMissionError(undefined);
+ if (name.trim() === "") setName(example.name);
+ }}
+ />
+ </div>
+ <ModelField
+ models={models}
+ loadError={modelsError}
+ value={modelRef}
+ onChange={setModelRef}
+ disabled={busy}
+ />
+ <WorkspaceField projectId={projectId} value={workspace} onChange={setWorkspace} />
+ <MoneyPerMonthInput
+ label={S.company.ceoBudget}
+ currency={currency}
+ value={ceoBudget}
+ hint={S.company.ceoBudgetHint}
+ {...(budgetError !== undefined ? { error: budgetError } : {})}
+ disabled={busy}
+ onChange={(text) => {
+ setCeoBudget(text);
+ setBudgetError(undefined);
+ }}
+ />
+ {formError !== null && <ErrorLine message={formError} onRetry={() => void submit()} />}
+ </div>
+ </Modal>
+ );
+}
+
+export function OrganizationSettingsDialog({
+ open,
+ projectId,
+ orgId,
+ onClose,
+ onChanged,
+}: {
+ open: boolean;
+ projectId: string;
+ orgId: string;
+ onClose: () => void;
+ /** Settings were written (name, mission, status …): the caller refreshes the list. */
+ onChanged: () => void;
+}) {
+ /** Stored settings as loaded on open (null until then) — the no-change baseline. */
+ const [settings, setSettings] = useState<OrganizationSettings | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [name, setName] = useState("");
+ const [mission, setMission] = useState("");
+ const [timezone, setTimezone] = useState("");
+ const [language, setLanguage] = useState<OrgLanguage>(DEFAULT_ORG_LANGUAGE);
+ const [approvalMode, setApprovalMode] = useState<OrgApprovalMode>("allow-all");
+ const [modelRef, setModelRef] = useState<ModelRefDto | null>(null);
+ const [workspace, setWorkspace] = useState("");
+ const [busy, setBusy] = useState(false);
+ const { models, error: modelsError } = useProjectModels(projectId, open);
+
+ const adopt = (next: OrganizationSettings) => {
+ setSettings(next);
+ setName(next.name);
+ setMission(next.mission);
+ setTimezone(next.timezone);
+ setLanguage(next.language ?? DEFAULT_ORG_LANGUAGE);
+ setApprovalMode(next.approvalMode);
+ setModelRef(next.model ?? null);
+ setWorkspace(next.workspace ?? "");
+ };
+
+ const load = useCallback(() => {
+ let cancelled = false;
+ setSettings(null);
+ setLoadError(null);
+ void api
+ .getOrganization(projectId, orgId)
+ .then((detail) => {
+ if (!cancelled) adopt(detail.settings);
+ })
+ .catch((e: unknown) => {
+ if (!cancelled) setLoadError(apiErrorText(e));
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [projectId, orgId]);
+
+ useEffect(() => {
+ if (!open) return;
+ return load();
+ }, [open, load]);
+
+ const patch = async (body: OrganizationPatchRequest) => {
+ setBusy(true);
+ try {
+ adopt(await api.patchOrganization(projectId, orgId, body));
+ toastSuccess(S.common.saved);
+ onChanged();
+ return true;
+ } catch (e) {
+ toastError(apiErrorText(e));
+ return false;
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const save = () => {
+ if (settings === null) return;
+ const body: OrganizationPatchRequest = {};
+ if (name.trim() && name.trim() !== settings.name) body.name = name.trim();
+ if (mission.trim() && mission.trim() !== settings.mission) body.mission = mission.trim();
+ if (timezone.trim() && timezone.trim() !== settings.timezone) body.timezone = timezone.trim();
+ if (language !== (settings.language ?? DEFAULT_ORG_LANGUAGE)) body.language = language;
+ if (approvalMode !== settings.approvalMode) body.approvalMode = approvalMode;
+ // Clearing sends null: the organization returns to the Project default / its own directory.
+ const storedModel = settings.model ?? null;
+ if (!(storedModel === null && modelRef === null) && !sameModelRef(storedModel, modelRef)) {
+ body.model = modelRef;
+ }
+ const nextWorkspace = workspace.trim();
+ if (nextWorkspace !== (settings.workspace ?? "")) {
+ body.workspace = nextWorkspace === "" ? null : nextWorkspace;
+ }
+ if (Object.keys(body).length === 0) {
+ onClose();
+ return;
+ }
+ void patch(body).then((ok) => {
+ if (ok) onClose();
+ });
+ };
+
+ const hydrated = settings !== null;
+ const paused = settings?.status === "paused";
+ return (
+ <Modal
+ open={open}
+ title={S.company.settingsTitle}
+ onClose={onClose}
+ widthClass="sm:max-w-lg"
+ footer={
+ <>
+ <Button size="sm" onClick={onClose} disabled={busy}>
+ {S.common.cancel}
+ </Button>
+ <Button size="sm" variant="primary" disabled={!hydrated || busy} onClick={save}>
+ {S.common.save}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ {loadError !== null && (
+ <ErrorLine message={S.company.settingsLoadFailed} detail={loadError} onRetry={load} />
+ )}
+ {/* Status row: the pause / resume is immediate (its own PATCH), not part of Save —
+ stopping an organization is a decision, not a draft. */}
+ <div className="flex items-center justify-between gap-3">
+ <span
+ className={`flex items-center ${ICON_GAP.row} text-xs font-semibold text-gray-600 dark:text-gray-400`}
+ >
+ {S.company.status}
+ <InfoPopover label={S.company.status}>{S.company.pauseInfo}</InfoPopover>
+ </span>
+ <span className="flex items-center gap-2">
+ {settings !== null && <OrgStatusPill org={settings} />}
+ <Button
+ size="sm"
+ disabled={!hydrated || busy}
+ onClick={() => void patch({ status: paused ? "active" : "paused" })}
+ >
+ {paused ? S.company.resume : S.company.pause}
+ </Button>
+ </span>
+ </div>
+ <Input
+ label={S.company.displayName}
+ size="sm"
+ value={name}
+ disabled={!hydrated || busy}
+ onChange={(e) => setName(e.target.value)}
+ />
+ <Textarea
+ label={S.company.mission}
+ size="sm"
+ rows={3}
+ value={mission}
+ disabled={!hydrated || busy}
+ hint={S.company.missionHint}
+ onChange={(e) => setMission(e.target.value)}
+ />
+ <ModelField
+ models={models}
+ loadError={modelsError}
+ value={modelRef}
+ onChange={setModelRef}
+ disabled={!hydrated || busy}
+ />
+ <WorkspaceField projectId={projectId} value={workspace} onChange={setWorkspace} />
+ <Input
+ label={S.company.timezone}
+ size="sm"
+ value={timezone}
+ disabled={!hydrated || busy}
+ hint={S.company.timezoneHint}
+ className="font-mono"
+ onChange={(e) => setTimezone(e.target.value)}
+ />
+ <div>
+ {/* The "?" sits beside the field's own title (Select carries no info slot). */}
+ <span className="mb-1 flex items-center gap-1">
+ <FieldLabel block={false}>{S.company.language}</FieldLabel>
+ <InfoPopover label={S.company.language}>{S.company.languageInfo}</InfoPopover>
+ </span>
+ <Select
+ size="sm"
+ aria-label={S.company.language}
+ value={language}
+ disabled={!hydrated || busy}
+ onChange={(e) => setLanguage(e.target.value as OrgLanguage)}
+ >
+ {ORG_LANGUAGES.map((l) => (
+ <option key={l} value={l}>
+ {S.company.languages[l]}
+ </option>
+ ))}
+ </Select>
+ </div>
+ <div>
+ {/* The "?" sits beside the field's own title (Select carries no info slot). */}
+ <span className="mb-1 flex items-center gap-1">
+ <FieldLabel block={false}>{S.company.approvalMode}</FieldLabel>
+ <InfoPopover label={S.company.approvalMode}>{S.company.approvalModeInfo}</InfoPopover>
+ </span>
+ <Select
+ size="sm"
+ aria-label={S.company.approvalMode}
+ value={approvalMode}
+ disabled={!hydrated || busy}
+ onChange={(e) => setApprovalMode(e.target.value as OrgApprovalMode)}
+ >
+ {APPROVAL_MODES.map((m) => (
+ <option key={m} value={m}>
+ {S.company.approvalModes[m] ?? m}
+ </option>
+ ))}
+ </Select>
+ </div>
+ </div>
+ </Modal>
+ );
+}
diff --git a/packages/web/src/features/company/org-draft.ts b/packages/web/src/features/company/org-draft.ts
new file mode 100644
index 00000000..92e98a97
--- /dev/null
+++ b/packages/web/src/features/company/org-draft.ts
@@ -0,0 +1,128 @@
+/**
+ * The create-organization dialog's draft: what was typed, kept in localStorage so an
+ * accidental close, a reload or a switch back to development mode does not lose a mission
+ * someone spent minutes on. It is a DRAFT, not a preference — it is written on every edit,
+ * restored when the dialog reopens and dropped the moment the organization is created (or
+ * the user clears it).
+ *
+ * Scoped by user and by Project: two people on one browser must not see each other's draft,
+ * and a draft belongs to the Project it was aimed at (its Workspace and model are that
+ * Project's). Storage is injectable (work-mode.ts convention: vitest runs in Node with no
+ * localStorage) and every read degrades to "no draft" rather than throwing at a dialog open.
+ */
+import type { ModelRefDto } from "@prismshadow/penguin-server/api";
+
+/** Minimal storage interface (the subset of localStorage used here); tests inject an in-memory one. */
+export interface DraftStorage {
+ getItem(key: string): string | null;
+ setItem(key: string, value: string): void;
+ removeItem(key: string): void;
+}
+
+/** The dialog's fields, exactly as typed — `ceoBudget` stays the raw text so a half-typed number survives. */
+export interface OrgCreateDraft {
+ orgId: string;
+ name: string;
+ mission: string;
+ workspace: string;
+ model: ModelRefDto | null;
+ ceoBudget: string;
+}
+
+export const EMPTY_ORG_DRAFT: OrgCreateDraft = {
+ orgId: "",
+ name: "",
+ mission: "",
+ workspace: "",
+ model: null,
+ ceoBudget: "",
+};
+
+/** The draft's storage key. One key per (user, Project); a signed-out browser gets its own bucket. */
+export function orgDraftKey(userId: string | null, projectId: string): string {
+ return `penguin.orgCreateDraft.${userId ?? ""}.${projectId}`;
+}
+
+const str = (v: unknown): string => (typeof v === "string" ? v : "");
+
+/** A stored model reference, or null for anything that is not one (a truncated write, an older shape). */
+function parseModel(v: unknown): ModelRefDto | null {
+ if (v === null || typeof v !== "object") return null;
+ const { provider, modelId } = v as { provider?: unknown; modelId?: unknown };
+ if (typeof provider !== "string" || typeof modelId !== "string") return null;
+ if (provider === "" || modelId === "") return null;
+ return { provider, modelId };
+}
+
+/**
+ * A stored draft, field by field. Anything unexpected (not JSON, not an object, a field of
+ * the wrong type) contributes its empty value instead of rejecting the whole draft: the
+ * mission is the expensive field, and losing it because the model reference was mangled
+ * would be the worst possible trade.
+ */
+export function parseOrgDraft(raw: string | null): OrgCreateDraft | null {
+ if (raw === null || raw === "") return null;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(raw);
+ } catch {
+ return null;
+ }
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
+ const d = parsed as Record<string, unknown>;
+ const draft: OrgCreateDraft = {
+ orgId: str(d.orgId),
+ name: str(d.name),
+ mission: str(d.mission),
+ workspace: str(d.workspace),
+ model: parseModel(d.model),
+ ceoBudget: str(d.ceoBudget),
+ };
+ return hasContent(draft) ? draft : null;
+}
+
+/**
+ * Whether a draft is worth storing or restoring at all. A form the user only opened and
+ * closed has nothing in it, and offering to "clear" that would be noise; the CEO budget is
+ * left out of the test because the dialog prefills it, so it is not something the user typed.
+ */
+export function hasContent(draft: OrgCreateDraft): boolean {
+ return (
+ draft.orgId.trim() !== "" ||
+ draft.name.trim() !== "" ||
+ draft.mission.trim() !== "" ||
+ draft.workspace.trim() !== "" ||
+ draft.model !== null
+ );
+}
+
+export function serializeOrgDraft(draft: OrgCreateDraft): string {
+ return JSON.stringify(draft);
+}
+
+export function loadOrgDraft(key: string, storage?: DraftStorage): OrgCreateDraft | null {
+ try {
+ return parseOrgDraft((storage ?? localStorage).getItem(key));
+ } catch {
+ return null;
+ }
+}
+
+/** Writes the draft, or removes it when there is nothing left in it to keep. */
+export function saveOrgDraft(key: string, draft: OrgCreateDraft, storage?: DraftStorage): void {
+ try {
+ const store = storage ?? localStorage;
+ if (hasContent(draft)) store.setItem(key, serializeOrgDraft(draft));
+ else store.removeItem(key);
+ } catch {
+ /* best-effort persistence (quota limits / private browsing) */
+ }
+}
+
+export function clearOrgDraft(key: string, storage?: DraftStorage): void {
+ try {
+ (storage ?? localStorage).removeItem(key);
+ } catch {
+ /* best-effort */
+ }
+}
diff --git a/packages/web/src/features/company/org-examples.ts b/packages/web/src/features/company/org-examples.ts
new file mode 100644
index 00000000..5ae349f3
--- /dev/null
+++ b/packages/web/src/features/company/org-examples.ts
@@ -0,0 +1,19 @@
+/**
+ * The example missions offered under the create-organization dialog's mission field: four
+ * companies that are worth starting, in the order they are shown — three that produce work of
+ * their own, and one that mirrors a real company into digital twins. Only the ids live here —
+ * the name and the mission of each are copy, and copy lives in the two dictionaries
+ * (`S.company.missionExamples[id]`), the way the draft screen's example tasks do.
+ *
+ * Clicking one fills the mission (it replaces what is there — the click asks for THIS
+ * mission) and the display name only while that field is still empty, so an example never
+ * overwrites a name someone typed. The id is left alone: it is generated from the name.
+ */
+export const ORG_EXAMPLES = [
+ { id: "research" },
+ { id: "agentTuning" },
+ { id: "cloudReseller" },
+ { id: "mirror" },
+] as const;
+
+export type OrgExampleId = (typeof ORG_EXAMPLES)[number]["id"];
diff --git a/packages/web/src/features/company/org-layout.tsx b/packages/web/src/features/company/org-layout.tsx
new file mode 100644
index 00000000..2c94db90
--- /dev/null
+++ b/packages/web/src/features/company/org-layout.tsx
@@ -0,0 +1,372 @@
+/**
+ * The route shell of company mode. `/org` alone resolves to an organization (the one last
+ * opened, else the first of the current Project, else the first anywhere) and opens its
+ * overview, or, with none, renders an empty landing that offers creating one;
+ * `/org/:projectId/:orgId/<page>` renders the page inside an organization context. Both fall
+ * back to a Session's own page while company mode is unavailable — the admin master switch
+ * off, or the user's own switch off — so a stale bookmark never shows an empty shell.
+ *
+ * Entering an organization's routes has three side effects the shell relies on: the work
+ * mode flips to company (a deep link is a mode choice), the current Project follows the
+ * route (the session list and the Agent set belong to the Project), and the organization
+ * becomes the shell's current one (its channels and their badges, its desks, the switcher's
+ * label) — and stays so after these routes unmount, since a desk conversation is one of the
+ * organization's own surfaces even though it lives at `/chat/:sessionId`.
+ *
+ * The organization layout is also where the ticket dialog is mounted, once: a ticket's detail
+ * is read in place from whichever surface named it — the board, the finance ledger, the
+ * overview's inbox, a channel's reference — so the window belongs to the shell around the
+ * pages rather than to any one of them.
+ *
+ * The page primitives live here too — `OrgPage`, `OrgSection`, `OrgEmptyLine` and the
+ * skeleton — so every organization page shares one frame, one header row and one section
+ * rule instead of each drawing its own.
+ */
+import { createContext, useContext, useEffect, useState } from "react";
+import type { ReactNode } from "react";
+import { Navigate, Outlet, useNavigate, useParams } from "react-router";
+import type { OrganizationSummary } from "@prismshadow/penguin-server/api";
+import { S } from "../../lib/strings";
+import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
+import { useCompany } from "../../state/company";
+import { useProject } from "../../state/project";
+import { Button } from "../../components/ui/button";
+import { EmptyState } from "../../components/ui/empty-state";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { COMPANY_MODE_ICON } from "../../components/ui/icons";
+import { InfoPopover } from "../../components/ui/info-popover";
+import { Skeleton } from "../../components/ui/skeleton";
+import { orgKey, orgPagePath, resolveOrgLanding } from "./company-nav";
+import { CreateOrganizationDialog, useOrganizationCreated } from "./org-dialogs";
+import { ORG_EXAMPLES } from "./org-examples";
+import { TicketDialogHost } from "./ticket-dialog";
+
+export interface OrgContextValue {
+ projectId: string;
+ orgId: string;
+ /** The organization's summary from the shell's list; null until the list holds it. */
+ org: OrganizationSummary | null;
+}
+
+const OrgContext = createContext<OrgContextValue | null>(null);
+
+export function useOrg(): OrgContextValue {
+ const ctx = useContext(OrgContext);
+ if (!ctx) throw new Error("useOrg must be used within an organization route");
+ return ctx;
+}
+
+/** The scrolling column every organization surface sits in, and the width the narrow pages read best at. */
+function OrgFrame({ wide = false, children }: { wide?: boolean; children: ReactNode }) {
+ return (
+ <div className="h-full overflow-y-auto p-4 md:p-6">
+ <div className={wide ? "min-w-0" : "mx-auto max-w-6xl"}>{children}</div>
+ </div>
+ );
+}
+
+/**
+ * The frame the two organization-less surfaces sit in — the empty landing and the stale deep
+ * link. Each is one short block of guidance with nothing above or below it, so the column
+ * centres it in the window instead of parking it against the top edge, the way the dialogs
+ * are centred. `min-h-full` rather than a fixed centred height: a window shorter than the
+ * block grows the column and scrolls it whole, where `justify-center` alone would push its
+ * top out of reach.
+ */
+function OrgCenteredFrame({ children }: { children: ReactNode }) {
+ return (
+ <div className="h-full overflow-y-auto p-4 md:p-6">
+ <div className="flex min-h-full flex-col justify-center">{children}</div>
+ </div>
+ );
+}
+
+/** `/org` with no organization named. */
+export function OrgIndexRedirect() {
+ const company = useCompany();
+ const { currentProject } = useProject();
+ if (!company.available) return <Navigate to="/chat" replace />;
+ // The list is still on its way: a placeholder page rather than a blank one, so a slow
+ // first load never reads as a broken route.
+ if (!company.orgsLoaded) {
+ return (
+ <OrgFrame>
+ <OrgPageSkeleton />
+ </OrgFrame>
+ );
+ }
+ const target = resolveOrgLanding(
+ company.lastOrgKey,
+ company.organizations,
+ currentProject?.projectId ?? null,
+ );
+ if (target === null) return <OrgEmptyLanding />;
+ // An organization opens on its overview: the one page that says what the whole
+ // organization is doing. Its channels are one click away in the sidebar's own list.
+ return <Navigate to={orgPagePath(target.projectId, target.orgId, "overview")} replace />;
+}
+
+/**
+ * The landing of a user who has no organization anywhere: what one is, the button that makes
+ * one, and three missions worth starting.
+ *
+ * The proposals are the same three the create dialog offers under its mission field, as cards:
+ * a name to recognize the shape of the company by and the mission itself, clamped to three
+ * lines with the whole text in the tooltip. Each opens the dialog already filled in — the
+ * hardest part of an empty landing is not the form, it is having nothing to type into it — and
+ * leaves the id to the field's own generator.
+ *
+ * The cards stretch to one height and lay their content out as a column, so the three names
+ * sit on one line and each mission starts under its own name: a `<button>` centres its own
+ * content vertically, which left the shorter cards' names floating half a line below the
+ * tallest card's.
+ */
+function OrgEmptyLanding() {
+ const company = useCompany();
+ const onOrgCreated = useOrganizationCreated();
+ const [createOpen, setCreateOpen] = useState(false);
+ /** The proposal the dialog opens filled in with; null when the plain create button opened it. */
+ const [picked, setPicked] = useState<{ name: string; mission: string } | null>(null);
+ const openCreate = (example: { name: string; mission: string } | null) => {
+ setPicked(example);
+ setCreateOpen(true);
+ };
+ // Landing on `/org` is a choice of mode like entering an organization is: the sidebar
+ // shows the company shell around this page rather than the development list.
+ const { available, setWorkMode } = company;
+ useEffect(() => {
+ if (available) setWorkMode("company");
+ }, [available, setWorkMode]);
+ return (
+ <OrgCenteredFrame>
+ <div className="mx-auto max-w-2xl py-8 text-center md:py-14">
+ <span className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-300">
+ <GlyphIcon d={COMPANY_MODE_ICON} size={ICON_SIZE.sectionMark + 6} />
+ </span>
+ <h1 className="mt-4 text-2xl font-semibold tracking-tight">{S.company.landingTitle}</h1>
+ <p className="mx-auto mt-2 max-w-xl text-sm text-gray-600 dark:text-gray-300">
+ {S.company.landingBody}
+ </p>
+ <div className="mt-6">
+ <Button variant="primary" onClick={() => openCreate(null)}>
+ {S.company.createOrg}
+ </Button>
+ </div>
+ <ul className="mx-auto mt-10 grid max-w-2xl grid-cols-1 gap-3 text-left sm:grid-cols-2">
+ {ORG_EXAMPLES.map((example) => {
+ const copy = S.company.missionExamples[example.id];
+ return (
+ <li key={example.id} className="min-w-0">
+ <button
+ type="button"
+ title={copy.mission}
+ onClick={() => openCreate(copy)}
+ className="flex h-full w-full flex-col rounded-md border border-gray-200 p-3 text-left transition-colors duration-150 hover:border-gray-300 hover:bg-gray-50 dark:border-gray-800 dark:hover:border-gray-700 dark:hover:bg-gray-800/60"
+ >
+ <span className="block text-sm font-medium">{copy.name}</span>
+ <span className="mt-1 line-clamp-3 block text-xs leading-relaxed text-gray-500 dark:text-gray-400">
+ {copy.mission}
+ </span>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ <CreateOrganizationDialog
+ open={createOpen}
+ {...(picked !== null ? { initial: picked } : {})}
+ onClose={() => setCreateOpen(false)}
+ onCreated={(detail) => {
+ setCreateOpen(false);
+ company.setWorkMode("company");
+ void onOrgCreated(detail);
+ }}
+ />
+ </OrgCenteredFrame>
+ );
+}
+
+/**
+ * The list is settled and the routed organization is not in it: gone, or never reachable —
+ * a bookmark that outlived what it pointed at. The page says so and then offers the two ways
+ * on, rather than leaving the reader on a dead end: make one, or go back to the list (which
+ * lands on another organization, or on the empty landing when there is none).
+ */
+function OrgGone() {
+ const navigate = useNavigate();
+ const onOrgCreated = useOrganizationCreated();
+ const [createOpen, setCreateOpen] = useState(false);
+ return (
+ <OrgCenteredFrame>
+ <EmptyState
+ title={S.company.orgGoneTitle}
+ description={S.company.orgGoneBody}
+ action={
+ <div className="flex flex-wrap items-center justify-center gap-2">
+ <Button variant="primary" onClick={() => setCreateOpen(true)}>
+ {S.company.createOrg}
+ </Button>
+ <Button onClick={() => navigate("/org", { replace: true })}>
+ {S.company.backToOrgs}
+ </Button>
+ </div>
+ }
+ />
+ <CreateOrganizationDialog
+ open={createOpen}
+ onClose={() => setCreateOpen(false)}
+ onCreated={(detail) => {
+ setCreateOpen(false);
+ void onOrgCreated(detail);
+ }}
+ />
+ </OrgCenteredFrame>
+ );
+}
+
+export function OrgLayout() {
+ const params = useParams<{ projectId: string; orgId: string }>();
+ const projectId = params.projectId ?? "";
+ const orgId = params.orgId ?? "";
+ const company = useCompany();
+ const { projects, currentProject, setCurrentProjectId } = useProject();
+ const key = orgKey(projectId, orgId);
+
+ // Entering an organization route is a choice of mode — asserted when the route is entered,
+ // never re-asserted when the mode later changes: the user's own switch to development
+ // navigates away, and re-forcing company mode here would undo the click before this
+ // layout unmounts.
+ const { available, setWorkMode, setCurrentOrg } = company;
+ useEffect(() => {
+ if (available) setWorkMode("company");
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- route entry only, not on every mode change
+ }, [available, key, setWorkMode]);
+
+ // The session list and the Agent set belong to the Project, so it follows the route.
+ const currentProjectId = currentProject?.projectId ?? null;
+ const knownProject = projects.some((p) => p.projectId === projectId);
+ useEffect(() => {
+ if (knownProject && currentProjectId !== null && currentProjectId !== projectId) {
+ setCurrentProjectId(projectId);
+ }
+ }, [knownProject, currentProjectId, projectId, setCurrentProjectId]);
+
+ // The organization stays the shell's current one after these routes unmount: opening a
+ // desk or a ticket session leaves them for `/chat/:sessionId`, and company mode's sidebar
+ // has to keep listing that organization's channels and desks around the conversation.
+ // Leaving company mode is what drops it (CompanyProvider).
+ useEffect(() => {
+ setCurrentOrg(key);
+ }, [key, setCurrentOrg]);
+
+ if (!available) return <Navigate to="/chat" replace />;
+ const org =
+ company.organizations.find((o) => o.projectId === projectId && o.orgId === orgId) ?? null;
+ if (org === null && company.orgsLoaded) return <OrgGone />;
+ return (
+ <OrgContext.Provider value={{ projectId, orgId, org }}>
+ <Outlet />
+ <TicketDialogHost />
+ </OrgContext.Provider>
+ );
+}
+
+/**
+ * The page frame every organization page shares: a scrolling column with the page title,
+ * its "?" (the page's semantics, disclosed on request) and the header actions on one row,
+ * the content below. The organization's name is not repeated in the title — the switcher
+ * above the sidebar already names it; the overview's own hero is the one place it is.
+ */
+export function OrgPage({
+ title,
+ info,
+ actions,
+ wide = false,
+ children,
+}: {
+ title: string;
+ info?: string;
+ actions?: ReactNode;
+ /** Board-shaped pages take the whole width; the rest read better in a column. */
+ wide?: boolean;
+ children: ReactNode;
+}) {
+ return (
+ <OrgFrame wide={wide}>
+ <div className="mb-5 flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
+ <h1 className={`flex min-w-0 items-center ${ICON_GAP.row} text-xl font-semibold`}>
+ {title}
+ {info !== undefined && <InfoPopover label={title}>{info}</InfoPopover>}
+ </h1>
+ {actions !== undefined && (
+ <div className="flex flex-wrap items-center gap-2">{actions}</div>
+ )}
+ </div>
+ {children}
+ </OrgFrame>
+ );
+}
+
+/** A page still fetching: placeholder bands where its header and sections will be. Shown only until the first data (or the first error) arrives. */
+export function OrgPageSkeleton() {
+ return (
+ <div className="space-y-6" aria-busy="true">
+ <Skeleton className="h-20" />
+ <Skeleton className="h-24" />
+ <div className="grid grid-cols-1 gap-8 lg:grid-cols-2">
+ <Skeleton className="h-40" />
+ <Skeleton className="h-40" />
+ </div>
+ </div>
+ );
+}
+
+/**
+ * A ruled section: a small uppercase title with an optional count, its "?" and optional
+ * trailing controls, a rule beneath, then the body. Sections, not cards — the page reads
+ * as one column of titled runs rather than a grid of boxes.
+ */
+export function OrgSection({
+ title,
+ info,
+ count,
+ actions,
+ children,
+ className = "",
+}: {
+ title: string;
+ info?: string;
+ /** How many items the body holds, shown after the title (omit for sections that are not lists). */
+ count?: number;
+ actions?: ReactNode;
+ children: ReactNode;
+ className?: string;
+}) {
+ return (
+ <section className={`min-w-0 ${className}`}>
+ <div className="mb-3 flex items-center justify-between gap-2 border-b border-gray-200 pb-2 dark:border-gray-800">
+ <h2
+ className={`flex min-w-0 items-center ${ICON_GAP.row} text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400`}
+ >
+ {title}
+ {count !== undefined && (
+ <span className="rounded-full bg-gray-100 px-1.5 text-[10px] font-semibold tabular-nums text-gray-500 dark:bg-gray-800 dark:text-gray-400">
+ {count}
+ </span>
+ )}
+ {info !== undefined && <InfoPopover label={title}>{info}</InfoPopover>}
+ </h2>
+ {actions !== undefined && (
+ <div className="flex shrink-0 items-center gap-1.5">{actions}</div>
+ )}
+ </div>
+ {children}
+ </section>
+ );
+}
+
+/** A section with nothing to list: one quiet line where the rows would be. */
+export function OrgEmptyLine({ children }: { children: ReactNode }) {
+ return <p className="py-1 text-xs text-gray-400 dark:text-gray-500">{children}</p>;
+}
diff --git a/packages/web/src/features/company/org-session-groups.tsx b/packages/web/src/features/company/org-session-groups.tsx
new file mode 100644
index 00000000..f231b77f
--- /dev/null
+++ b/packages/web/src/features/company/org-session-groups.tsx
@@ -0,0 +1,391 @@
+/**
+ * The 工位 group under the company sidebar's channel list, and the collapsed rail's twin.
+ *
+ * One row per employee, in chart order, expanded by default: the organization's people are
+ * its primary objects, and a desk is where a person is talked to. Every employee has a desk
+ * session from the moment it is hired, so a row normally carries one; a row whose id these
+ * caches have not learned yet still stands there and opens the desk on click, exactly as the
+ * org chart's card does. Ticket sessions have no group of their own — a session exists
+ * because a ticket started it, and it is read from that ticket's drawer, where the work it
+ * belongs to is on screen beside it.
+ *
+ * A row that names a desk session carries the development list's row menu (right-click, and
+ * the hover ellipsis), pared down to the two actions an organization leaves to the reader:
+ * copy the Session id, and bind the desk to a messaging bot. A desk's title and its lifecycle are
+ * the organization's — the employee names it, hiring and firing open and close it — so
+ * rename, archive, delete and pin are not offered here. The binding's own indicator is read
+ * from the session list store: the organization's sessions route does not carry it.
+ *
+ * The group reads the company store's caches (the organization's chart and its sessions
+ * route), so opening it costs no request; the session the shell is on is marked in place. The
+ * run marks come from the session list's live statuses wherever it holds the row — those
+ * caches are only re-read on an organization event, and a run ending publishes none
+ * (org-sessions.ts).
+ */
+import { useMemo, useState } from "react";
+import { useNavigate } from "react-router";
+import type { MessagingChannel } from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
+import { toneDot, toneInk } from "../../lib/tone";
+import { useCompany } from "../../state/company";
+import { useProject } from "../../state/project";
+import { useLiveSessionStatuses, useSessions } from "../../state/sessions";
+import { AgentAvatar } from "../../components/ui/agent-avatar";
+import { Button } from "../../components/ui/button";
+import { useRowContextMenu } from "../../components/ui/context-menu";
+import { writeClipboard } from "../../components/ui/copy-button";
+import { Dropdown } from "../../components/ui/dropdown";
+import { FolderSection, Icon } from "../../components/ui/group-list";
+import { MESSAGING_RELAY_ICON } from "../../components/ui/icons";
+import { SessionActivityIcon } from "../../components/ui/session-activity-icon";
+import {
+ DESK_ROW_ACTIONS,
+ SessionRowHoverActions,
+ SessionRowMenuRows,
+} from "../../components/ui/session-row-menu";
+import type { SessionRowAction, SessionRowState } from "../../components/ui/session-row-menu";
+import { SkeletonList } from "../../components/ui/skeleton";
+import { toastError, toastSuccess } from "../../components/ui/toast";
+import { Truncated } from "../../components/ui/truncated";
+import { MessagingBindingModal } from "../messaging/messaging-binding-modal";
+import { orgKey } from "./company-nav";
+import { deskRows, orgRowActivity } from "./org-sessions";
+import type { OrgDeskRow } from "./org-sessions";
+
+/**
+ * The row's surface — the hover and active fill — on the wrapper rather than on the button,
+ * so the row's menu affordances sit inside the same lit box the reader is pointing at, and
+ * `group` reaches them.
+ */
+const rowSurface = (active: boolean) =>
+ `group flex select-none items-center rounded-md pr-1 transition-colors duration-150 ${
+ active ? "bg-gray-200/70 dark:bg-gray-800" : "hover:bg-gray-200/50 dark:hover:bg-gray-800/70"
+ }`;
+
+/** The row's own button, at the channel rows' density so the whole sidebar reads as one list. */
+const rowButton = (active: boolean) =>
+ `flex min-w-0 flex-1 items-center ${ICON_GAP.row} px-2.5 py-1.5 text-left text-sm transition-colors duration-150 disabled:opacity-60 ${
+ active ? "font-medium text-gray-900 dark:text-gray-100" : "text-gray-600 dark:text-gray-400"
+ }`;
+
+/**
+ * A desk is neither archivable nor pinnable, so the two toggles the shared menu labels read
+ * are constant here — it offers neither action (DESK_ROW_ACTIONS).
+ */
+const DESK_ROW_STATE: SessionRowState = { archived: false, pinned: false };
+
+/**
+ * Opening a desk: the store's row when one exists, and otherwise the desk endpoint, which
+ * creates it — the same call the org chart's card makes, so the two entry points cannot
+ * disagree about what "open the desk" means.
+ */
+function useOpenDesk(projectId: string, orgId: string, onNavigate?: () => void) {
+ const navigate = useNavigate();
+ const company = useCompany();
+ const { setCurrentAgentId } = useProject();
+ const [opening, setOpening] = useState<string | null>(null);
+
+ /** Opens an existing Session: the current Agent follows it, as every other list does. */
+ const openSession = (sessionId: string, agentId: string) => {
+ if (agentId !== "") setCurrentAgentId(agentId);
+ navigate(`/chat/${sessionId}`);
+ onNavigate?.();
+ };
+
+ const openDesk = async (agentId: string, sessionId: string | null) => {
+ if (opening !== null) return;
+ if (sessionId !== null) {
+ openSession(sessionId, agentId);
+ return;
+ }
+ setOpening(agentId);
+ try {
+ const desk = await api.getOrgDesk(projectId, orgId, agentId);
+ // Freshly created: the row has to learn its Session id to mark itself as the open one.
+ void company.reloadOrgChart();
+ void company.reloadOrgSessions();
+ openSession(desk.sessionId, agentId);
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setOpening(null);
+ }
+ };
+ return { openDesk, opening };
+}
+
+/**
+ * One desk row. The menu hangs off a desk this list knows the id of; while it does not (the
+ * caches have not caught up with a hire, or the desk has yet to be provisioned) there is no
+ * Session to copy or bind, so the row stays a plain button until a click opens one.
+ */
+function DeskRow({
+ row,
+ active,
+ opening,
+ messagingChannel,
+ onOpen,
+ onMessaging,
+}: {
+ row: OrgDeskRow;
+ active: boolean;
+ /** This row's desk is being created right now (the click that creates it is in flight). */
+ opening: boolean;
+ /** The enabled messaging binding of this desk's Session, from the session list store. */
+ messagingChannel: MessagingChannel | undefined;
+ onOpen: () => void;
+ onMessaging: (sessionId: string) => void;
+}) {
+ const ctx = useRowContextMenu();
+ const sessionId = row.sessionId;
+ const activity = orgRowActivity(row.status);
+ const deskName = S.company.sessionList.deskOf(row.name);
+ const label =
+ activity === "running" ? `${deskName} · ${S.company.sessionList.running}` : deskName;
+
+ /** Run one action on this desk's Session, closing the menu first if it was open. */
+ const run = (action: SessionRowAction) => {
+ ctx.close();
+ if (sessionId === null) return;
+ if (action === "messaging") {
+ onMessaging(sessionId);
+ return;
+ }
+ if (action === "copy") {
+ // The panel closes under the click, so the confirmation is a toast rather than
+ // feedback on the row that ran it — the development list's rule for the same action.
+ writeClipboard(sessionId);
+ toastSuccess(S.common.copied);
+ }
+ };
+ /**
+ * Menu items hand focus back to the row before acting: the panel unmounts under the user,
+ * and the menu is the only keyboard route to these actions.
+ */
+ const runFromMenu = (action: SessionRowAction) => {
+ ctx.returnFocus()?.focus();
+ run(action);
+ };
+
+ return (
+ <li>
+ <div
+ ref={sessionId === null ? undefined : ctx.rowRef}
+ // Right-click / Shift+F10 / press-and-hold open the row's menu; the native menu is
+ // suppressed inside that handler only, so the rest of the app keeps the browser's own.
+ {...(sessionId === null ? {} : ctx.rowProps)}
+ className={rowSurface(active)}
+ >
+ <button
+ type="button"
+ aria-current={active ? "true" : undefined}
+ disabled={opening}
+ title={row.jobTitle !== "" ? `${row.name} · ${row.jobTitle}` : row.name}
+ aria-label={label}
+ // A press-and-hold that opened the menu must not also open the desk: touch screens
+ // replay the held press as a click once the finger lifts.
+ onClick={() => {
+ if (ctx.consumeLongPressClick()) return;
+ onOpen();
+ }}
+ className={rowButton(active)}
+ >
+ <AgentAvatar
+ id={row.agentId}
+ name={row.name}
+ size={ICON_SIZE.rowLead}
+ className="shrink-0 rounded"
+ />
+ <Truncated text={row.name} className="min-w-0 flex-1" />
+ {/* Enabled-messaging indicator, the development row's own mark: one glyph for every
+ channel, the channel named in the tooltip and the screen-reader text. */}
+ {messagingChannel !== undefined && (
+ <span
+ title={S.messaging.enabledIndicator[messagingChannel]}
+ className="shrink-0 text-gray-400 dark:text-gray-500"
+ >
+ <Icon d={MESSAGING_RELAY_ICON} size={ICON_SIZE.rowMark} />
+ <span className="sr-only">{S.messaging.enabledIndicator[messagingChannel]}</span>
+ </span>
+ )}
+ {activity !== null && <SessionActivityIcon activity={activity} />}
+ </button>
+ {/* The menu affordance's slot, laid out rather than overlaid and reserved on every row
+ — including a desk that does not exist yet — so the names line up down the group
+ and nothing floats over the run mark. No direct hover action goes in it: a desk has
+ none that is both safe and one click, so it holds the ellipsis alone, which is also
+ the pointer's way into a menu right-click leaves undiscoverable. */}
+ <span className="flex h-6 w-6 shrink-0 items-center justify-center">
+ {sessionId !== null && (
+ <SessionRowHoverActions
+ actions={[]}
+ state={DESK_ROW_STATE}
+ onRun={run}
+ onMore={ctx.openAt}
+ />
+ )}
+ </span>
+ {sessionId !== null && (
+ <>
+ {/* `contents` keeps this wrapper out of the row's flex layout: it draws no box of
+ its own and the panel is portaled against the point the gesture landed on. */}
+ <Dropdown
+ open={ctx.open}
+ setOpen={ctx.setOpen}
+ portal={{ direction: "down", align: "left" }}
+ anchorRect={ctx.anchor}
+ anchorOwner={ctx.anchorOwner}
+ returnFocus={ctx.returnFocus}
+ className="contents"
+ menuClass="w-36"
+ button={null}
+ >
+ <SessionRowMenuRows
+ actions={DESK_ROW_ACTIONS}
+ state={DESK_ROW_STATE}
+ onRun={runFromMenu}
+ />
+ </Dropdown>
+ </>
+ )}
+ </div>
+ </li>
+ );
+}
+
+export function OrgSessionGroups({
+ projectId,
+ orgId,
+ activeSessionId,
+ onNavigate,
+}: {
+ projectId: string;
+ orgId: string;
+ /** The Session the shell is on, so the group can mark it. */
+ activeSessionId: string | null;
+ onNavigate?: () => void;
+}) {
+ const company = useCompany();
+ const [desksOpen, setDesksOpen] = useState(true);
+ /** The desk whose messaging binding is open in the dialog; null when none is. */
+ const [messagingSessionId, setMessagingSessionId] = useState<string | null>(null);
+ const live = useLiveSessionStatuses();
+ const { sessions, replace } = useSessions();
+ // Which desks relay to a bot. The organization's sessions route has no such field, so the
+ // session list store is the only source — a desk it has not loaded simply shows no mark.
+ const messaging = useMemo(() => {
+ const map = new Map<string, MessagingChannel>();
+ for (const s of sessions) {
+ if (s.messagingChannel !== undefined) map.set(s.sessionId, s.messagingChannel);
+ }
+ return map;
+ }, [sessions]);
+ const orgSessions = company.orgSessions.get(orgKey(projectId, orgId));
+ const desks = deskRows(company.orgChart, orgSessions, live);
+ const { openDesk, opening } = useOpenDesk(projectId, orgId, onNavigate);
+ // Nothing has been read for this organization yet: a skeleton, not an "empty" claim.
+ const chartFailed = company.orgChart === null && company.orgChartError !== null;
+ const loading = company.orgChart === null && orgSessions === undefined && !chartFailed;
+
+ return (
+ <div className="mt-1">
+ <FolderSection
+ label={S.company.sessionList.desks(desks.length)}
+ open={desksOpen}
+ onToggle={() => setDesksOpen((v) => !v)}
+ >
+ {loading ? (
+ <SkeletonList rows={2} />
+ ) : chartFailed && desks.length === 0 ? (
+ <div className="flex items-center justify-between gap-2 px-2.5 py-1">
+ <span className={`text-xs ${toneInk.danger}`}>{S.company.sessionList.loadFailed}</span>
+ <Button size="sm" onClick={() => void company.reloadOrgChart()}>
+ {S.common.retry}
+ </Button>
+ </div>
+ ) : desks.length === 0 ? (
+ <p className="px-2.5 py-1 text-xs text-gray-400 dark:text-gray-600">
+ {S.company.sessionList.noEmployees}
+ </p>
+ ) : (
+ <ul className="space-y-0.5">
+ {desks.map((d) => (
+ <DeskRow
+ key={d.agentId}
+ row={d}
+ active={d.sessionId !== null && d.sessionId === activeSessionId}
+ opening={opening === d.agentId}
+ messagingChannel={d.sessionId === null ? undefined : messaging.get(d.sessionId)}
+ onOpen={() => void openDesk(d.agentId, d.sessionId)}
+ onMessaging={setMessagingSessionId}
+ />
+ ))}
+ </ul>
+ )}
+ </FolderSection>
+ {/* Messaging binding dialog (the row menu's "Messaging binding…"): the row's indicator
+ follows the dialog's own save/unbind outcome through the session list store. */}
+ {messagingSessionId !== null && (
+ <MessagingBindingModal
+ sessionId={messagingSessionId}
+ onClose={() => setMessagingSessionId(null)}
+ // The row's Session id comes from the company store's cache of the organization's
+ // sessions route. A desk exists from the hire and the reconcile pass re-opens one
+ // whose session went missing, so a row naming an id the server cannot find should
+ // not happen — but when it does, the cache is what is stale: re-read it, and the
+ // editor's own toast has already said why the dialog closed.
+ onLoadFailed={() => void company.reloadOrgSessions()}
+ onChanged={(sessionId, channel) => {
+ const current = sessions.find((x) => x.sessionId === sessionId);
+ if (!current) return;
+ const updated = { ...current };
+ if (channel !== null) updated.messagingChannel = channel;
+ else delete updated.messagingChannel;
+ replace(updated);
+ }}
+ />
+ )}
+ </div>
+ );
+}
+
+/** The collapsed rail's desks: the same rows as avatars, each with its running dot. */
+export function DeskRailRows({ projectId, orgId }: { projectId: string; orgId: string }) {
+ const company = useCompany();
+ const live = useLiveSessionStatuses();
+ const desks = deskRows(company.orgChart, company.orgSessions.get(orgKey(projectId, orgId)), live);
+ const { openDesk, opening } = useOpenDesk(projectId, orgId);
+ if (desks.length === 0) return null;
+ return (
+ <>
+ {desks.map((d) => {
+ const running = orgRowActivity(d.status) !== null;
+ const name = running
+ ? `${S.company.sessionList.deskOf(d.name)} · ${S.company.sessionList.running}`
+ : S.company.sessionList.deskOf(d.name);
+ return (
+ <button
+ key={d.agentId}
+ type="button"
+ title={name}
+ aria-label={name}
+ disabled={opening === d.agentId}
+ onClick={() => void openDesk(d.agentId, d.sessionId)}
+ className="relative flex h-8 w-8 items-center justify-center rounded-md transition-colors duration-150 hover:bg-gray-200/70 disabled:opacity-60 dark:hover:bg-gray-800"
+ >
+ <AgentAvatar id={d.agentId} name={d.name} size={18} className="rounded" />
+ {running && (
+ <span
+ aria-hidden
+ className={`absolute -right-0.5 -top-0.5 h-1.5 w-1.5 rounded-full ${toneDot.busy}`}
+ />
+ )}
+ </button>
+ );
+ })}
+ </>
+ );
+}
diff --git a/packages/web/src/features/company/org-sessions.ts b/packages/web/src/features/company/org-sessions.ts
new file mode 100644
index 00000000..7307e509
--- /dev/null
+++ b/packages/web/src/features/company/org-sessions.ts
@@ -0,0 +1,166 @@
+/**
+ * The company sidebar's 工位 group, as pure shaping (unit tested) over the organization's
+ * chart, its sessions route and the session list's live statuses: one row per EMPLOYEE, in
+ * chart order, whether or not these caches already name its desk session. The roster is the
+ * chart's (the sessions route only knows employees whose desk is in the ledger); the state is
+ * the live one where the session list holds the row.
+ *
+ * The employees' own states (the chart's dots, the overview's counts) are corrected the same
+ * way by `liveEmployeeStates` at the bottom of this file, which reads the sessions attached to
+ * tickets too — a ticket session running is its employee running, even though the sidebar
+ * lists no ticket sessions of its own (they are reached from the ticket that started them).
+ *
+ * Both take their run state from the LIVE statuses first, because the two snapshots behind
+ * them only move on an organization event: the sessions route is re-read when a run is
+ * dispatched (`org_run`) or a ticket moves, and the chart when a summary does — and a run
+ * ENDING publishes none of those. A desk would sit on 「运行中」 until some unrelated event
+ * happened to arrive. The session list's own statuses come from the user event channel, which
+ * reports every flip of every Session, so they are the state that is actually current; the
+ * snapshots stand in for the rows that list has not loaded.
+ */
+import type {
+ OrgChartResponse,
+ OrgEmployeeState,
+ OrgSessionsResponse,
+ SessionStatus,
+} from "@prismshadow/penguin-server/api";
+import type { SessionActivity } from "../../lib/session-activity";
+
+/**
+ * Live run statuses by Session id — the session list store's view of them (state/sessions.tsx),
+ * which the user event channel keeps in step. A Session the list has not loaded is simply
+ * absent, and the caller falls back to the snapshot it does have.
+ */
+export type LiveSessionStatuses = ReadonlyMap<string, SessionStatus>;
+
+/**
+ * One employee's desk row. `sessionId` is null only while neither cache names the employee's
+ * desk — the server opens one at hire time and re-opens a missing one on its next pass, so
+ * this is the window between a hire and the next read of the chart or the sessions route.
+ */
+export interface OrgDeskRow {
+ agentId: string;
+ /** The employee's display name — the row title, whatever the session's own title says. */
+ name: string;
+ /** The employee's job title, shown as the row's tooltip. */
+ jobTitle: string;
+ sessionId: string | null;
+ status: SessionStatus;
+}
+
+/**
+ * Desk rows in chart order — the reporting line, which is how the organization reads. The
+ * chart is the roster; the run state comes from the live statuses, then from the sessions
+ * route's snapshot, then from the chart's own `state` — a desk the sessions route has not
+ * listed yet (it was opened between the two reads) still shows that it is running. Without a
+ * chart yet (the first read of an organization) the sessions route stands in: it walks the
+ * same chart server-side, so the order holds and only employees without a desk are missing
+ * until the chart lands.
+ */
+export function deskRows(
+ chart: OrgChartResponse | null,
+ sessions: OrgSessionsResponse | undefined,
+ live?: LiveSessionStatuses,
+): OrgDeskRow[] {
+ const snapshot = new Map((sessions?.desks ?? []).map((d) => [d.agentId, d]));
+ if (chart === null) {
+ return (sessions?.desks ?? []).map((d) => ({
+ agentId: d.agentId,
+ name: d.name,
+ jobTitle: "",
+ sessionId: d.sessionId,
+ status: live?.get(d.sessionId) ?? d.status,
+ }));
+ }
+ return chart.employees.map((e) => {
+ const desk = snapshot.get(e.agentId);
+ const sessionId = desk?.sessionId ?? e.desk?.sessionId ?? null;
+ const liveStatus = sessionId === null ? undefined : live?.get(sessionId);
+ return {
+ agentId: e.agentId,
+ name: e.name,
+ jobTitle: e.title,
+ sessionId,
+ status: liveStatus ?? desk?.status ?? (e.state === "running" ? "running" : "idle"),
+ };
+ });
+}
+
+/**
+ * The glyph a desk row draws: the same live states the ordinary session list shows (an
+ * hourglass while running, the squeeze while compacting), and nothing when settled — a desk
+ * row has no read marker of its own, so it never claims "unread".
+ */
+export function orgRowActivity(status: SessionStatus): SessionActivity {
+ if (status === "running") return "running";
+ if (status === "compacting") return "compacting";
+ return null;
+}
+
+/**
+ * One employee's run state, from the Sessions the organization attributes to it: running while
+ * any of them is running or compacting, idle once all of them have settled, and — when nothing
+ * is known about any of them — the state the chart itself reported.
+ *
+ * Each Session is judged by the live status where the list holds it and by the organization's
+ * own snapshot otherwise, which is exactly how the desk and ticket rows draw their marks, so
+ * the chart and the sidebar can never say different things about the same run.
+ *
+ * `paused` is not a run state — the budget stopped the employee, and no Session can say
+ * otherwise — so it is returned untouched.
+ */
+function employeeLiveState(
+ state: OrgEmployeeState,
+ own: ReadonlyArray<{ sessionId: string; status?: SessionStatus }>,
+ live: LiveSessionStatuses | undefined,
+): OrgEmployeeState {
+ if (state === "paused") return "paused";
+ let known = false;
+ for (const session of own) {
+ const status = live?.get(session.sessionId) ?? session.status;
+ if (status === undefined) continue;
+ known = true;
+ if (status === "running" || status === "compacting") return "running";
+ }
+ return known ? "idle" : state;
+}
+
+/**
+ * The employees' run states corrected by the live session list, by agent id — what the org
+ * chart's dots and the overview's counts draw instead of the chart's own `state`.
+ *
+ * An employee's Sessions are its desk (named by the chart's entry and by the sessions route,
+ * which may know one the other does not yet) and every session attached to a ticket it is
+ * working. Both snapshots are re-read only on an organization event, and a run ending
+ * publishes none of those, so an employee that finished kept its running dot until something
+ * unrelated moved.
+ */
+export function liveEmployeeStates<
+ T extends { agentId: string; state: OrgEmployeeState; desk?: { sessionId: string } },
+>(
+ employees: readonly T[],
+ sessions: OrgSessionsResponse | undefined,
+ live?: LiveSessionStatuses,
+): ReadonlyMap<string, OrgEmployeeState> {
+ const deskOf = new Map((sessions?.desks ?? []).map((d) => [d.agentId, d]));
+ const ticketsOf = new Map<string, Array<{ sessionId: string; status: SessionStatus }>>();
+ for (const t of sessions?.tickets ?? []) {
+ for (const s of t.sessions) {
+ const entry = { sessionId: s.sessionId, status: s.status };
+ const list = ticketsOf.get(s.agentId);
+ if (list) list.push(entry);
+ else ticketsOf.set(s.agentId, [entry]);
+ }
+ }
+ const out = new Map<string, OrgEmployeeState>();
+ for (const e of employees) {
+ const desk = deskOf.get(e.agentId);
+ const own: Array<{ sessionId: string; status?: SessionStatus }> = [];
+ // The chart's own desk id carries no status: it contributes only what the live list says.
+ if (e.desk !== undefined) own.push({ sessionId: e.desk.sessionId });
+ if (desk !== undefined) own.push({ sessionId: desk.sessionId, status: desk.status });
+ own.push(...(ticketsOf.get(e.agentId) ?? []));
+ out.set(e.agentId, employeeLiveState(e.state, own, live));
+ }
+ return out;
+}
diff --git a/packages/web/src/features/company/org-switcher.tsx b/packages/web/src/features/company/org-switcher.tsx
new file mode 100644
index 00000000..dcde0c1f
--- /dev/null
+++ b/packages/web/src/features/company/org-switcher.tsx
@@ -0,0 +1,268 @@
+/**
+ * The organization switcher that stands where the Project switcher stands in development
+ * mode. The trigger names the open organization with its status dot and, beneath it, the
+ * Project it belongs to; the menu lists every organization the user can reach, grouped by
+ * Project with a check mark on the open one (picking one opens its overview), then the two
+ * entries that make and shape one — "New organization" (success makes the new organization
+ * the shell's current one and lands in its CEO's desk session) and "Organization settings".
+ * Same Dropdown, same menu rows as the Project switcher, so the two modes read as one shell.
+ *
+ * Beside it lives what the sidebar shows in place of a channel list while the user has no
+ * organization at all — the same create dialog, reached from the slot where the list would be.
+ */
+import { useState } from "react";
+import { useNavigate } from "react-router";
+import { S } from "../../lib/strings";
+import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
+import { toneSurface } from "../../lib/tone";
+import { useCompany } from "../../state/company";
+import { projectDisplayName, useProject } from "../../state/project";
+import { Dropdown } from "../../components/ui/dropdown";
+import { Badge } from "../../components/ui/badge";
+import { Button } from "../../components/ui/button";
+import { SkeletonList } from "../../components/ui/skeleton";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { CheckIcon, ChevronDown, GEAR_ICON, PlusIcon } from "../../components/ui/icons";
+import { groupOrganizationsByProject, orgKey, orgPagePath, parseOrgKey } from "./company-nav";
+import {
+ CreateOrganizationDialog,
+ OrganizationSettingsDialog,
+ useOrganizationCreated,
+} from "./org-dialogs";
+import { OrgStatusDot } from "./shared";
+
+const menuItemClass = `flex w-full items-center ${ICON_GAP.menu} px-3.5 py-2 text-left text-sm transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800`;
+
+export function OrgSwitcher({ onNavigate }: { onNavigate?: () => void }) {
+ const navigate = useNavigate();
+ const company = useCompany();
+ const onOrgCreated = useOrganizationCreated();
+ const { projects } = useProject();
+ const [open, setOpen] = useState(false);
+ const [createOpen, setCreateOpen] = useState(false);
+ const [settingsOpen, setSettingsOpen] = useState(false);
+
+ const current = company.currentOrg;
+ const currentKey = company.currentOrgKey ?? company.lastOrgKey;
+ const projectName = (projectId: string) => {
+ const p = projects.find((x) => x.projectId === projectId);
+ return p ? projectDisplayName(p) : projectId;
+ };
+ const groups = groupOrganizationsByProject(
+ company.organizations,
+ projects.map((p) => p.projectId),
+ );
+ const settingsTarget = parseOrgKey(currentKey);
+
+ const go = (to: string) => {
+ navigate(to);
+ onNavigate?.();
+ };
+
+ const triggerTitle =
+ current !== null
+ ? S.company.inProject(projectName(current.projectId), current.name)
+ : S.company.switcher;
+ /**
+ * What is waiting in this organization's channels, summed over the ones the user belongs
+ * to: mentions first, since they are addressed to it. The list below carries the same
+ * numbers per channel — this is the copy that survives the list being scrolled away, and
+ * the only one on a phone before the drawer is opened.
+ */
+ const channelNote =
+ company.channelMentions > 0
+ ? S.company.channels.badgeMentions(company.channelMentions)
+ : company.channelUnread > 0
+ ? S.company.channels.badgeUnread(company.channelUnread)
+ : null;
+ const triggerLabel = channelNote !== null ? `${triggerTitle} · ${channelNote}` : triggerTitle;
+
+ return (
+ <>
+ <Dropdown
+ open={open}
+ setOpen={setOpen}
+ className="min-w-0 flex-1"
+ menuClass="left-0 right-0 top-full mt-1 origin-top"
+ button={
+ <button
+ type="button"
+ onClick={() => setOpen(!open)}
+ title={triggerLabel}
+ // The count beside the name renders aria-hidden — it is a bare `@3` — so the
+ // accessible name has to carry the same fact in words.
+ aria-label={triggerLabel}
+ aria-haspopup="menu"
+ aria-expanded={open}
+ className="flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left transition-colors duration-150 hover:bg-gray-200/70 dark:hover:bg-gray-800"
+ >
+ <span className="min-w-0 flex-1">
+ <span className={`flex items-center ${ICON_GAP.row}`}>
+ {current !== null && <OrgStatusDot org={current} />}
+ <span className="min-w-0 truncate text-base font-semibold leading-tight">
+ {current !== null
+ ? current.name
+ : company.orgsLoaded
+ ? S.company.noOrganizations
+ : S.common.loading}
+ </span>
+ </span>
+ {/* The Project the organization belongs to: the second line, so the name stays the headline. */}
+ {current !== null && (
+ <span className="block truncate text-[11px] leading-tight text-gray-500 dark:text-gray-400">
+ {projectName(current.projectId)}
+ </span>
+ )}
+ </span>
+ {channelNote !== null && (
+ <span
+ aria-hidden
+ className={`shrink-0 rounded-full px-1.5 text-[10px] font-semibold tabular-nums ${
+ company.channelMentions > 0
+ ? toneSurface.attention
+ : "bg-gray-200 text-gray-700 dark:bg-gray-700 dark:text-gray-200"
+ }`}
+ >
+ {company.channelMentions > 0
+ ? `@${company.channelMentions}`
+ : company.channelUnread}
+ </span>
+ )}
+ <span className="text-gray-400">
+ <ChevronDown />
+ </span>
+ </button>
+ }
+ >
+ {groups.map((group) => (
+ <div key={group.projectId} role="group" aria-label={projectName(group.projectId)}>
+ <p className="px-3.5 pb-0.5 pt-2 text-[11px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500">
+ {projectName(group.projectId)}
+ </p>
+ {group.organizations.map((o) => {
+ const key = orgKey(o.projectId, o.orgId);
+ const active = key === currentKey;
+ return (
+ <button
+ key={key}
+ type="button"
+ title={S.company.inProject(projectName(o.projectId), o.name)}
+ aria-current={active ? "true" : undefined}
+ onClick={() => {
+ setOpen(false);
+ go(orgPagePath(o.projectId, o.orgId, "overview"));
+ }}
+ className={`${menuItemClass} ${active ? "font-semibold" : ""}`}
+ >
+ <OrgStatusDot org={o} />
+ <span className="min-w-0 flex-1 truncate">{o.name}</span>
+ {o.invalid !== undefined ? (
+ <Badge tone="red">{S.company.orgInvalid}</Badge>
+ ) : o.status === "paused" ? (
+ <Badge tone="amber">{S.company.orgPaused}</Badge>
+ ) : null}
+ {active && (
+ <span className="shrink-0 text-gray-500 dark:text-gray-400">
+ <CheckIcon />
+ <span className="sr-only">{S.company.switcherCurrent}</span>
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ ))}
+ {groups.length === 0 && (
+ <p className="px-3.5 py-2 text-sm text-gray-400 dark:text-gray-500">
+ {company.orgsLoaded ? S.company.noOrganizations : S.common.loading}
+ </p>
+ )}
+ <div className="mt-1.5 border-t border-gray-100 pt-1.5 dark:border-gray-800">
+ <button
+ type="button"
+ className={menuItemClass}
+ onClick={() => {
+ setOpen(false);
+ setCreateOpen(true);
+ }}
+ >
+ <span className="shrink-0 text-gray-400 dark:text-gray-500">
+ <PlusIcon size={ICON_SIZE.rowLead} />
+ </span>
+ {S.company.createOrg}
+ </button>
+ {settingsTarget !== null && (
+ <button
+ type="button"
+ className={menuItemClass}
+ onClick={() => {
+ setOpen(false);
+ setSettingsOpen(true);
+ }}
+ >
+ <span className="shrink-0 text-gray-400 dark:text-gray-500">
+ <GlyphIcon d={GEAR_ICON} size={ICON_SIZE.rowLead} />
+ </span>
+ {S.company.orgSettings}
+ </button>
+ )}
+ </div>
+ </Dropdown>
+
+ <CreateOrganizationDialog
+ open={createOpen}
+ onClose={() => setCreateOpen(false)}
+ onCreated={(detail) => {
+ setCreateOpen(false);
+ // Creation opens the CEO's desk: land in it so the mission conversation starts now,
+ // with the shell already inside the organization that desk belongs to.
+ void onOrgCreated(detail).then(() => onNavigate?.());
+ }}
+ />
+ {settingsTarget !== null && (
+ <OrganizationSettingsDialog
+ open={settingsOpen}
+ projectId={settingsTarget.projectId}
+ orgId={settingsTarget.orgId}
+ onClose={() => setSettingsOpen(false)}
+ onChanged={() => void company.reloadOrganizations()}
+ />
+ )}
+ </>
+ );
+}
+
+/**
+ * The sidebar's list slot while the user has no organization anywhere: one quiet line and
+ * the button that fixes it, in place of a channel list that would have nothing to list (and
+ * of the load failure a listing for a deleted organization used to leave there). The six
+ * page rows above stay put, disabled — the shell keeps its shape rather than collapsing into
+ * something that reads as broken.
+ */
+export function NoOrganizationsSidebar({ onNavigate }: { onNavigate?: () => void }) {
+ const company = useCompany();
+ const onOrgCreated = useOrganizationCreated();
+ const [createOpen, setCreateOpen] = useState(false);
+ // "No organization" is only true once the list has settled; before that it is a guess, and
+ // a guess that flashes a call to action is worse than a placeholder.
+ if (!company.orgsLoaded) return <SkeletonList rows={3} />;
+ return (
+ <div className="mt-3 space-y-2 px-2.5 pt-2">
+ <p className="text-xs text-gray-400 dark:text-gray-500">{S.company.noOrganizations}</p>
+ {/* A quiet secondary button: every empty page beside this list (the landing, the
+ organization-gone page) carries the primary "New organization" itself, so this one
+ only covers the pages that do not. */}
+ <Button size="sm" onClick={() => setCreateOpen(true)}>
+ {S.company.createOrg}
+ </Button>
+ <CreateOrganizationDialog
+ open={createOpen}
+ onClose={() => setCreateOpen(false)}
+ onCreated={(detail) => {
+ setCreateOpen(false);
+ void onOrgCreated(detail).then(() => onNavigate?.());
+ }}
+ />
+ </div>
+ );
+}
diff --git a/packages/web/src/features/company/overview-page.tsx b/packages/web/src/features/company/overview-page.tsx
new file mode 100644
index 00000000..86f84f91
--- /dev/null
+++ b/packages/web/src/features/company/overview-page.tsx
@@ -0,0 +1,841 @@
+/**
+ * The organization's overview, a calm dashboard: a hero naming the organization (its status
+ * pill, the line of metadata and the mission folded to one line), a KPI strip — employees
+ * (on desk / running / paused), the board as a segmented bar with its blocked count, today's
+ * calendar, and this period's spend as the ring beside the amount with the budget bar under
+ * it — and then three full-width runs, one under the other: the inbox (what names the reader,
+ * what is stuck and what has landed, newest first), today's timeline with each instance's
+ * outcome, and the budget alerts. Each reading is stated once: the spend lives in its KPI cell
+ * alone, and nothing on this page is clickable as a whole — no card, no row, no heading. Every
+ * jump is a named control: in the three lists the row's title is the link (a text button, the
+ * rest of the row inert), and where there is no title to click — a KPI cell, the counts under
+ * the board bar — a named corner button carries it. The controls inside a card stay clickable,
+ * and the destination is read rather than guessed.
+ * The overview is the one page whose rows cross into another menu — it is the dashboard, and
+ * its readings are links to where each lives: today's schedule to the calendar, a budget alert
+ * to finance, an inbox line to the channel it was said in. A ticket is the exception in the
+ * other direction: it opens as the detail dialog, in place, like everywhere else.
+ * A brand-new organization (nobody hired, empty board) gets the three-step guide in place of
+ * the sections, and the header then drops its "open the CEO's desk" button: the guide's first
+ * step is that same call to action, and one screen carries a control once.
+ *
+ * Loading discipline: the skeleton shows only until the first response or the first error;
+ * a failed refresh keeps what was last read on screen under one error line with its retry.
+ */
+import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from "react";
+import type { ReactNode } from "react";
+import { useNavigate } from "react-router";
+import type {
+ OrgChartResponse,
+ OrgTicketStatus,
+ OrganizationDetail,
+} from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { formatDateTime, formatMoney, formatRelativeShort } from "../../lib/format";
+import { useDocumentTitle } from "../../lib/use-document-title";
+import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
+import { toneDot, toneInk, toneSurface } from "../../lib/tone";
+import type { Tone } from "../../lib/tone";
+import { useCompany } from "../../state/company";
+import { useLocale } from "../../state/locale";
+import { useLiveSessionStatuses } from "../../state/sessions";
+import { useTheme } from "../../state/theme";
+import { Button } from "../../components/ui/button";
+import { Badge } from "../../components/ui/badge";
+import { Chevron } from "../../components/ui/chevron";
+import { EmptyState } from "../../components/ui/empty-state";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { NAV_ICONS } from "../../components/ui/icons";
+import { Segmented } from "../../components/ui/segmented";
+import { toastError } from "../../components/ui/toast";
+import { STAT_ICONS } from "../../lib/stat-icons";
+import { orgChannelPath, orgKey, orgPagePath } from "./company-nav";
+import type { CompanyNavKey } from "./company-nav";
+import { CHANNEL_ICON } from "./channel-sidebar";
+import { OrgEmptyLine, OrgPage, OrgPageSkeleton, OrgSection, useOrg } from "./org-layout";
+import {
+ BudgetBar,
+ ErrorLine,
+ JumpButton,
+ OrgStatusPill,
+ PrincipalChip,
+ SpendRing,
+ TitleButton,
+ principalLabel,
+} from "./shared";
+import { agentPrincipal } from "./principals";
+import { liveEmployeeStates } from "./org-sessions";
+import { timeLabel } from "./calendar-geom";
+import {
+ BOARD_SEGMENT_TONE,
+ FIRST_STEPS,
+ INBOX_FILTERS,
+ TIMELINE_TONE,
+ boardSummary,
+ employeeCounts,
+ firstSteps,
+ inboxCounts,
+ inboxMatches,
+ inboxRows,
+ missionClampedGuess,
+ spendSummary,
+ todaySummary,
+} from "./overview-summary";
+import type {
+ FirstStep,
+ InboxCategory,
+ InboxFilter,
+ InboxRow,
+ InboxTarget,
+ TimelineMark,
+} from "./overview-summary";
+
+/** How many of today's instances the timeline shows before pointing at the calendar. */
+const TIMELINE_ROWS = 6;
+
+/** The mark that leads an inbox row: the channel hash for what was said, the board's glyph for a ticket. */
+const INBOX_ICON: Record<InboxCategory, string> = {
+ mention: CHANNEL_ICON,
+ blocked: NAV_ICONS.orgTickets,
+ done: NAV_ICONS.orgTickets,
+};
+
+/**
+ * A row of a section: full width, the content decides the rest. The row is inert — it carries
+ * no click of its own and no hover wash that would imply one; where it leads somewhere, its
+ * title is the only thing that goes there.
+ */
+const rowClass = "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm";
+
+/** A small tone-marked count: the dot, the label, the number. */
+function ToneCount({ tone, label, value }: { tone: Tone; label: string; value: number }) {
+ return (
+ <span className={`inline-flex items-center ${ICON_GAP.tight}`} title={label}>
+ <span className={`block h-1.5 w-1.5 rounded-full ${toneDot[tone]}`} />
+ <span>{label}</span>
+ <span className="font-semibold tabular-nums text-gray-700 dark:text-gray-200">{value}</span>
+ </span>
+ );
+}
+
+/** The bar segments' fills: the ticket status badges' tones, with done as the heavier neutral its badge wears. */
+const BOARD_FILL: Record<OrgTicketStatus, string> = {
+ proposed: toneDot.muted,
+ in_progress: toneDot.busy,
+ review: toneDot.attention,
+ done: "bg-gray-500 dark:bg-gray-400",
+ rejected: toneDot.danger,
+};
+
+/** The label of a timeline mark: the calendar's own outcome names, plus "upcoming". */
+function markLabel(mark: TimelineMark): string {
+ return mark === "upcoming"
+ ? S.company.overview.upcoming
+ : (S.company.calendarOutcomes[mark] ?? mark);
+}
+
+/**
+ * The label row of a summary block: its name, and the one button that opens the page the
+ * block summarizes. Every KPI cell wears it, so the corner button sits in the same place in
+ * all of them.
+ */
+function SummaryLabel({
+ label,
+ jump,
+ onJump,
+}: {
+ label: string;
+ /** The corner button's name — where it goes, e.g. "Open the org chart". */
+ jump: string;
+ onJump: () => void;
+}) {
+ return (
+ <div className="flex items-start justify-between gap-2">
+ <span className="block text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
+ {label}
+ </span>
+ <JumpButton label={jump} onClick={onJump} />
+ </div>
+ );
+}
+
+/**
+ * One cell of the KPI strip: its label with the corner button, the headline number, and the
+ * detail line under it. The cell is a plain card rather than a link — several cells carry
+ * their own controls in the detail, which a card-wide click would swallow, and a card that is
+ * silently clickable never says where the click lands.
+ */
+function KpiCell({
+ label,
+ value,
+ detail,
+ jump,
+ onJump,
+}: {
+ label: string;
+ value: ReactNode;
+ detail: ReactNode;
+ jump: string;
+ onJump: () => void;
+}) {
+ return (
+ <div className="flex min-h-28 flex-col justify-between bg-white px-4 py-3 dark:bg-gray-950">
+ <div>
+ <SummaryLabel label={label} jump={jump} onJump={onJump} />
+ <span className="mt-1 block text-2xl font-semibold leading-none tabular-nums">{value}</span>
+ </div>
+ <div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-500 dark:text-gray-400">
+ {detail}
+ </div>
+ </div>
+ );
+}
+
+/**
+ * The organization's mission under the hero's metadata line: a label, one clamped line, and
+ * the chevron that opens it. Missions run to paragraphs, and a hero that prints one whole
+ * pushes the dashboard itself below the fold. Collapsed on every visit — the mission is read
+ * once, not tracked — so nothing is persisted.
+ *
+ * Whether the toggle is offered at all is a measurement (`scrollHeight > clientHeight` on the
+ * clamped paragraph, re-taken on resize), seeded by a guess from the text so the toggle does
+ * not flicker in after the first paint. The measurement only holds while collapsed: unclamped,
+ * the two heights are equal and re-measuring would take the toggle away mid-read.
+ */
+function MissionFold({ mission }: { mission: string }) {
+ const [expanded, setExpanded] = useState(false);
+ const [overflows, setOverflows] = useState(() => missionClampedGuess(mission));
+ const textRef = useRef<HTMLParagraphElement>(null);
+ const bodyId = useId();
+ useLayoutEffect(() => {
+ if (expanded) return;
+ const el = textRef.current;
+ if (el === null) return;
+ // A sub-pixel line height leaves the two heights a fraction apart on a text that fits.
+ const measure = () => setOverflows(el.scrollHeight > el.clientHeight + 1);
+ measure();
+ window.addEventListener("resize", measure);
+ return () => window.removeEventListener("resize", measure);
+ }, [expanded, mission]);
+ if (mission.trim() === "") return null;
+ const toggle = expanded ? S.company.overview.collapse : S.company.overview.expand;
+ return (
+ <div className="mt-3 max-w-3xl">
+ <p className="text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
+ {S.company.overview.mission}
+ </p>
+ <div className="mt-0.5 flex items-baseline gap-3">
+ <p
+ ref={textRef}
+ id={bodyId}
+ className={`min-w-0 flex-1 text-sm text-gray-600 dark:text-gray-300 ${
+ expanded ? "whitespace-pre-line" : "line-clamp-1"
+ }`}
+ >
+ {mission}
+ </p>
+ {overflows && (
+ <button
+ type="button"
+ onClick={() => setExpanded((v) => !v)}
+ title={toggle}
+ aria-expanded={expanded}
+ aria-controls={bodyId}
+ className={`inline-flex shrink-0 items-center ${ICON_GAP.tight} rounded text-xs text-gray-500 transition-colors duration-150 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200`}
+ >
+ {toggle}
+ <Chevron open={expanded} size={ICON_SIZE.chevronDense} />
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+/**
+ * An inbox row's state dot: attention while the row needs the reader, muted once it is only
+ * news. Nothing here rests on the colour alone — every row wears the chip that names its
+ * category beside it.
+ */
+function InboxDot({ row }: { row: InboxRow }) {
+ return (
+ <span className="flex shrink-0 items-center">
+ <span aria-hidden className={`block h-1.5 w-1.5 rounded-full ${toneDot[row.tone]}`} />
+ </span>
+ );
+}
+
+/** One step of the first-steps guide: its number (a check once done), title, what to do, and the button that does it. */
+function StepCard({
+ index,
+ done,
+ current,
+ title,
+ body,
+ action,
+}: {
+ index: number;
+ done: boolean;
+ current: boolean;
+ title: string;
+ body: string;
+ action: ReactNode;
+}) {
+ return (
+ <li
+ className={`flex flex-col gap-2 rounded-md border p-4 ${
+ current ? "border-gray-300 dark:border-gray-700" : "border-gray-200 dark:border-gray-800"
+ }`}
+ >
+ <span className={`flex items-center ${ICON_GAP.menu}`}>
+ <span
+ className={`flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-xs font-semibold ${
+ done
+ ? toneSurface.success
+ : current
+ ? "bg-gray-900 text-white dark:bg-gray-100 dark:text-gray-900"
+ : "bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-400"
+ }`}
+ >
+ {done ? <GlyphIcon d={STAT_ICONS.check} size={ICON_SIZE.inlineGlyph} /> : index}
+ </span>
+ <span className="text-sm font-medium">{title}</span>
+ </span>
+ <p className="flex-1 text-xs text-gray-500 dark:text-gray-400">{body}</p>
+ <span className="flex items-center justify-between gap-2">
+ {done ? (
+ <span className={`text-xs ${toneInk.success}`}>{S.company.overview.stepDone}</span>
+ ) : (
+ <span />
+ )}
+ {action}
+ </span>
+ </li>
+ );
+}
+
+export function OverviewPage() {
+ const { projectId, orgId, org } = useOrg();
+ const navigate = useNavigate();
+ const company = useCompany();
+ const { currency } = useTheme();
+ const { locale } = useLocale();
+ const liveStatuses = useLiveSessionStatuses();
+ useDocumentTitle(org ? `${org.name} · ${S.nav.org.overview}` : S.nav.org.overview);
+ const [detail, setDetail] = useState<OrganizationDetail | null>(null);
+ const [chart, setChart] = useState<OrgChartResponse | null>(null);
+ /** The whole calendar's size, read only while the organization is fresh (today's slice says nothing about next week). */
+ const [calendarCount, setCalendarCount] = useState<number | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [openingDesk, setOpeningDesk] = useState(false);
+ /** The inbox chip in force; local to the visit, as a filter over one section should be. */
+ const [inboxFilter, setInboxFilter] = useState<InboxFilter>("all");
+
+ // Another organization's data must not linger while this one loads.
+ useEffect(() => {
+ setDetail(null);
+ setChart(null);
+ setCalendarCount(null);
+ setError(null);
+ }, [projectId, orgId]);
+
+ const load = useCallback(async () => {
+ try {
+ const [d, c] = await Promise.all([
+ api.getOrganization(projectId, orgId),
+ api.getOrgChart(projectId, orgId),
+ ]);
+ setDetail(d);
+ setChart(c);
+ setError(null);
+ if (
+ firstSteps({
+ employeeCount: c.employees.length,
+ boardTotal: boardSummary(d.board).total,
+ ceoDeskOpened: d.ceoDeskSessionId !== undefined,
+ calendarCount: 0,
+ }).fresh
+ ) {
+ // Best effort: an unreadable calendar only leaves the third step unticked.
+ try {
+ setCalendarCount((await api.listOrgCalendar(projectId, orgId)).events.length);
+ } catch {
+ setCalendarCount(null);
+ }
+ }
+ } catch (e) {
+ setError(apiErrorText(e));
+ }
+ }, [projectId, orgId]);
+
+ // Every event family moves something on this page: reload on any of them.
+ const { messages, tickets, runs, budget } = company.versions;
+ useEffect(() => {
+ void load();
+ }, [load, messages, tickets, runs, budget]);
+
+ const page = (key: CompanyNavKey, query = "") =>
+ navigate(`${orgPagePath(projectId, orgId, key)}${query}`);
+ /**
+ * Where an inbox row leads: a ticket opens as the dialog over this page, while what was said
+ * in a channel opens the channel — a conversation is a place, not a detail.
+ */
+ const openInboxRow = (target: InboxTarget) => {
+ if (target.kind === "ticket") company.openTicket(projectId, orgId, target.ticketId);
+ else navigate(orgChannelPath(projectId, orgId, target.channelId));
+ };
+
+ const openCeoDesk = async () => {
+ if (chart === null || openingDesk) return;
+ setOpeningDesk(true);
+ try {
+ const desk = await api.getOrgDesk(projectId, orgId, chart.ceoAgentId);
+ navigate(`/chat/${desk.sessionId}`);
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setOpeningDesk(false);
+ }
+ };
+
+ const title = S.nav.org.overview;
+ const info = S.company.overview.info;
+
+ if (detail === null || chart === null) {
+ return (
+ <OrgPage title={title} info={info}>
+ {error !== null ? (
+ <EmptyState
+ title={error}
+ action={<Button onClick={() => void load()}>{S.common.retry}</Button>}
+ />
+ ) : (
+ <OrgPageSkeleton />
+ )}
+ </OrgPage>
+ );
+ }
+
+ // Who is actually working: the session list's live statuses, since the chart's own `state`
+ // only moves on an organization event and a run ending publishes none.
+ const counts = employeeCounts(
+ chart.employees,
+ liveEmployeeStates(
+ chart.employees,
+ company.orgSessions.get(orgKey(projectId, orgId)),
+ liveStatuses,
+ ),
+ );
+ const board = boardSummary(detail.board);
+ const today = todaySummary(detail.today);
+ const spend = spendSummary(detail.spend);
+ const steps = firstSteps({
+ employeeCount: chart.employees.length,
+ boardTotal: board.total,
+ ceoDeskOpened: detail.ceoDeskSessionId !== undefined,
+ calendarCount: calendarCount ?? 0,
+ });
+ const names = new Map(chart.employees.map((e) => [e.agentId, e.name]));
+ const inbox = inboxRows({
+ inbox: detail.inbox,
+ names: (principal) => principalLabel(principal, names),
+ });
+ const inboxTotals = inboxCounts(inbox);
+ const visibleInbox = inbox.filter((row) => inboxMatches(row, inboxFilter));
+ const ceoName = names.get(chart.ceoAgentId) ?? chart.ceoAgentId;
+
+ const deskButton = (variant: "primary" | "secondary", size: "sm" | "md") => (
+ <Button
+ size={size}
+ variant={variant}
+ disabled={openingDesk}
+ onClick={() => void openCeoDesk()}
+ title={`${ceoName} · ${S.company.openDesk}`}
+ >
+ {openingDesk ? S.company.openingDesk : S.company.overview.openCeoDesk}
+ </Button>
+ );
+
+ const stepAction = (step: FirstStep, current: boolean) => {
+ const variant = current ? "primary" : "secondary";
+ if (step === "ceo") return deskButton(variant, "sm");
+ if (step === "hire") {
+ return (
+ <Button size="sm" variant={variant} onClick={() => page("chart")}>
+ {S.company.overview.goToChart}
+ </Button>
+ );
+ }
+ return (
+ <Button size="sm" variant={variant} onClick={() => page("calendar")}>
+ {S.company.overview.goToCalendar}
+ </Button>
+ );
+ };
+ const stepText: Record<FirstStep, { title: string; body: string }> = {
+ ceo: { title: S.company.overview.stepCeoTitle, body: S.company.overview.stepCeoBody },
+ hire: { title: S.company.overview.stepHireTitle, body: S.company.overview.stepHireBody },
+ schedule: {
+ title: S.company.overview.stepScheduleTitle,
+ body: S.company.overview.stepScheduleBody,
+ },
+ };
+
+ const spendDetail =
+ spend.budget === null
+ ? S.company.noBudget
+ : spend.remaining !== null && spend.remaining < 0
+ ? S.company.overview.overBudget(formatMoney(-spend.remaining, currency))
+ : S.company.overview.budgetLeft(formatMoney(spend.remaining ?? 0, currency));
+
+ return (
+ // While the first-steps guide is on screen its step 1 IS the "open the CEO's desk"
+ // button, so the header does not draw a second one.
+ <OrgPage
+ title={title}
+ info={info}
+ {...(steps.fresh ? {} : { actions: deskButton("secondary", "sm") })}
+ >
+ {error !== null && (
+ <ErrorLine
+ message={S.company.overview.refreshFailed}
+ detail={error}
+ onRetry={() => void load()}
+ className="mb-4"
+ />
+ )}
+
+ {/* Hero: name and state, the metadata line, and the mission folded to one line. The
+ period's spend is not repeated here — it is the last cell of the KPI strip. */}
+ <header className="min-w-0 border-b border-gray-200 pb-5 dark:border-gray-800">
+ <div className="flex flex-wrap items-center gap-2">
+ <h2 className="text-2xl font-semibold tracking-tight">{detail.name}</h2>
+ <OrgStatusPill org={detail} />
+ </div>
+ <p className="mt-1.5 text-xs text-gray-500 dark:text-gray-400">
+ {S.company.overview.createdBy(detail.createdBy)} ·{" "}
+ {S.company.overview.employeesCount(counts.total)} ·{" "}
+ {S.company.overview.period(detail.spend.period)}
+ </p>
+ <MissionFold mission={detail.mission} />
+ </header>
+
+ {/* KPI strip: four cells ruled by hairlines, each with the button that opens its page. */}
+ <div className="mt-5 grid grid-cols-2 gap-px overflow-hidden rounded-md border border-gray-200 bg-gray-200 lg:grid-cols-4 dark:border-gray-800 dark:bg-gray-800">
+ <KpiCell
+ label={S.company.overview.employees}
+ value={counts.total}
+ jump={S.company.overview.openChart}
+ onJump={() => page("chart")}
+ detail={
+ <>
+ <ToneCount tone="success" label={S.company.overview.onDesk} value={counts.onDesk} />
+ <ToneCount tone="busy" label={S.company.overview.running} value={counts.running} />
+ <ToneCount tone="attention" label={S.company.overview.paused} value={counts.paused} />
+ </>
+ }
+ />
+ <KpiCell
+ label={S.company.overview.board}
+ value={board.open}
+ jump={S.company.overview.openBoard}
+ onJump={() => page("tickets")}
+ detail={
+ <span className="block w-full">
+ <span
+ className="flex h-1.5 w-full overflow-hidden rounded-full bg-gray-100 dark:bg-gray-800"
+ role="img"
+ aria-label={`${S.company.overview.openTickets} ${board.open} · ${S.company.overview.boardTotal(board.total)}`}
+ >
+ {board.segments
+ .filter((seg) => seg.count > 0)
+ .map((seg) => (
+ <span
+ key={seg.status}
+ title={`${S.company.tickets.columns[seg.status] ?? seg.status} ${seg.count}`}
+ className={`block h-full ${BOARD_FILL[seg.status]}`}
+ style={{ width: `${seg.share * 100}%` }}
+ />
+ ))}
+ </span>
+ {/* The counts under the bar are the controls, not the bar and not the cell: each
+ is a small button that opens the board filtered to what it counts, and its
+ tooltip says so rather than leaving the reader to guess. */}
+ <span className="mt-2 flex flex-wrap items-center gap-x-2 gap-y-1">
+ {board.segments.map((seg) => (
+ <button
+ key={seg.status}
+ type="button"
+ title={S.company.overview.openColumn(
+ S.company.tickets.columns[seg.status] ?? seg.status,
+ )}
+ onClick={() => page("tickets", `?column=${seg.status}`)}
+ className={`inline-flex items-center ${ICON_GAP.tight} rounded px-1 text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800`}
+ >
+ <span
+ className={`block h-1.5 w-1.5 rounded-full ${BOARD_FILL[seg.status]}`}
+ aria-hidden
+ />
+ {S.company.tickets.columns[seg.status] ?? seg.status}
+ <span className="font-semibold tabular-nums text-gray-700 dark:text-gray-200">
+ {seg.count}
+ </span>
+ </button>
+ ))}
+ {/* The blocked count is one more label in this row, not a pill: it is read
+ beside the five column counts and has to weigh the same as they do. */}
+ <button
+ type="button"
+ title={S.company.overview.openColumn(S.company.overview.blocked)}
+ onClick={() => page("tickets", "?blocked=1")}
+ className={`inline-flex items-center ${ICON_GAP.tight} rounded px-1 text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800`}
+ >
+ <span
+ className={`block h-1.5 w-1.5 rounded-full ${
+ detail.blockedTickets > 0 ? toneDot.attention : toneDot.muted
+ }`}
+ aria-hidden
+ />
+ {S.company.overview.blocked}
+ <span className="font-semibold tabular-nums text-gray-700 dark:text-gray-200">
+ {detail.blockedTickets}
+ </span>
+ </button>
+ </span>
+ </span>
+ }
+ />
+ <KpiCell
+ label={S.company.overview.today}
+ value={today.total}
+ jump={S.company.overview.openCalendar}
+ onJump={() => page("calendar")}
+ detail={
+ today.total === 0 ? (
+ <span>{S.company.overview.todayEmpty}</span>
+ ) : (
+ <>
+ {today.fired > 0 && (
+ <ToneCount tone="success" label={markLabel("fired")} value={today.fired} />
+ )}
+ {today.queued > 0 && (
+ <ToneCount tone="attention" label={markLabel("queued")} value={today.queued} />
+ )}
+ {today.failed > 0 && (
+ <ToneCount tone="danger" label={S.company.overview.failed} value={today.failed} />
+ )}
+ {today.paused > 0 && (
+ <ToneCount tone="muted" label={markLabel("paused")} value={today.paused} />
+ )}
+ <ToneCount
+ tone="attention"
+ label={S.company.overview.upcoming}
+ value={today.upcoming}
+ />
+ </>
+ )
+ }
+ />
+ <KpiCell
+ label={S.company.overview.spend}
+ value={
+ <span className={`flex items-center ${ICON_GAP.card}`}>
+ {/* Small: the cell is a quarter of the strip, and the ring is the picture of a
+ number already spelled out beside it. */}
+ <SpendRing
+ size={40}
+ cost={spend.cost}
+ currency={currency}
+ {...(spend.budget !== null ? { budget: spend.budget } : {})}
+ {...(spend.ratio !== null ? { ratio: spend.ratio } : {})}
+ />
+ <span className="min-w-0 truncate">{formatMoney(spend.cost, currency)}</span>
+ </span>
+ }
+ jump={S.company.overview.openFinance}
+ onJump={() => page("finance")}
+ detail={
+ <span className="block w-full">
+ <BudgetBar
+ cost={spend.cost}
+ currency={currency}
+ compact
+ {...(spend.budget !== null ? { budget: spend.budget } : {})}
+ {...(spend.ratio !== null ? { ratio: spend.ratio } : {})}
+ />
+ <span className="mt-1.5 block">{spendDetail}</span>
+ </span>
+ }
+ />
+ </div>
+
+ {steps.fresh ? (
+ <OrgSection
+ title={S.company.overview.firstStepsTitle}
+ info={S.company.overview.firstStepsInfo}
+ className="mt-8"
+ >
+ <ol className="grid grid-cols-1 gap-4 md:grid-cols-3">
+ {FIRST_STEPS.map((step, i) => (
+ <StepCard
+ key={step}
+ index={i + 1}
+ done={steps.done[step]}
+ current={steps.next === step}
+ title={stepText[step].title}
+ body={stepText[step].body}
+ action={stepAction(step, steps.next === step)}
+ />
+ ))}
+ </ol>
+ </OrgSection>
+ ) : (
+ <>
+ {/* The inbox: everything that needs the reader, newest first. */}
+ <OrgSection
+ title={S.company.overview.inbox}
+ info={S.company.overview.inboxInfo}
+ count={inbox.length}
+ className="mt-8"
+ actions={
+ <div role="group" aria-label={S.company.overview.inbox}>
+ <Segmented
+ cols={4}
+ value={inboxFilter}
+ onChange={setInboxFilter}
+ options={INBOX_FILTERS.map((f) => ({
+ value: f,
+ label: `${S.company.overview.inboxFilters[f]} ${inboxTotals[f]}`,
+ }))}
+ />
+ </div>
+ }
+ >
+ {visibleInbox.length === 0 ? (
+ <OrgEmptyLine>{S.company.overview.inboxEmpty}</OrgEmptyLine>
+ ) : (
+ <ul className="space-y-0.5">
+ {visibleInbox.map((row) => (
+ <li key={row.key} className={rowClass}>
+ <span
+ className={`flex w-20 shrink-0 items-center ${ICON_GAP.tight} text-xs text-gray-500 dark:text-gray-400`}
+ >
+ <GlyphIcon d={INBOX_ICON[row.category]} size={ICON_SIZE.rowLead} />
+ <span className="truncate">
+ {S.company.overview.inboxCategories[row.category]}
+ </span>
+ </span>
+ <InboxDot row={row} />
+ <TitleButton
+ className="flex-1 truncate"
+ title={
+ row.target.kind === "ticket"
+ ? S.company.overview.openTicket
+ : S.company.overview.openChannel
+ }
+ onClick={() => openInboxRow(row.target)}
+ >
+ {row.title}
+ </TitleButton>
+ {row.detail !== undefined && (
+ <span className="hidden max-w-40 shrink-0 truncate text-xs text-gray-500 sm:inline dark:text-gray-400">
+ {row.detail}
+ </span>
+ )}
+ <span
+ className="w-20 shrink-0 text-right text-xs tabular-nums text-gray-400 dark:text-gray-500"
+ {...(row.time !== null ? { title: formatDateTime(row.time) } : {})}
+ >
+ {row.time === null ? "—" : formatRelativeShort(row.time, locale)}
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+ </OrgSection>
+
+ {/* Today's timeline: a dot per instance on a rule, in the tone of its outcome. */}
+ {/* No jump of its own: the KPI cell above carries the one button to the calendar,
+ and every row's title opens it too. */}
+ <OrgSection title={S.company.overview.today} count={today.total} className="mt-8">
+ {today.entries.length === 0 ? (
+ <OrgEmptyLine>{S.company.overview.todayEmpty}</OrgEmptyLine>
+ ) : (
+ <ol className="ml-1.5 border-l border-gray-200 dark:border-gray-800">
+ {today.entries.slice(0, TIMELINE_ROWS).map((entry) => {
+ const tone = TIMELINE_TONE[entry.mark];
+ return (
+ <li key={entry.key} className="relative pl-4">
+ <span
+ aria-hidden
+ className={`absolute -left-1 top-3 block h-1.5 w-1.5 rounded-full ${toneDot[tone]}`}
+ />
+ <div className={`${rowClass} px-1.5`}>
+ <span className="w-11 shrink-0 font-mono text-xs tabular-nums text-gray-500 dark:text-gray-400">
+ {entry.at === null ? "—" : timeLabel(entry.at)}
+ </span>
+ <TitleButton
+ className="flex-1 truncate"
+ title={S.company.overview.openCalendar}
+ onClick={() => page("calendar")}
+ >
+ {entry.title}
+ </TitleButton>
+ <span className="hidden shrink-0 text-xs text-gray-500 sm:inline-flex dark:text-gray-400">
+ <PrincipalChip principal={agentPrincipal(entry.agentId)} names={names} />
+ </span>
+ <span className={`shrink-0 text-xs ${toneInk[tone]}`}>
+ {markLabel(entry.mark)}
+ </span>
+ </div>
+ </li>
+ );
+ })}
+ {today.entries.length > TIMELINE_ROWS && (
+ <li className="pl-4 pt-1 text-xs text-gray-400 dark:text-gray-500">
+ {S.company.overview.timelineMore(today.entries.length - TIMELINE_ROWS)}
+ </li>
+ )}
+ </ol>
+ )}
+ </OrgSection>
+
+ {/* Budget alerts: who, warned or paused, when. */}
+ <OrgSection
+ title={S.company.overview.alerts}
+ count={detail.alerts.length}
+ className="mt-8"
+ >
+ {detail.alerts.length === 0 ? (
+ <OrgEmptyLine>{S.company.overview.alertsEmpty}</OrgEmptyLine>
+ ) : (
+ <ul className="space-y-0.5">
+ {detail.alerts.map((a) => (
+ <li key={`${a.agentId}/${a.period}`} className={rowClass}>
+ <TitleButton
+ className="flex-1 truncate"
+ title={S.company.overview.openFinance}
+ onClick={() => page("finance")}
+ >
+ <PrincipalChip principal={agentPrincipal(a.agentId)} names={names} />
+ </TitleButton>
+ {a.pausedAt !== undefined ? (
+ <Badge tone="red">{S.company.finance.paused}</Badge>
+ ) : (
+ <Badge tone="amber">{S.company.finance.warned}</Badge>
+ )}
+ <span className="shrink-0 text-xs text-gray-500 dark:text-gray-400">
+ {formatRelativeShort(a.pausedAt ?? a.warnedAt ?? "", locale)}
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+ </OrgSection>
+ </>
+ )}
+ </OrgPage>
+ );
+}
diff --git a/packages/web/src/features/company/overview-summary.ts b/packages/web/src/features/company/overview-summary.ts
new file mode 100644
index 00000000..517d9fc5
--- /dev/null
+++ b/packages/web/src/features/company/overview-summary.ts
@@ -0,0 +1,399 @@
+/**
+ * The overview page's shaping (pure, unit tested): the employee counts, the board as a
+ * segmented bar, today's calendar as an ordered timeline with each instance's outcome, the
+ * spend against the budget, the inbox — what names the reader, what is stuck and what has
+ * landed, newest first — and whether an organization is still fresh enough that a three-step
+ * guide serves it better than an empty dashboard.
+ */
+import type {
+ OrgCalendarItem,
+ OrgCalendarOutcome,
+ OrgEmployeeItem,
+ OrgEmployeeState,
+ OrgInbox,
+ OrgTicketItem,
+ OrgTicketStatus,
+} from "@prismshadow/penguin-server/api";
+import type { Tone } from "../../lib/tone";
+import { DEFAULT_CHANNEL_ID } from "./channel-list";
+import { TICKET_COLUMNS } from "./ticket-board";
+
+export interface EmployeeCounts {
+ total: number;
+ /** Employees whose desk session exists. */
+ onDesk: number;
+ running: number;
+ /** Budget-paused. */
+ paused: number;
+}
+
+/**
+ * The employee tallies. `liveStates` is what the session list says each employee is doing
+ * (org-sessions.ts, liveEmployeeStates), which outranks the chart's own `state`: that snapshot
+ * is re-read on organization events and a run ending publishes none, so the running count
+ * would otherwise keep counting employees that had already stopped. An employee the map does
+ * not name — or a page that passes no map at all — falls back to the snapshot.
+ */
+export function employeeCounts(
+ employees: ReadonlyArray<Pick<OrgEmployeeItem, "agentId" | "state" | "desk">>,
+ liveStates?: ReadonlyMap<string, OrgEmployeeState>,
+): EmployeeCounts {
+ let onDesk = 0;
+ let running = 0;
+ let paused = 0;
+ for (const e of employees) {
+ if (e.desk !== undefined) onDesk += 1;
+ const state = liveStates?.get(e.agentId) ?? e.state;
+ if (state === "running") running += 1;
+ else if (state === "paused") paused += 1;
+ }
+ return { total: employees.length, onDesk, running, paused };
+}
+
+export interface BoardSegment {
+ status: OrgTicketStatus;
+ count: number;
+ /** 0–1 share of the whole board; 0 on an empty board. */
+ share: number;
+}
+
+export interface BoardSummary {
+ segments: BoardSegment[];
+ total: number;
+ /** proposed + in_progress + review: what is still moving. */
+ open: number;
+}
+
+/** The board as a segmented bar: every column in lifecycle order, its count and its share. */
+export function boardSummary(board: Partial<Record<OrgTicketStatus, number>>): BoardSummary {
+ const total = TICKET_COLUMNS.reduce((n, c) => n + (board[c] ?? 0), 0);
+ const segments = TICKET_COLUMNS.map((status) => {
+ const count = board[status] ?? 0;
+ return { status, count, share: total === 0 ? 0 : count / total };
+ });
+ const open = (board.proposed ?? 0) + (board.in_progress ?? 0) + (board.review ?? 0);
+ return { segments, total, open };
+}
+
+/** The bar's fill per column, in the same tones the ticket status badges wear (done takes a heavier neutral, as its badge does). */
+export const BOARD_SEGMENT_TONE: Record<OrgTicketStatus, Tone | "done"> = {
+ proposed: "muted",
+ in_progress: "busy",
+ review: "attention",
+ done: "done",
+ rejected: "danger",
+};
+
+/** What today's timeline says about one instance: its recorded outcome, or that it is still ahead. */
+export type TimelineMark = OrgCalendarOutcome | "upcoming";
+
+export interface TimelineEntry {
+ key: string;
+ agentId: string;
+ title: string;
+ /** Epoch ms of the instance shown: the last firing today, else the next one; null when the event carries neither. */
+ at: number | null;
+ mark: TimelineMark;
+}
+
+export interface TodaySummary {
+ entries: TimelineEntry[];
+ total: number;
+ fired: number;
+ queued: number;
+ /** missed + error: instances that did not run as planned. */
+ failed: number;
+ paused: number;
+ upcoming: number;
+}
+
+const parse = (iso: string | undefined): number | null => {
+ if (iso === undefined) return null;
+ const ms = Date.parse(iso);
+ return Number.isNaN(ms) ? null : ms;
+};
+
+/** Today's events in time order, each with the mark its outcome earns; unknown times sort last. */
+export function todaySummary(
+ today: ReadonlyArray<
+ Pick<
+ OrgCalendarItem,
+ "agentId" | "name" | "title" | "lastFiredAt" | "nextFireAt" | "lastOutcome"
+ >
+ >,
+): TodaySummary {
+ const counts = { fired: 0, queued: 0, failed: 0, paused: 0, upcoming: 0 };
+ const entries: TimelineEntry[] = today.map((ev) => {
+ const mark: TimelineMark = ev.lastOutcome ?? "upcoming";
+ if (mark === "fired") counts.fired += 1;
+ else if (mark === "queued") counts.queued += 1;
+ else if (mark === "paused") counts.paused += 1;
+ else if (mark === "upcoming") counts.upcoming += 1;
+ else counts.failed += 1;
+ return {
+ key: `${ev.agentId}/${ev.name}`,
+ agentId: ev.agentId,
+ title: ev.title ?? ev.name,
+ at: parse(ev.lastFiredAt) ?? parse(ev.nextFireAt),
+ mark,
+ };
+ });
+ entries.sort((a, b) => (a.at ?? Infinity) - (b.at ?? Infinity) || a.key.localeCompare(b.key));
+ return { entries, total: today.length, ...counts };
+}
+
+/** The tone a timeline mark takes: fired is done well, queued waits, missed and error failed, paused recedes, upcoming waits on time. */
+export const TIMELINE_TONE: Record<TimelineMark, Tone> = {
+ fired: "success",
+ queued: "attention",
+ paused: "muted",
+ missed: "danger",
+ error: "danger",
+ upcoming: "attention",
+};
+
+export interface SpendSummaryView {
+ cost: number;
+ budget: number | null;
+ /** cost / budget, unclamped; null without a budget. */
+ ratio: number | null;
+ /** budget − cost; negative when over; null without a budget. */
+ remaining: number | null;
+}
+
+export function spendSummary(spend: {
+ cost: number;
+ budget?: number;
+ ratio?: number;
+}): SpendSummaryView {
+ if (spend.budget === undefined || spend.budget <= 0) {
+ return { cost: spend.cost, budget: null, ratio: null, remaining: null };
+ }
+ return {
+ cost: spend.cost,
+ budget: spend.budget,
+ ratio: spend.ratio ?? spend.cost / spend.budget,
+ remaining: spend.budget - spend.cost,
+ };
+}
+
+/**
+ * How many rows the inbox holds. Past this the reader is better served by the channel and the
+ * board themselves, and the section stops being something a person can scan.
+ */
+export const INBOX_ROWS = 40;
+
+/**
+ * What an inbox row is about — the three things the organization has to say to a person:
+ * something was said TO them, something is stuck, something is finished. The order is also how
+ * rows of the same instant are ranked.
+ */
+export type InboxCategory = "mention" | "blocked" | "done";
+
+const CATEGORY_ORDER: Record<InboxCategory, number> = {
+ mention: 0,
+ blocked: 1,
+ done: 2,
+};
+
+/** Where a row leads: the channel it was said in, or the ticket it is about. */
+export type InboxTarget =
+ { kind: "channel"; channelId: string } | { kind: "ticket"; ticketId: string };
+
+export interface InboxRow {
+ key: string;
+ category: InboxCategory;
+ title: string;
+ /** The aside after the title: who said it, who owns it, what it waits for. */
+ detail?: string;
+ /** ISO 8601, or null when the source carries no time at all. */
+ time: string | null;
+ tone: Tone;
+ target: InboxTarget;
+}
+
+export interface InboxInput {
+ /**
+ * The three lists as the organization detail sends them. A server older than the field sends
+ * none, which is an empty inbox rather than an error: every row here is a convenience the
+ * pages behind it also offer.
+ */
+ inbox: OrgInbox | undefined;
+ /**
+ * A principal's display name. A function rather than a map because `all` and `system` have
+ * localized names: the page passes its own `principalLabel` bound to the employee names.
+ */
+ names: (principal: string) => string;
+}
+
+/** The first line of a message that carries anything; "" when the whole text is blank. */
+function firstLine(text: string): string {
+ for (const line of text.split("\n")) {
+ const trimmed = line.trim();
+ if (trimmed !== "") return trimmed;
+ }
+ return "";
+}
+
+/**
+ * A ticket's own time. Ticket ids are `yyyy-mm-dd-<slug>` and the board item carries no
+ * timestamp, so the day it was filed is the only time the inbox can rank it by; null for an
+ * id that does not start with a date.
+ */
+function ticketTime(ticketId: string): string | null {
+ const m = /^(\d{4}-\d{2}-\d{2})-/.exec(ticketId);
+ if (m === null) return null;
+ const iso = `${m[1]}T00:00:00.000Z`;
+ return Number.isNaN(Date.parse(iso)) ? null : iso;
+}
+
+/**
+ * A blocked ticket's aside: why it is stuck, then who it waits on. The reason is what the
+ * reader acts on and the principal is who they act through, so the reason leads; either half
+ * may be missing, and a ticket blocked with neither recorded carries no aside at all.
+ */
+function blockedDetail(ticket: OrgTicketItem, names: (principal: string) => string): string {
+ const reason = ticket.blocked?.trim() ?? "";
+ const waitsOn =
+ ticket.blockedBy === undefined || ticket.blockedBy === "" ? "" : names(ticket.blockedBy);
+ return [reason, waitsOn].filter((part) => part !== "").join(" · ");
+}
+
+/**
+ * The inbox as one list, newest first: the messages that name the reader (or everyone), the
+ * tickets that are blocked, and the tickets closed as done this period. Nothing else — a
+ * dashboard that repeats the whole channel is a second channel, and what earns a place here is
+ * what is addressed to the reader, what has stopped, and what has landed.
+ *
+ * Rows without a time sort last (a ticket whose id carries no date and that was never stamped
+ * closed), ties fall back to the category order and then the key, and the list is capped at
+ * `INBOX_ROWS`.
+ */
+export function inboxRows(input: InboxInput): InboxRow[] {
+ const rows: InboxRow[] = [];
+
+ for (const message of input.inbox?.mentions ?? []) {
+ rows.push({
+ key: `mention/${message.id}`,
+ category: "mention",
+ title: firstLine(message.text),
+ detail: input.names(message.sender),
+ time: message.time,
+ tone: "attention",
+ target: { kind: "channel", channelId: DEFAULT_CHANNEL_ID },
+ });
+ }
+
+ for (const ticket of input.inbox?.blockedTickets ?? []) {
+ const detail = blockedDetail(ticket, input.names);
+ rows.push({
+ key: `blocked/${ticket.ticketId}`,
+ category: "blocked",
+ title: ticket.title,
+ ...(detail !== "" ? { detail } : {}),
+ time: ticketTime(ticket.ticketId),
+ tone: "attention",
+ target: { kind: "ticket", ticketId: ticket.ticketId },
+ });
+ }
+
+ for (const ticket of input.inbox?.doneTickets ?? []) {
+ rows.push({
+ key: `done/${ticket.ticketId}`,
+ category: "done",
+ title: ticket.title,
+ ...(ticket.owner !== undefined ? { detail: input.names(ticket.owner) } : {}),
+ // A ticket closed before the field existed still has the day it was filed to rank by.
+ time: ticket.closedAt ?? ticketTime(ticket.ticketId),
+ // Nothing is asked of the reader: the row is news, and its mark recedes.
+ tone: "muted",
+ target: { kind: "ticket", ticketId: ticket.ticketId },
+ });
+ }
+
+ return rows
+ .map((row) => ({ row, ms: row.time === null ? null : parse(row.time) }))
+ .sort((a, b) => {
+ if (a.ms === null || b.ms === null) {
+ if (a.ms !== b.ms) return a.ms === null ? 1 : -1;
+ } else if (a.ms !== b.ms) return b.ms - a.ms;
+ return (
+ CATEGORY_ORDER[a.row.category] - CATEGORY_ORDER[b.row.category] ||
+ a.row.key.localeCompare(b.row.key)
+ );
+ })
+ .slice(0, INBOX_ROWS)
+ .map((entry) => entry.row);
+}
+
+/** The inbox's filter chips, in rendered order: everything, then one per category. */
+export type InboxFilter = "all" | InboxCategory;
+export const INBOX_FILTERS: readonly InboxFilter[] = ["all", "mention", "blocked", "done"];
+
+/** Whether a chip admits a row: its own category, and "all" everything. */
+export function inboxMatches(row: InboxRow, filter: InboxFilter): boolean {
+ return filter === "all" || row.category === filter;
+}
+
+/** How many rows each chip would show. */
+export function inboxCounts(rows: readonly InboxRow[]): Record<InboxFilter, number> {
+ const counts: Record<InboxFilter, number> = {
+ all: rows.length,
+ mention: 0,
+ blocked: 0,
+ done: 0,
+ };
+ for (const row of rows) {
+ for (const filter of INBOX_FILTERS) {
+ if (filter !== "all" && inboxMatches(row, filter)) counts[filter] += 1;
+ }
+ }
+ return counts;
+}
+
+/** The three steps a new organization walks: talk to the CEO, hire, schedule. */
+export type FirstStep = "ceo" | "hire" | "schedule";
+export const FIRST_STEPS: readonly FirstStep[] = ["ceo", "hire", "schedule"];
+
+export interface FirstStepsState {
+ /** True while the guide replaces the dashboard: nobody hired and nothing on the board. */
+ fresh: boolean;
+ done: Record<FirstStep, boolean>;
+ /** The first step not yet done, or null when all three are. */
+ next: FirstStep | null;
+}
+
+/**
+ * Whether the organization is still at its first steps, and which of them are done. The
+ * guide stands only while no one but the CEO is employed and the board is empty; hiring or
+ * filing a ticket means the organization is at work, and the dashboard takes over even if
+ * no calendar event exists yet.
+ */
+export function firstSteps(input: {
+ employeeCount: number;
+ boardTotal: number;
+ ceoDeskOpened: boolean;
+ calendarCount: number;
+}): FirstStepsState {
+ const done: Record<FirstStep, boolean> = {
+ ceo: input.ceoDeskOpened,
+ hire: input.employeeCount > 1,
+ schedule: input.calendarCount > 0,
+ };
+ const fresh = input.employeeCount <= 1 && input.boardTotal === 0;
+ const next = FIRST_STEPS.find((step) => !done[step]) ?? null;
+ return { fresh, done, next };
+}
+
+/** Characters of a mission the hero's single clamped line holds, near enough to guess by. */
+const MISSION_ONE_LINE = 48;
+
+/**
+ * Whether the hero's mission fold should offer its toggle before the browser has measured
+ * anything: a mission that carries a line break, or one longer than a line holds. The page
+ * corrects this from the element's own overflow once it has laid out, so the guess only has to
+ * be right often enough that the toggle does not flicker in on the first paint.
+ */
+export function missionClampedGuess(mission: string): boolean {
+ return mission.includes("\n") || mission.trim().length > MISSION_ONE_LINE;
+}
diff --git a/packages/web/src/features/company/page-hints.ts b/packages/web/src/features/company/page-hints.ts
new file mode 100644
index 00000000..8b5f2a7e
--- /dev/null
+++ b/packages/web/src/features/company/page-hints.ts
@@ -0,0 +1,54 @@
+/**
+ * The dismissal of a page hint: the one-line muted note an empty calendar or an empty ticket
+ * board shows above its grid, saying what the page is for and where its create button is. The
+ * note is read once and then in the way forever, so the "×" beside it puts it away for good —
+ * the same sentence stays in the page's "?", which is where it is reachable afterwards.
+ *
+ * Scoped by user, Project, organization and page: two people on one browser dismiss
+ * separately, and a note dismissed in one organization still greets the first empty board of
+ * the next — the organization it explains is the one the reader has not seen yet.
+ *
+ * Storage is injectable (org-draft.ts convention: vitest runs in Node with no localStorage)
+ * and every read degrades to "not dismissed": showing a one-line note once too often costs
+ * far less than throwing while a page renders.
+ */
+
+/** Minimal storage interface (the subset of localStorage used here); tests inject an in-memory one. */
+export interface HintStorage {
+ getItem(key: string): string | null;
+ setItem(key: string, value: string): void;
+}
+
+/** The pages that carry a dismissible hint. */
+export type HintPage = "calendar" | "tickets";
+
+/** What a dismissed hint stores. The value is never read back — the key's presence is the answer. */
+const DISMISSED = "1";
+
+/** The hint's storage key. One key per (user, Project, organization, page); a signed-out browser gets its own bucket. */
+export function hintKey(
+ userId: string | null,
+ projectId: string,
+ orgId: string,
+ page: HintPage,
+): string {
+ return `penguin.orgPageHint.${userId ?? ""}.${projectId}.${orgId}.${page}`;
+}
+
+/** Whether this hint has been dismissed. Anything unreadable (private browsing, a cleared bucket) reads as "no". */
+export function isHintDismissed(key: string, storage?: HintStorage): boolean {
+ try {
+ return (storage ?? localStorage).getItem(key) !== null;
+ } catch {
+ return false;
+ }
+}
+
+/** Puts the hint away for good. A storage that refuses the write costs the click nothing beyond this render. */
+export function dismissHint(key: string, storage?: HintStorage): void {
+ try {
+ (storage ?? localStorage).setItem(key, DISMISSED);
+ } catch {
+ /* best-effort persistence (quota limits / private browsing) */
+ }
+}
diff --git a/packages/web/src/features/company/principals.ts b/packages/web/src/features/company/principals.ts
new file mode 100644
index 00000000..9401590d
--- /dev/null
+++ b/packages/web/src/features/company/principals.ts
@@ -0,0 +1,38 @@
+/**
+ * Principal notation as organization files use it (pure): `agent:<id>` / `user:<id>`, plus
+ * `all` and `system`. Mirrors the server's organization/principal.ts, which the browser
+ * bundle cannot import; the two must keep spelling principals identically.
+ */
+export type ParsedPrincipal =
+ | { kind: "agent"; id: string }
+ | { kind: "user"; id: string }
+ | { kind: "all" }
+ | { kind: "system" }
+ | { kind: "unknown"; raw: string };
+
+export function parsePrincipal(raw: string): ParsedPrincipal {
+ const value = raw.trim();
+ if (value === "all") return { kind: "all" };
+ if (value === "system") return { kind: "system" };
+ const m = /^(agent|user):(.+)$/.exec(value);
+ if (!m) return { kind: "unknown", raw: value };
+ return m[1] === "agent" ? { kind: "agent", id: m[2]! } : { kind: "user", id: m[2]! };
+}
+
+export const agentPrincipal = (agentId: string): string => `agent:${agentId}`;
+
+/** The agent id behind an `agent:` principal, or null for anything else. */
+export function principalAgentId(raw: string): string | null {
+ const p = parsePrincipal(raw);
+ return p.kind === "agent" ? p.id : null;
+}
+
+/** Splits a `Notify`-style input: comma separated, blanks dropped, order kept, duplicates removed. */
+export function splitPrincipalList(raw: string): string[] {
+ const out: string[] = [];
+ for (const part of raw.split(",")) {
+ const v = part.trim();
+ if (v !== "" && !out.includes(v)) out.push(v);
+ }
+ return out;
+}
diff --git a/packages/web/src/features/company/semantic-id-field.tsx b/packages/web/src/features/company/semantic-id-field.tsx
new file mode 100644
index 00000000..637be542
--- /dev/null
+++ b/packages/web/src/features/company/semantic-id-field.tsx
@@ -0,0 +1,173 @@
+/**
+ * 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 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.
+ *
+ * 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,
+ * where a label would crowd the value it is meant to leave room for. What it must stay outside
+ * 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.
+ */
+import { useId, useState } from "react";
+import type { KeyboardEvent } from "react";
+import type { SemanticIdSuggestRequest } from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { ICON_SIZE } from "../../lib/icon-scale";
+import { toneInk } from "../../lib/tone";
+import { Button } from "../../components/ui/button";
+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 type { IdSuggestNotice } from "./id-suggest-notice";
+
+/** Generate (lucide sparkles): the four-pointed star with its two smaller companions. */
+const SPARKLES_ICON =
+ "m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275zM5 3v4M19 17v4M3 5h4M17 19h4";
+
+export function SemanticIdField({
+ projectId,
+ kind,
+ label,
+ hint,
+ value,
+ source,
+ taken,
+ error,
+ disabled = false,
+ onChange,
+ onEnter,
+}: {
+ projectId: string;
+ /** What the id is for; the server's proposal is shaped by it. */
+ kind: SemanticIdSuggestRequest["kind"];
+ label: string;
+ /** The id rule, which stays on screen while the user types; the generation clause is appended here. */
+ hint: string;
+ value: string;
+ /** The text a proposal is derived from — the display name, or the mission while the name is empty. */
+ source: string;
+ /** Ids already taken in the target scope, so a proposal never collides. Omitted where the caller knows of none. */
+ taken?: readonly string[];
+ /** The caller's own validation message; it outranks anything the generation has to say. */
+ error?: string | undefined;
+ disabled?: boolean;
+ onChange: (id: string) => void;
+ /** Enter inside the field, where the dialog submits on it. */
+ onEnter?: () => void;
+}) {
+ const controlId = useId();
+ const messageId = `${controlId}-message`;
+ const [busy, setBusy] = useState(false);
+ /** What the last proposal has to say about the id it filled in; cleared by the next edit or attempt. */
+ const [notice, setNotice] = useState<IdSuggestNotice | null>(null);
+ const derivable = source.trim() !== "";
+ // The caller's validation outranks the proposal's own note: a rejected id is about what is
+ // in the box, which is what the user is looking at.
+ const showError = error !== undefined;
+ const below = showError || notice !== null;
+
+ const generate = async () => {
+ setBusy(true);
+ setNotice(null);
+ try {
+ const res = await api.suggestSemanticId(projectId, {
+ name: source.trim(),
+ kind,
+ ...(taken !== undefined && taken.length > 0 ? { taken: [...taken] } : {}),
+ });
+ onChange(res.id);
+ setNotice(idSuggestNotice(res, S.company.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.
+ toastError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ 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();
+ }
+ },
+ }
+ : {})}
+ />
+ {/* The tooltip keeps saying where the id comes from; the label only says who makes it. */}
+ <Button
+ size="sm"
+ title={S.company.generateId}
+ aria-busy={busy || undefined}
+ disabled={disabled || busy || !derivable}
+ onClick={() => void generate()}
+ className="shrink-0 whitespace-nowrap"
+ >
+ {busy ? (
+ <span className="inline-block h-3 w-3 animate-spin rounded-full border-[1.5px] border-current border-t-transparent" />
+ ) : (
+ <GlyphIcon d={SPARKLES_ICON} size={ICON_SIZE.inlineGlyph} />
+ )}
+ {S.company.generateIdLabel}
+ </Button>
+ </div>
+ {showError ? (
+ <FieldError id={messageId}>{error}</FieldError>
+ ) : notice?.tone === "attention" ? (
+ // A placeholder id: what the user must act on, so it takes the slot the error would.
+ // `status` rather than `alert` — the box holds a valid id, nothing was rejected.
+ <span id={messageId} role="status" className={`mt-1 block text-xs ${toneInk.attention}`}>
+ {notice.text}
+ </span>
+ ) : (
+ <>
+ {/* The generation clause carries its own leading separator: what joins two clauses
+ is punctuation, and punctuation is part of the language. The id rule stays on
+ screen beside a quiet note — it is what the user reads while typing. */}
+ <FieldHint>{`${hint}${S.company.idGenerateHint}`}</FieldHint>
+ {notice !== null && (
+ <span id={messageId} role="status" className={`mt-1 block text-xs ${toneInk.muted}`}>
+ {notice.text}
+ </span>
+ )}
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/packages/web/src/features/company/shared.tsx b/packages/web/src/features/company/shared.tsx
new file mode 100644
index 00000000..ca36968d
--- /dev/null
+++ b/packages/web/src/features/company/shared.tsx
@@ -0,0 +1,516 @@
+/**
+ * Small pieces every organization page shares: the organization's status pill and dot, the
+ * budget bar and ring, the budget field and the two marks a budget box wears (its unit, and
+ * what a converted amount will be stored as), the ticket status and priority pills, the
+ * blocked badge, the failed-refresh line, the two ways out of a summary — the title that
+ * opens what it names, and the corner button a titleless card or row uses instead — the
+ * labelled value and the bordered KPI tile, and principal naming.
+ * Every status colour here is a tone from lib/tone.ts, picked by meaning.
+ */
+import { useId } from "react";
+import type { ReactNode } from "react";
+import type {
+ OrgStatus,
+ OrgTicketPriority,
+ OrgTicketStatus,
+} from "@prismshadow/penguin-server/api";
+import { S } from "../../lib/strings";
+import { formatMoney, formatPercent } from "../../lib/format";
+import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
+import { toneDot, toneInk, toneStrip } from "../../lib/tone";
+import type { Tone } from "../../lib/tone";
+import type { Currency } from "../../state/theme";
+import { AgentAvatar } from "../../components/ui/agent-avatar";
+import { Badge } from "../../components/ui/badge";
+import type { BadgeTone } from "../../components/ui/badge";
+import { Button } from "../../components/ui/button";
+import { FieldError, FieldHint, FieldLabel } from "../../components/ui/field";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { Input } from "../../components/ui/input";
+import { toStoredUsd, unitLabel } from "./budget-input";
+import { budgetTone } from "./finance-tree";
+import { parsePrincipal } from "./principals";
+import { ORG_STATUS_TONE, orgStatusKind } from "./shell-org-status";
+import type { OrgStatusKind } from "./shell-org-status";
+
+/** Circled exclamation (lucide circle-alert): the mark of an invalid chart entry or ticket file, and of the finance page's alert count. */
+export const INVALID_ICON = "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM12 8v4m0 4h.01";
+
+/** Arrow leaving to the upper right (lucide arrow-up-right): the mark of a jump to another page. */
+const JUMP_ICON = "M7 7h10v10M7 17 17 7";
+
+/**
+ * The way out of a card or a row that has no title to click: a flat glyph button that opens the
+ * page, the session or the ticket the thing beside it stands for, named for its destination
+ * ("Open the org chart", 「查看工单」). It sits in a KPI card's corner and at the end of a
+ * titleless row.
+ *
+ * Neither the card nor the row is itself the link. A whole-area click swallows the controls
+ * living inside it and leaves a reader guessing where the click would land, so the surface stays
+ * inert and the navigation is this button — always drawn, never revealed on hover, since a
+ * control that appears only under a pointer cannot be reached by touch at all. Where the thing
+ * does have a title, TitleButton carries the jump instead and this button is not drawn at all.
+ */
+export function JumpButton({
+ label,
+ onClick,
+ className = "",
+}: {
+ /** Where it goes, as the tooltip and the accessible name both read it. */
+ label: string;
+ onClick: () => void;
+ className?: string;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ title={label}
+ aria-label={label}
+ className={`inline-flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200 ${className}`}
+ >
+ <GlyphIcon d={JUMP_ICON} size={ICON_SIZE.inlineGlyph} />
+ </button>
+ );
+}
+
+/**
+ * A title that opens what it names: the click target of a card or a row that has one. The
+ * title is the one part of a surface that already says where a click would land, so it is the
+ * link — a real button, focusable and underlined on hover — while the rest of the surface stays
+ * inert (or, on the ticket board, stays the drag handle). Where a row has no natural title,
+ * JumpButton is the way out instead.
+ *
+ * The visible text is the accessible name; `title` carries the destination as the tooltip, so
+ * the name is still the thing the reader sees.
+ */
+export function TitleButton({
+ onClick,
+ title,
+ className = "",
+ children,
+}: {
+ onClick: () => void;
+ /** The tooltip: what a click opens, e.g. 「打开工单」. */
+ title?: string;
+ className?: string;
+ children: ReactNode;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ {...(title !== undefined ? { title } : {})}
+ className={`min-w-0 text-left hover:underline focus-visible:underline ${className}`}
+ >
+ {children}
+ </button>
+ );
+}
+
+/** The label of an organization's headline state. */
+function orgStatusLabel(kind: OrgStatusKind): string {
+ if (kind === "invalid") return S.company.orgInvalid;
+ return kind === "paused" ? S.company.statusPaused : S.company.statusActive;
+}
+
+const ORG_STATUS_BADGE: Record<OrgStatusKind, BadgeTone> = {
+ invalid: "red",
+ paused: "amber",
+ active: "green",
+};
+
+/** An organization's headline state as a pill: invalid configuration outranks paused, paused outranks active. The reason rides in the tooltip when the configuration is invalid. */
+export function OrgStatusPill({ org }: { org: { status: OrgStatus; invalid?: string } }) {
+ const kind = orgStatusKind(org);
+ return (
+ <span {...(org.invalid !== undefined ? { title: org.invalid } : {})} className="inline-flex">
+ <Badge tone={ORG_STATUS_BADGE[kind]}>{orgStatusLabel(kind)}</Badge>
+ </span>
+ );
+}
+
+/** The same state as a 6px dot (the switcher's trigger and rows), its name in the tooltip and sr text. */
+export function OrgStatusDot({ org }: { org: { status: OrgStatus; invalid?: string } }) {
+ const kind = orgStatusKind(org);
+ const label = orgStatusLabel(kind);
+ return (
+ <span title={label} className="inline-flex shrink-0 items-center">
+ <span className={`block h-1.5 w-1.5 rounded-full ${toneDot[ORG_STATUS_TONE[kind]]}`} />
+ <span className="sr-only">{label}</span>
+ </span>
+ );
+}
+
+/**
+ * A refresh that failed while the page still holds what it last read: one danger strip
+ * naming the failure, the server's reason beside it, and the retry — never a skeleton over
+ * data that is already on screen.
+ */
+export function ErrorLine({
+ message,
+ detail,
+ onRetry,
+ className = "",
+}: {
+ message: string;
+ /** The server's own wording (apiErrorText), shown after the message. */
+ detail?: string;
+ onRetry: () => void;
+ className?: string;
+}) {
+ return (
+ <div
+ role="alert"
+ className={`flex flex-wrap items-center justify-between gap-x-3 gap-y-2 rounded-md border px-3 py-2 text-xs ${toneStrip.danger} ${className}`}
+ >
+ <span className="min-w-0">
+ <span className="font-medium">{message}</span>
+ {detail !== undefined && detail !== message && (
+ <span className="ml-2 opacity-80">{detail}</span>
+ )}
+ </span>
+ <Button size="sm" onClick={onRetry}>
+ {S.common.retry}
+ </Button>
+ </div>
+ );
+}
+
+/**
+ * Spend against a budget as a ring: the used share drawn clockwise from the top in the
+ * budget's tone (attention from 80%, danger from 100%, the ring full when over), the percent
+ * inside; a muted, empty ring with a dash when there is no budget. The exact amounts ride in
+ * the accessible name and tooltip.
+ */
+export function SpendRing({
+ cost,
+ budget,
+ ratio,
+ currency,
+ size = 64,
+}: {
+ cost: number;
+ budget?: number;
+ ratio?: number;
+ currency: Currency;
+ size?: number;
+}) {
+ const tone = budgetTone(ratio);
+ const strokeWidth = Math.max(3, Math.round(size * 0.1));
+ const center = size / 2;
+ const r = (size - strokeWidth) / 2;
+ const c = 2 * Math.PI * r;
+ const share = ratio === undefined ? 0 : Math.min(1, Math.max(0, ratio));
+ const label =
+ budget === undefined
+ ? `${formatMoney(cost, currency)} · ${S.company.noBudget}`
+ : `${S.company.spendOfBudget(formatMoney(cost, currency), formatMoney(budget, currency))} · ${formatPercent(ratio)}`;
+ const ink = tone === "muted" ? "text-gray-300 dark:text-gray-700" : toneInk[tone];
+ return (
+ <svg
+ width={size}
+ height={size}
+ viewBox={`0 0 ${size} ${size}`}
+ role="img"
+ aria-label={label}
+ className={`block shrink-0 ${ink}`}
+ >
+ <title>{label}</title>
+ <circle
+ cx={center}
+ cy={center}
+ r={r}
+ fill="none"
+ stroke="currentColor"
+ strokeOpacity={0.25}
+ strokeWidth={strokeWidth}
+ />
+ {share > 0 && (
+ <circle
+ cx={center}
+ cy={center}
+ r={r}
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={strokeWidth}
+ strokeLinecap="round"
+ strokeDasharray={`${share * c} ${c}`}
+ transform={`rotate(-90 ${center} ${center})`}
+ />
+ )}
+ <text
+ x={center}
+ y={center}
+ textAnchor="middle"
+ dominantBaseline="central"
+ fontSize={Math.round(size * 0.22)}
+ fontWeight="600"
+ className="fill-gray-700 dark:fill-gray-200"
+ >
+ {budget === undefined ? "—" : formatPercent(ratio)}
+ </text>
+ </svg>
+ );
+}
+
+/** Spend against a budget as a bar: attention from 80%, danger from 100%; a muted rule when there is no budget. */
+export function BudgetBar({
+ cost,
+ budget,
+ ratio,
+ currency,
+ compact = false,
+}: {
+ cost: number;
+ budget?: number;
+ ratio?: number;
+ currency: Currency;
+ compact?: boolean;
+}) {
+ const tone = budgetTone(ratio);
+ const width = ratio === undefined ? 0 : Math.min(100, Math.max(0, ratio * 100));
+ const label =
+ budget === undefined
+ ? `${formatMoney(cost, currency)} · ${S.company.noBudget}`
+ : `${S.company.spendOfBudget(formatMoney(cost, currency), formatMoney(budget, currency))} · ${formatPercent(ratio)}`;
+ return (
+ <div className={compact ? "min-w-24" : ""}>
+ {!compact && (
+ <p
+ className={`mb-1 text-xs font-medium ${tone === "muted" ? "text-gray-500 dark:text-gray-400" : toneInk[tone]}`}
+ >
+ {label}
+ </p>
+ )}
+ <div
+ role="progressbar"
+ aria-label={label}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={Math.round(width)}
+ title={label}
+ className="h-1.5 w-full overflow-hidden rounded-full bg-gray-100 dark:bg-gray-800"
+ >
+ <div className={`h-full rounded-full ${toneDot[tone]}`} style={{ width: `${width}%` }} />
+ </div>
+ </div>
+ );
+}
+
+/**
+ * The unit that follows a budget box: the currency the reader picked, and the period the cap
+ * covers ("$ / month"). It sits after the box rather than inside the label, so one mark
+ * serves both a form field and the finance table's in-place editor.
+ */
+export function MoneyPerMonthUnit({ currency }: { currency: Currency }) {
+ return (
+ <span className="shrink-0 whitespace-nowrap text-xs text-gray-500 dark:text-gray-400">
+ {unitLabel(currency, S)}
+ </span>
+ );
+}
+
+/**
+ * What a budget typed in another currency will actually be stored as. Budgets live in USD in
+ * the organization's chart file and this App converts at one fixed rate, so a reader working
+ * in CNY is told the amount the file is about to hold. Nothing to say to a reader already
+ * working in USD, or while the box is empty.
+ */
+export function StoredUsdNote({ usd, currency }: { usd: number | null; currency: Currency }) {
+ if (currency === "USD" || usd === null) return null;
+ return (
+ <span className="mt-1 block text-[11px] text-gray-400 dark:text-gray-500">
+ {S.company.budgetStoredAs(formatMoney(usd, "USD"))}
+ </span>
+ );
+}
+
+/**
+ * A budget field: a number box in the reader's currency with the unit after it, the hint (or
+ * the error) beneath, and the stored amount under that while the two currencies differ. The
+ * three dialogs that set a budget share it; the finance table edits inside a cell and wears
+ * the two marks above on their own.
+ *
+ * The box is bare — an `Input` with no title of its own — and the title is associated by
+ * `htmlFor`, because a wrapping `<label>` names its first labelable descendant and this
+ * field's row holds more than the box.
+ */
+export function MoneyPerMonthInput({
+ label,
+ currency,
+ value,
+ hint,
+ error,
+ placeholder,
+ disabled = false,
+ autoFocus = false,
+ onChange,
+}: {
+ label: string;
+ currency: Currency;
+ /** The typed text, in the reader's currency; budget-input.ts converts it to what is stored. */
+ value: string;
+ hint?: string;
+ error?: string;
+ placeholder?: string;
+ disabled?: boolean;
+ autoFocus?: boolean;
+ onChange: (text: string) => void;
+}) {
+ const controlId = useId();
+ const errorId = `${controlId}-error`;
+ return (
+ <div>
+ <FieldLabel htmlFor={controlId}>{label}</FieldLabel>
+ <div className="flex items-center gap-2">
+ <Input
+ id={controlId}
+ size="sm"
+ type="number"
+ inputMode="decimal"
+ min={0}
+ step="any"
+ className="min-w-0 flex-1"
+ value={value}
+ disabled={disabled}
+ autoFocus={autoFocus}
+ invalid={error !== undefined}
+ {...(placeholder !== undefined ? { placeholder } : {})}
+ {...(error !== undefined ? { "aria-describedby": errorId } : {})}
+ onChange={(e) => onChange(e.target.value)}
+ />
+ <MoneyPerMonthUnit currency={currency} />
+ </div>
+ {error !== undefined ? (
+ <FieldError id={errorId}>{error}</FieldError>
+ ) : hint !== undefined ? (
+ <FieldHint>{hint}</FieldHint>
+ ) : null}
+ <StoredUsdNote usd={toStoredUsd(value, currency)} currency={currency} />
+ </div>
+ );
+}
+
+const STATUS_TONE: Record<OrgTicketStatus, BadgeTone> = {
+ proposed: "gray",
+ in_progress: "green",
+ review: "amber",
+ done: "brand",
+ rejected: "red",
+};
+
+export function TicketStatusBadge({ status }: { status: OrgTicketStatus }) {
+ return <Badge tone={STATUS_TONE[status]}>{S.company.tickets.columns[status] ?? status}</Badge>;
+}
+
+const PRIORITY_TONE: Record<OrgTicketPriority, BadgeTone> = { P0: "red", P1: "amber", P2: "gray" };
+
+export function PriorityBadge({ priority }: { priority: OrgTicketPriority }) {
+ return <Badge tone={PRIORITY_TONE[priority]}>{priority}</Badge>;
+}
+
+/** The blocked mark: an attention pill whose tooltip carries the reason and who it waits on. */
+export function BlockedBadge({ reason, by }: { reason: string; by?: string }) {
+ return (
+ <span title={S.company.tickets.blockedTooltip(reason, by ?? "—")} className="inline-flex">
+ <Badge tone="amber">{S.company.tickets.blocked}</Badge>
+ </span>
+ );
+}
+
+/** A principal's display name: an employee's name (or its id), a member's user id, "System", "Everyone". */
+export function principalLabel(principal: string, names: ReadonlyMap<string, string>): string {
+ const p = parsePrincipal(principal);
+ switch (p.kind) {
+ case "agent":
+ return names.get(p.id) ?? p.id;
+ case "user":
+ return p.id;
+ case "all":
+ return S.company.principalAll;
+ case "system":
+ return S.company.principalSystem;
+ default:
+ return p.raw;
+ }
+}
+
+/** A principal as an avatar plus its name (agents get their tile; people a plain initial disc). */
+export function PrincipalChip({
+ principal,
+ names,
+ size = 14,
+}: {
+ principal: string;
+ names: ReadonlyMap<string, string>;
+ size?: number;
+}) {
+ const p = parsePrincipal(principal);
+ const label = principalLabel(principal, names);
+ return (
+ <span className="inline-flex min-w-0 items-center gap-1.5">
+ {p.kind === "agent" ? (
+ <AgentAvatar id={p.id} name={label} size={size} className="shrink-0 rounded" />
+ ) : (
+ <span
+ aria-hidden
+ style={{ width: size, height: size, fontSize: Math.round(size * 0.6) }}
+ className="flex shrink-0 items-center justify-center rounded-full bg-gray-900 font-bold text-white dark:bg-gray-200 dark:text-gray-900"
+ >
+ {label.slice(0, 1).toUpperCase()}
+ </span>
+ )}
+ <span className="truncate">{label}</span>
+ </span>
+ );
+}
+
+/**
+ * One KPI as its own bordered card, the shape the cost center's summary uses: a small glyph
+ * beside the label, the value bold beneath it, and a line of detail under that. A tone inks
+ * the glyph and the value together, so the reading and its mark say the same thing. The card
+ * is plain elements — a KPI is a reading, not a control, and a whole-card click would swallow
+ * whatever sits inside it; anything extra rides beside the value as children (the finance
+ * page hangs its gauge there).
+ */
+export function StatTile({
+ icon,
+ label,
+ value,
+ tone,
+ detail,
+ children,
+}: {
+ /** A 24x24 line path, drawn through GlyphIcon like every other mark in the app. */
+ icon: string;
+ label: string;
+ value: ReactNode;
+ tone?: Tone;
+ /** One quiet line under the value: what the number is measured against. */
+ detail?: string;
+ children?: ReactNode;
+}) {
+ const ink = tone !== undefined ? toneInk[tone] : "";
+ return (
+ <div className="rounded-md border border-gray-200 bg-white p-3 dark:border-gray-800 dark:bg-gray-900">
+ <p
+ className={`mb-1.5 flex items-center ${ICON_GAP.row} text-[11px] text-gray-500 dark:text-gray-400`}
+ >
+ <GlyphIcon d={icon} size={ICON_SIZE.inlineGlyph} className={ink} />
+ <span className="truncate">{label}</span>
+ </p>
+ <div className="flex items-center justify-between gap-2">
+ <div className="min-w-0">
+ <p className={`truncate text-lg font-semibold tabular-nums ${ink}`}>{value}</p>
+ {detail !== undefined && (
+ <p className="mt-0.5 text-[11px] leading-snug text-gray-500 dark:text-gray-400">
+ {detail}
+ </p>
+ )}
+ </div>
+ {children}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/features/company/shell-org-status.ts b/packages/web/src/features/company/shell-org-status.ts
new file mode 100644
index 00000000..444d74d0
--- /dev/null
+++ b/packages/web/src/features/company/shell-org-status.ts
@@ -0,0 +1,42 @@
+/**
+ * The shell's organization status marks (pure, unit tested): the tone the switcher's dot and
+ * the overview's status pill take, and what a session-list group should render given what
+ * the store holds for it — so the sidebar never shows a skeleton for a fetch that already
+ * failed.
+ */
+import type { Tone } from "../../lib/tone";
+
+export type OrgStatusKind = "invalid" | "paused" | "active";
+
+/** An organization's headline state: invalid configuration outranks paused, paused outranks active. */
+export function orgStatusKind(org: {
+ status: "active" | "paused";
+ invalid?: string;
+}): OrgStatusKind {
+ if (org.invalid !== undefined) return "invalid";
+ return org.status === "paused" ? "paused" : "active";
+}
+
+/** The tone of that state: danger for a configuration that needs fixing, attention while paused, success while running. */
+export const ORG_STATUS_TONE: Record<OrgStatusKind, Tone> = {
+ invalid: "danger",
+ paused: "attention",
+ active: "success",
+};
+
+/**
+ * What a session-list group renders. The store drops an organization from its map when its
+ * sessions request fails, so "not in the map" means two different things: nothing has been
+ * fetched yet (a skeleton) or the fetch failed (an error line with a retry). `settled` says a
+ * fetch has completed at least once since the list mounted.
+ */
+export type GroupRender = "loading" | "error" | "empty" | "list";
+
+export function groupRender(input: {
+ loaded: boolean;
+ settled: boolean;
+ count: number;
+}): GroupRender {
+ if (input.loaded) return input.count === 0 ? "empty" : "list";
+ return input.settled ? "error" : "loading";
+}
diff --git a/packages/web/src/features/company/ticket-board.ts b/packages/web/src/features/company/ticket-board.ts
new file mode 100644
index 00000000..688fa003
--- /dev/null
+++ b/packages/web/src/features/company/ticket-board.ts
@@ -0,0 +1,128 @@
+/**
+ * The ticket board's shaping (pure, unit tested): the five columns in lifecycle order, how
+ * cards sort inside one, the blocked-only filter and the search box, which moves need a
+ * reason, the per-column counts the overview shows, the shape an id slug must take, and the
+ * two facts a card reads off a ticket's own fields — whether its due date has passed and the
+ * day its id was minted.
+ */
+import type {
+ OrgTicketItem,
+ OrgTicketStatus,
+ OrgTicketsResponse,
+} from "@prismshadow/penguin-server/api";
+
+/** The five kanban columns, in lifecycle order. */
+export const TICKET_COLUMNS: readonly OrgTicketStatus[] = [
+ "proposed",
+ "in_progress",
+ "review",
+ "done",
+ "rejected",
+];
+
+export function isTicketStatus(value: string | null | undefined): value is OrgTicketStatus {
+ return (TICKET_COLUMNS as readonly string[]).includes(value ?? "");
+}
+
+/**
+ * The shape of a ticket id's slug: lowercase letters in hyphen-joined words, no digits — the
+ * date prefix already carries the numbers. Mirrors TICKET_SLUG_PATTERN in the server's API
+ * contract, which the browser bundle cannot import as a value; the two must stay identical.
+ */
+export const TICKET_SLUG_PATTERN = /^[a-z]+(?:-[a-z]+)*$/;
+
+/** Whether a typed slug can be used as written; an empty box is not a slug and is left to the server. */
+export function isTicketSlug(value: string): boolean {
+ return TICKET_SLUG_PATTERN.test(value);
+}
+
+const PRIORITY_RANK: Record<string, number> = { P0: 0, P1: 1, P2: 2 };
+
+export function isBlocked(t: Pick<OrgTicketItem, "blocked">): boolean {
+ return t.blocked !== undefined && t.blocked !== "";
+}
+
+/**
+ * A column's cards: priority first (P0 above P2), earlier due date next, then the id — so the
+ * urgent and the overdue rise, and equal tickets keep a stable place across refetches.
+ */
+export function sortTickets<T extends Pick<OrgTicketItem, "priority" | "due" | "ticketId">>(
+ tickets: readonly T[],
+): T[] {
+ return [...tickets].sort(
+ (a, b) =>
+ (PRIORITY_RANK[a.priority] ?? 9) - (PRIORITY_RANK[b.priority] ?? 9) ||
+ (a.due ?? "￿").localeCompare(b.due ?? "￿") ||
+ a.ticketId.localeCompare(b.ticketId),
+ );
+}
+
+export interface BoardColumn {
+ status: OrgTicketStatus;
+ tickets: OrgTicketItem[];
+}
+
+/**
+ * The search box's match: case-insensitive, against the title, the id, the owner principal
+ * and the parent id, and — when the caller passes the chart's names — the owner's display
+ * name, so "dev" finds Dev's tickets whether the user thinks in ids or names.
+ */
+export function matchesTicketQuery(
+ t: Pick<OrgTicketItem, "title" | "ticketId" | "owner" | "parent">,
+ query: string,
+ names?: ReadonlyMap<string, string>,
+): boolean {
+ const q = query.trim().toLowerCase();
+ if (q === "") return true;
+ const ownerId = t.owner.startsWith("agent:") ? t.owner.slice(6) : null;
+ const ownerName = ownerId !== null ? names?.get(ownerId) : undefined;
+ return [t.title, t.ticketId, t.owner, t.parent, ownerName].some(
+ (v) => v !== undefined && v.toLowerCase().includes(q),
+ );
+}
+
+/** The board as rendered: every column, cards sorted, narrowed by the blocked-only switch and the search box. */
+export function boardColumns(
+ res: Pick<OrgTicketsResponse, "columns">,
+ opts: { blockedOnly?: boolean; query?: string; names?: ReadonlyMap<string, string> } = {},
+): BoardColumn[] {
+ return TICKET_COLUMNS.map((status) => {
+ const all = res.columns[status] ?? [];
+ const kept = all.filter(
+ (t) =>
+ (!opts.blockedOnly || isBlocked(t)) && matchesTicketQuery(t, opts.query ?? "", opts.names),
+ );
+ return { status, tickets: sortTickets(kept) };
+ });
+}
+
+/** Moving into `rejected` records a reason under Result; every other move is a bare status change. */
+export function moveNeedsReason(target: OrgTicketStatus): boolean {
+ return target === "rejected";
+}
+
+/** A drop is a move only across columns; dropping a card back on its own column changes nothing. */
+export function canMove(from: OrgTicketStatus, to: OrgTicketStatus): boolean {
+ return from !== to;
+}
+
+/** Every ticket of the board in column order — the parent picker's list and the id → title map. */
+export function allTickets(res: Pick<OrgTicketsResponse, "columns">): OrgTicketItem[] {
+ return TICKET_COLUMNS.flatMap((status) => res.columns[status] ?? []);
+}
+
+/** A due date (`yyyy-mm-dd`) is overdue once the local day `todayKey` (same form) has passed it. */
+export function isOverdue(due: string | undefined, todayKey: string): boolean {
+ return due !== undefined && /^\d{4}-\d{2}-\d{2}/.test(due) && due.slice(0, 10) < todayKey;
+}
+
+/** The day a ticket was minted, read off its id (`yyyy-mm-dd-<slug>`); null for an id in another shape. */
+export function ticketCreatedDate(ticketId: string): string | null {
+ const m = /^(\d{4}-\d{2}-\d{2})-/.exec(ticketId);
+ return m === null ? null : m[1]!;
+}
+
+/** Tickets the server flagged (status disagreeing with the column, a duplicate id), in column order. */
+export function invalidTickets(res: Pick<OrgTicketsResponse, "columns">): OrgTicketItem[] {
+ return allTickets(res).filter((t) => t.invalid !== undefined);
+}
diff --git a/packages/web/src/features/company/ticket-dialog.tsx b/packages/web/src/features/company/ticket-dialog.tsx
new file mode 100644
index 00000000..883e470a
--- /dev/null
+++ b/packages/web/src/features/company/ticket-dialog.tsx
@@ -0,0 +1,1087 @@
+/**
+ * A ticket's detail, as the dialog every company surface opens in place — the board, the
+ * finance ledger, the overview's inbox and a channel's ticket reference all put the same
+ * window on screen instead of carrying the reader to another page. The shell state says which
+ * ticket is open (state/company.tsx) and `TicketDialogHost`, mounted once by the organization
+ * layout, is what renders it.
+ *
+ * The header names the ticket with its priority chip on the same line, and carries the back
+ * control while a parent or a child has been followed from inside the dialog. The body holds,
+ * in reading order, the identity line (status, the blocked mark, the id with a copy button,
+ * this ticket's cost and the total), the blocked strip saying why and on whom it waits, the
+ * header fields (the one owner, parent, notify, due, created), the goal, the acceptance
+ * criteria, the progress prose with its one-line append, the result, and under them three
+ * disclosures folded on every visit: the child tickets with the total cost, the ticket's own
+ * sessions, and the operation history, newest first. Each editable section edits in place with
+ * its own save / cancel; the footer holds the block / unblock and move actions. Saves confirm
+ * first, like every organization write.
+ *
+ * Nothing here is a whole-row link: a child, a session and the parent are opened by their own
+ * small corner button, so a click always says where it lands. Only a session leaves the page —
+ * a conversation has no in-place form — and a parent or a child swaps the dialog's own ticket.
+ * A session's live status is not drawn: a ticket reports its own work, not what a session is
+ * doing this second.
+ */
+import { Fragment, useCallback, useEffect, useId, useState } from "react";
+import { useNavigate } from "react-router";
+import type {
+ OrgEmployeeItem,
+ OrgTicketDetail,
+ OrgTicketItem,
+ OrgTicketPriority,
+ OrgTicketStatus,
+ OrgTicketUpdateRequest,
+} from "@prismshadow/penguin-server/api";
+import type { ReactNode } from "react";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { formatDateTime, formatMoney } from "../../lib/format";
+import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
+import { toneInk, toneStrip } from "../../lib/tone";
+import { useAuth } from "../../state/auth";
+import { useCompany } from "../../state/company";
+import { useTheme } from "../../state/theme";
+import { Button } from "../../components/ui/button";
+import { Chevron } from "../../components/ui/chevron";
+import { Input, Textarea } from "../../components/ui/input";
+import { Select } from "../../components/ui/select";
+import { Segmented } from "../../components/ui/segmented";
+import { FieldLabel } from "../../components/ui/field";
+import { ConfirmModal } from "../../components/ui/confirm-modal";
+import { CloseButton } from "../../components/ui/icons";
+import { Modal } from "../../components/ui/modal";
+import { Skeleton } from "../../components/ui/skeleton";
+import { CopyButton, ROW_COPY_CLASS } from "../../components/ui/copy-button";
+import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";
+import { Md } from "../chat/md";
+import { OrgSection } from "./org-layout";
+import {
+ BlockedBadge,
+ JumpButton,
+ PrincipalChip,
+ PriorityBadge,
+ TicketStatusBadge,
+ principalLabel,
+} from "./shared";
+import { agentPrincipal, splitPrincipalList } from "./principals";
+import {
+ TICKET_COLUMNS,
+ allTickets,
+ isBlocked,
+ isOverdue,
+ moveNeedsReason,
+ ticketCreatedDate,
+} from "./ticket-board";
+import { ticketHistoryRows, ticketSummaryCounts } from "./ticket-history";
+import { dayKey } from "./calendar-geom";
+
+const PRIORITIES: readonly OrgTicketPriority[] = ["P0", "P1", "P2"];
+
+/** The sections that edit in place; one at a time, so a save always names what it rewrites. */
+type Section = "summary" | "goal" | "acceptance" | "result";
+
+interface SummaryDraft {
+ title: string;
+ owner: string;
+ parent: string;
+ notify: string;
+ priority: OrgTicketPriority;
+ due: string;
+}
+
+/**
+ * The one mount of the ticket dialog, rendered by the organization layout beside the routed
+ * page. Every surface opens a ticket by naming it in the shell state and this follows, so a
+ * detail is read where the reader already is — no page switch, and the dialog survives one.
+ */
+export function TicketDialogHost() {
+ const company = useCompany();
+ const target = company.ticketDialog;
+ if (target === null) return null;
+ return (
+ <TicketDialog
+ projectId={target.projectId}
+ orgId={target.orgId}
+ ticketId={target.ticketId}
+ canGoBack={company.ticketBackDepth > 0}
+ onBack={company.backTicket}
+ onClose={company.closeTicket}
+ onOpenTicket={(ticketId) => company.openTicket(target.projectId, target.orgId, ticketId)}
+ onChanged={company.ticketsChanged}
+ />
+ );
+}
+
+function TicketDialog({
+ projectId,
+ orgId,
+ ticketId,
+ canGoBack,
+ onBack,
+ onClose,
+ onChanged,
+ onOpenTicket,
+}: {
+ projectId: string;
+ orgId: string;
+ ticketId: string;
+ /** A parent or a child was followed to get here, so the header offers the way back. */
+ canGoBack: boolean;
+ onBack: () => void;
+ onClose: () => void;
+ /** A write landed: the surfaces listing tickets refetch off the shell's version. */
+ onChanged: () => void;
+ /** Swap the dialog's ticket for another (a child, the parent). */
+ onOpenTicket: (ticketId: string) => void;
+}) {
+ const navigate = useNavigate();
+ const company = useCompany();
+ const { currency } = useTheme();
+ const { user } = useAuth();
+ const me = user?.userId ?? null;
+ const [detail, setDetail] = useState<OrgTicketDetail | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ /** The organization's board and roster: the parent picker, the child titles, the owner options. */
+ const [tickets, setTickets] = useState<readonly OrgTicketItem[]>([]);
+ const [employees, setEmployees] = useState<readonly OrgEmployeeItem[]>([]);
+ /**
+ * The organization whose board and roster are on hand, set once that fetch settles — resolved
+ * or failed. Settled rather than succeeded: when it fails the ids are all this dialog has, and
+ * waiting for names that are never coming would hold the skeleton open forever.
+ */
+ const [contextOrg, setContextOrg] = useState<string | null>(null);
+ const [editing, setEditing] = useState<Section | null>(null);
+ const [summaryDraft, setSummaryDraft] = useState<SummaryDraft | null>(null);
+ const [textDraft, setTextDraft] = useState("");
+ const [pendingSave, setPendingSave] = useState<OrgTicketUpdateRequest | null>(null);
+ const [confirmUnblock, setConfirmUnblock] = useState(false);
+ const [blockOpen, setBlockOpen] = useState(false);
+ const [blockReason, setBlockReason] = useState("");
+ const [blockBy, setBlockBy] = useState("");
+ const [progressText, setProgressText] = useState("");
+ const [moveTarget, setMoveTarget] = useState("");
+ const [pendingMove, setPendingMove] = useState<OrgTicketStatus | null>(null);
+ const [busy, setBusy] = useState(false);
+ const names = new Map(employees.map((e) => [e.agentId, e.name]));
+ const titles = new Map(tickets.map((t) => [t.ticketId, t.title]));
+ /** Whether the board and roster on hand are this organization's, so the fields can read names. */
+ const contextReady = contextOrg === `${projectId}/${orgId}`;
+ const { tickets: ticketsVersion, runs: runsVersion } = company.versions;
+
+ const load = useCallback(async () => {
+ try {
+ setDetail(await api.getOrgTicket(projectId, orgId, ticketId));
+ setError(null);
+ } catch (e) {
+ setError(apiErrorText(e));
+ }
+ }, [projectId, orgId, ticketId]);
+ // Another ticket: start blank. A version bump on the same ticket refetches in place, so a
+ // board event under an open dialog never flashes the skeleton or drops an edit in progress.
+ useEffect(() => {
+ setDetail(null);
+ setError(null);
+ setEditing(null);
+ setMoveTarget("");
+ }, [ticketId]);
+ useEffect(() => {
+ void load();
+ }, [load, ticketsVersion, runsVersion]);
+
+ // The board and the roster the fields read against. Still best effort — a failure opens the
+ // dialog anyway, on the ids — but the first reveal waits for it: the owner, the parent, the
+ // children and every history line read an id until it lands and a name afterwards, and the
+ // two are different lengths, so showing the detail first reflows the whole panel under the
+ // reader. A later version bump refetches in place and never re-hides what is on screen.
+ useEffect(() => {
+ let cancelled = false;
+ void (async () => {
+ try {
+ const [board, chart] = await Promise.all([
+ api.listOrgTickets(projectId, orgId),
+ api.getOrgChart(projectId, orgId),
+ ]);
+ if (cancelled) return;
+ setTickets(allTickets(board));
+ setEmployees(chart.employees);
+ } catch {
+ // The detail itself is what the dialog is for; it carries its own error strip.
+ } finally {
+ if (!cancelled) setContextOrg(`${projectId}/${orgId}`);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [projectId, orgId, ticketsVersion]);
+
+ const run = async (work: () => Promise<void>, done?: string) => {
+ setBusy(true);
+ try {
+ await work();
+ if (done !== undefined) toastSuccess(done);
+ await load();
+ onChanged();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const startEdit = (section: Section) => {
+ if (detail === null) return;
+ if (section === "summary") {
+ setSummaryDraft({
+ title: detail.title,
+ owner: detail.owner,
+ parent: detail.parent ?? "",
+ notify: detail.notify.join(", "),
+ priority: detail.priority,
+ due: detail.due ?? "",
+ });
+ } else {
+ setTextDraft(
+ section === "goal"
+ ? detail.goal
+ : section === "acceptance"
+ ? detail.acceptanceCriteria
+ : detail.result,
+ );
+ }
+ setEditing(section);
+ };
+
+ /** What the open section changed, as the update body; nothing changed → a toast, no dialog. */
+ const requestSave = () => {
+ if (detail === null || editing === null) return;
+ const body: OrgTicketUpdateRequest = {};
+ if (editing === "summary" && summaryDraft !== null) {
+ const d = summaryDraft;
+ if (d.title.trim() && d.title.trim() !== detail.title) body.title = d.title.trim();
+ // A ticket always has an owner: an empty box is no change, never a clearing.
+ if (d.owner !== "" && d.owner !== detail.owner) body.owner = d.owner;
+ if (d.parent !== (detail.parent ?? "")) body.parent = d.parent === "" ? null : d.parent;
+ const notify = splitPrincipalList(d.notify);
+ if (notify.join(",") !== detail.notify.join(",")) body.notify = notify;
+ if (d.priority !== detail.priority) body.priority = d.priority;
+ if (d.due !== (detail.due ?? "")) body.due = d.due === "" ? null : d.due;
+ } else if (editing === "goal" && textDraft !== detail.goal) {
+ body.goal = textDraft;
+ } else if (editing === "acceptance" && textDraft !== detail.acceptanceCriteria) {
+ body.acceptanceCriteria = textDraft;
+ } else if (editing === "result" && textDraft !== detail.result) {
+ body.result = textDraft;
+ }
+ if (Object.keys(body).length === 0) {
+ toastInfo(S.common.noChangesToSave);
+ setEditing(null);
+ return;
+ }
+ setPendingSave(body);
+ };
+
+ const commitSave = () => {
+ if (detail === null || pendingSave === null) return;
+ const body = pendingSave;
+ setPendingSave(null);
+ void run(async () => {
+ await api.updateOrgTicket(projectId, orgId, detail.ticketId, body);
+ setEditing(null);
+ }, S.company.tickets.saved);
+ };
+
+ const addProgress = () => {
+ if (detail === null || !progressText.trim() || busy) return;
+ void run(async () => {
+ await api.progressOrgTicket(projectId, orgId, detail.ticketId, {
+ text: progressText.trim(),
+ });
+ setProgressText("");
+ });
+ };
+
+ /** The move the footer asked for, once its confirmation (a reason, when rejecting) is answered. */
+ const commitMove = (reason: string) => {
+ if (detail === null || pendingMove === null) return;
+ const to = pendingMove;
+ setPendingMove(null);
+ void run(async () => {
+ await api.moveOrgTicket(projectId, orgId, detail.ticketId, {
+ status: to,
+ ...(moveNeedsReason(to) ? { reason: reason.trim() } : {}),
+ });
+ setMoveTarget("");
+ }, S.company.tickets.moved);
+ };
+
+ const children = (detail?.children ?? []).map(
+ (id) => tickets.find((t) => t.ticketId === id) ?? { ticketId: id, title: id },
+ );
+ const blocked = detail !== null && isBlocked(detail);
+ const todayKey = dayKey(Date.now());
+ const created = detail === null ? null : ticketCreatedDate(detail.ticketId);
+ const counts = detail === null ? null : ticketSummaryCounts(detail);
+ const history = detail === null ? [] : ticketHistoryRows(detail.history);
+ /** A history line's principal: the employee's name, "you" for the reader, else the user id. */
+ const historyPrincipal = (principal: string) =>
+ me !== null && principal === `user:${me}`
+ ? S.company.channels.you
+ : principalLabel(principal, names);
+ /**
+ * The owner picker's options. Employees first; a ticket owned by a person keeps that owner
+ * on the list, so opening the form does not silently reassign it to the first employee.
+ */
+ const ownerOptions = [
+ ...employees.map((e) => ({ value: agentPrincipal(e.agentId), label: e.name })),
+ ...(detail !== null && !employees.some((e) => agentPrincipal(e.agentId) === detail.owner)
+ ? [{ value: detail.owner, label: principalLabel(detail.owner, names) }]
+ : []),
+ ];
+
+ /** A section's trailing controls: an edit button at rest, cancel / save while it is open. */
+ const sectionActions = (section: Section) =>
+ editing === section ? (
+ <>
+ <Button size="sm" variant="ghost" disabled={busy} onClick={() => setEditing(null)}>
+ {S.common.cancel}
+ </Button>
+ <Button size="sm" variant="primary" disabled={busy} onClick={requestSave}>
+ {S.common.save}
+ </Button>
+ </>
+ ) : (
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={busy || editing !== null}
+ onClick={() => startEdit(section)}
+ >
+ {S.common.edit}
+ </Button>
+ );
+
+ /** A Markdown body, or its "nothing here yet" line; a textarea while the section is open. */
+ const textSection = (section: Exclude<Section, "summary">, text: string, empty: string) =>
+ editing === section ? (
+ <Textarea
+ size="sm"
+ rows={6}
+ aria-label={S.company.tickets[section]}
+ value={textDraft}
+ autoFocus
+ onChange={(e) => setTextDraft(e.target.value)}
+ />
+ ) : text.trim() === "" ? (
+ <p className="text-xs text-gray-400 dark:text-gray-500">{empty}</p>
+ ) : (
+ <div className="md-body text-sm leading-relaxed text-gray-800 dark:text-gray-100">
+ <Md text={text} />
+ </div>
+ );
+
+ /**
+ * One field of the summary grid. Every row is exactly one line tall, so labels and values
+ * line up down the column: anything taller than the line — the parent's jump button is the
+ * only such thing — pulls its own box back in with a negative margin rather than growing
+ * the row and pushing its label off the others' baseline.
+ */
+ const row = (label: string, value: ReactNode) => (
+ <>
+ <dt className="whitespace-nowrap text-gray-500 dark:text-gray-400">{label}</dt>
+ <dd className="flex min-w-0 items-center gap-1.5 text-gray-800 dark:text-gray-100">
+ {value}
+ </dd>
+ </>
+ );
+
+ return (
+ // Headerless and bare: the header below carries the back control and the priority chip
+ // beside the title, and the body owns its own scroller so the footer stays on screen.
+ <Modal
+ open
+ title={detail?.title ?? S.company.tickets.detail}
+ onClose={onClose}
+ headerless
+ bare
+ widthClass="sm:max-w-3xl"
+ >
+ <div className="flex max-h-[85vh] flex-col">
+ <div className="flex shrink-0 items-center gap-2 border-b border-gray-200 px-4 py-3 dark:border-gray-800">
+ {canGoBack && (
+ <Button size="sm" variant="ghost" onClick={onBack}>
+ {S.company.tickets.back}
+ </Button>
+ )}
+ {/* The priority sits on the title's line, one size under it: it is read with the
+ title, and a chip of its own line would push the ticket's first words down. */}
+ <h2 className="flex min-w-0 flex-1 items-center gap-2 text-base font-semibold">
+ <span className="min-w-0 truncate">{detail?.title ?? S.company.tickets.detail}</span>
+ {detail !== null && (
+ <span className="shrink-0">
+ <PriorityBadge priority={detail.priority} />
+ </span>
+ )}
+ </h2>
+ <CloseButton onClose={onClose} />
+ </div>
+
+ <div className="min-h-0 flex-1 space-y-5 overflow-y-auto px-4 py-4 sm:px-6">
+ {error !== null && detail === null ? (
+ <div
+ className={`flex flex-wrap items-center justify-between gap-2 rounded-md border px-3 py-2 text-xs ${toneStrip.danger}`}
+ >
+ <span>{error}</span>
+ <Button size="sm" onClick={() => void load()}>
+ {S.common.retry}
+ </Button>
+ </div>
+ ) : detail === null || !contextReady ? (
+ <div className="space-y-5">
+ <div className="flex gap-2">
+ <Skeleton className="h-5 w-14 rounded-full" />
+ <Skeleton className="h-5 w-10 rounded-full" />
+ <Skeleton className="h-5 w-40" />
+ </div>
+ <Skeleton className="h-28" />
+ <Skeleton className="h-20" />
+ <Skeleton className="h-20" />
+ </div>
+ ) : (
+ <>
+ {/* Identity line: status, the blocked mark, the id with its copy, the cost. */}
+ <div className="flex flex-wrap items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
+ <TicketStatusBadge status={detail.status} />
+ {blocked && (
+ <BlockedBadge
+ reason={detail.blocked ?? ""}
+ {...(detail.blockedBy !== undefined ? { by: detail.blockedBy } : {})}
+ />
+ )}
+ <span className="inline-flex items-center gap-0.5 font-mono">
+ {detail.ticketId}
+ <CopyButton
+ text={detail.ticketId}
+ label={S.company.tickets.copyId}
+ className={ROW_COPY_CLASS}
+ />
+ </span>
+ <span className="ml-auto tabular-nums">
+ {S.company.tickets.cost}{" "}
+ <span className="font-medium text-gray-700 dark:text-gray-200">
+ {formatMoney(detail.cost, currency)}
+ </span>
+ {" · "}
+ {S.company.tickets.rolledUpCost}{" "}
+ <span className="font-medium text-gray-700 dark:text-gray-200">
+ {formatMoney(detail.rolledUpCost, currency)}
+ </span>
+ </span>
+ </div>
+ {detail.invalid !== undefined && (
+ <div className={`rounded-md border px-3 py-2 text-xs ${toneStrip.danger}`}>
+ {detail.invalid}
+ </div>
+ )}
+ {blocked && (
+ <div
+ className={`flex flex-wrap items-center gap-x-3 gap-y-1 rounded-md border px-3 py-2 text-xs ${toneStrip.attention}`}
+ >
+ <span>
+ <span className="font-medium">{S.company.tickets.blockedReason}:</span>{" "}
+ {detail.blocked}
+ </span>
+ {detail.blockedBy !== undefined && (
+ <span className="inline-flex items-center gap-1.5">
+ <span>{S.company.tickets.blockedBy}:</span>
+ <PrincipalChip principal={detail.blockedBy} names={names} />
+ </span>
+ )}
+ </div>
+ )}
+
+ {/* Summary: the header fields as a definition list, a form while editing. */}
+ <OrgSection title={S.company.tickets.summary} actions={sectionActions("summary")}>
+ {editing === "summary" && summaryDraft !== null ? (
+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
+ <div className="md:col-span-2">
+ <Input
+ size="sm"
+ label={S.company.tickets.ticketTitle}
+ required
+ value={summaryDraft.title}
+ onChange={(e) =>
+ setSummaryDraft({ ...summaryDraft, title: e.target.value })
+ }
+ />
+ </div>
+ <Select
+ size="sm"
+ label={S.company.tickets.owner}
+ value={summaryDraft.owner}
+ onChange={(e) => setSummaryDraft({ ...summaryDraft, owner: e.target.value })}
+ >
+ {ownerOptions.map((o) => (
+ <option key={o.value} value={o.value}>
+ {o.label}
+ </option>
+ ))}
+ </Select>
+ <Select
+ size="sm"
+ label={S.company.tickets.parent}
+ value={summaryDraft.parent}
+ onChange={(e) => setSummaryDraft({ ...summaryDraft, parent: e.target.value })}
+ >
+ <option value="">{S.company.tickets.noParent}</option>
+ {tickets
+ .filter((t) => t.ticketId !== detail.ticketId)
+ .map((t) => (
+ <option key={t.ticketId} value={t.ticketId}>
+ {t.title}
+ </option>
+ ))}
+ </Select>
+ <div>
+ <FieldLabel>{S.company.tickets.priority}</FieldLabel>
+ <Segmented
+ options={PRIORITIES.map((p) => ({ value: p, label: p }))}
+ value={summaryDraft.priority}
+ onChange={(priority) => setSummaryDraft({ ...summaryDraft, priority })}
+ cols={3}
+ />
+ </div>
+ <Input
+ size="sm"
+ label={S.company.tickets.due}
+ type="date"
+ value={summaryDraft.due}
+ className="font-mono"
+ onChange={(e) => setSummaryDraft({ ...summaryDraft, due: e.target.value })}
+ />
+ <div className="md:col-span-2">
+ <Input
+ size="sm"
+ label={S.company.tickets.notify}
+ value={summaryDraft.notify}
+ hint={S.company.tickets.notifyHint}
+ className="font-mono"
+ onChange={(e) =>
+ setSummaryDraft({ ...summaryDraft, notify: e.target.value })
+ }
+ />
+ </div>
+ </div>
+ ) : (
+ <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5 text-xs">
+ {row(
+ S.company.tickets.owner,
+ <PrincipalChip principal={detail.owner} names={names} />,
+ )}
+ {row(
+ S.company.tickets.parent,
+ detail.parent !== undefined ? (
+ <>
+ <span className="min-w-0 truncate" title={detail.parent}>
+ {titles.get(detail.parent) ?? detail.parent}
+ </span>
+ <JumpButton
+ label={S.company.tickets.openTicket}
+ className="-my-1"
+ onClick={() => onOpenTicket(detail.parent!)}
+ />
+ </>
+ ) : (
+ <span className="text-gray-400 dark:text-gray-500">
+ {S.company.tickets.noParent}
+ </span>
+ ),
+ )}
+ {row(
+ S.company.tickets.notify,
+ detail.notify.length === 0 ? (
+ <span className="text-gray-400 dark:text-gray-500">{S.common.none}</span>
+ ) : (
+ <span className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1">
+ {detail.notify.map((p) => (
+ <PrincipalChip key={p} principal={p} names={names} />
+ ))}
+ </span>
+ ),
+ )}
+ {row(
+ S.company.tickets.due,
+ detail.due !== undefined ? (
+ <span
+ className={`font-mono tabular-nums ${
+ isOverdue(detail.due, todayKey) &&
+ detail.status !== "done" &&
+ detail.status !== "rejected"
+ ? toneInk.danger
+ : ""
+ }`}
+ >
+ {detail.due}
+ {isOverdue(detail.due, todayKey) &&
+ detail.status !== "done" &&
+ detail.status !== "rejected" &&
+ ` · ${S.company.tickets.overdue}`}
+ </span>
+ ) : (
+ <span className="text-gray-400 dark:text-gray-500">
+ {S.company.tickets.noDue}
+ </span>
+ ),
+ )}
+ {created !== null &&
+ row(
+ S.common.created,
+ <span className="font-mono tabular-nums">{created}</span>,
+ )}
+ </dl>
+ )}
+ </OrgSection>
+
+ <OrgSection title={S.company.tickets.goal} actions={sectionActions("goal")}>
+ {textSection("goal", detail.goal, S.company.tickets.noGoal)}
+ </OrgSection>
+
+ <OrgSection
+ title={S.company.tickets.acceptance}
+ actions={sectionActions("acceptance")}
+ >
+ {textSection(
+ "acceptance",
+ detail.acceptanceCriteria,
+ S.company.tickets.noAcceptance,
+ )}
+ </OrgSection>
+
+ {/* Progress: the sentences as written, oldest first, plus the one-line append.
+ Who wrote one and when is a history entry, not a chip on the sentence; the
+ bullets are md-compact so a one-line note reads as a line, not a paragraph. */}
+ <OrgSection title={S.company.tickets.progress}>
+ {detail.progress.length === 0 ? (
+ <p className="text-xs text-gray-400 dark:text-gray-500">
+ {S.company.tickets.progressEmpty}
+ </p>
+ ) : (
+ <ul className="md-body md-compact list-disc pl-5 text-sm text-gray-800 marker:text-gray-400 dark:text-gray-100 dark:marker:text-gray-500">
+ {detail.progress.map((p, i) => (
+ <li key={`${i}-${p}`}>
+ <Md text={p} />
+ </li>
+ ))}
+ </ul>
+ )}
+ <div className="mt-3 flex items-center gap-2">
+ <div className="min-w-0 flex-1">
+ <Input
+ size="sm"
+ aria-label={S.company.tickets.addProgress}
+ placeholder={S.company.tickets.progressPlaceholder}
+ value={progressText}
+ onChange={(e) => setProgressText(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.nativeEvent.isComposing) addProgress();
+ }}
+ />
+ </div>
+ <Button size="sm" disabled={busy || !progressText.trim()} onClick={addProgress}>
+ {S.company.tickets.addProgress}
+ </Button>
+ </div>
+ </OrgSection>
+
+ <OrgSection title={S.company.tickets.result} actions={sectionActions("result")}>
+ {textSection("result", detail.result, S.company.tickets.noResult)}
+ </OrgSection>
+
+ {/* The child tickets, folded: a plain list, each row opened by its own button. */}
+ <Fold
+ title={S.company.tickets.children}
+ summary={
+ counts === null || counts.childrenEmpty
+ ? S.common.none
+ : `${counts.children} · ${S.company.tickets.rolledUpCost} ${formatMoney(detail.rolledUpCost, currency)}`
+ }
+ >
+ {children.length === 0 ? (
+ <p className="text-xs text-gray-400 dark:text-gray-500">
+ {S.company.tickets.childrenEmpty}
+ </p>
+ ) : (
+ <ul className="space-y-0.5">
+ {children.map((c) => (
+ <li key={c.ticketId} className="flex items-center gap-2 px-2 py-1.5 text-sm">
+ <span className="min-w-0 flex-1 truncate" title={c.ticketId}>
+ {c.title}
+ </span>
+ {"status" in c && <TicketStatusBadge status={c.status} />}
+ {"owner" in c && (
+ <span className="shrink-0 text-xs text-gray-600 dark:text-gray-300">
+ <PrincipalChip principal={c.owner} names={names} />
+ </span>
+ )}
+ {"cost" in c && (
+ <span
+ className="shrink-0 font-mono text-[11px] tabular-nums text-gray-400 dark:text-gray-500"
+ title={S.company.tickets.cost}
+ >
+ {formatMoney(c.cost, currency)}
+ </span>
+ )}
+ <JumpButton
+ label={S.company.tickets.openTicket}
+ onClick={() => onOpenTicket(c.ticketId)}
+ />
+ </li>
+ ))}
+ </ul>
+ )}
+ </Fold>
+
+ {/* The sessions this ticket was worked in, folded. They are opened from here and
+ nowhere else: starting one and attaching one belong to the owner's desk and to
+ the CLI, not to a reader of the board. */}
+ <Fold
+ title={S.company.tickets.sessions}
+ summary={
+ counts === null || counts.sessionsEmpty
+ ? S.common.none
+ : S.company.tickets.sessionsCount(counts.sessions)
+ }
+ >
+ {detail.sessionItems.length === 0 ? (
+ <p className="text-xs text-gray-400 dark:text-gray-500">{S.common.none}</p>
+ ) : (
+ <ul className="space-y-0.5">
+ {detail.sessionItems.map((s) => (
+ <li key={s.sessionId} className="flex items-center gap-2 px-2 py-1.5 text-sm">
+ <PrincipalChip principal={agentPrincipal(s.agentId)} names={names} />
+ <span className="min-w-0 flex-1 truncate text-gray-600 dark:text-gray-300">
+ {s.title ?? s.sessionId}
+ </span>
+ {s.lastActiveAt !== undefined && (
+ <span className="shrink-0 font-mono text-[11px] tabular-nums text-gray-400 dark:text-gray-500">
+ {formatDateTime(s.lastActiveAt)}
+ </span>
+ )}
+ {/* The one way out of the dialog: a conversation has no in-place form,
+ so opening a session closes this and lands on it. */}
+ <JumpButton
+ label={S.company.tickets.openSession}
+ onClick={() => {
+ onClose();
+ navigate(`/chat/${s.sessionId}`);
+ }}
+ />
+ </li>
+ ))}
+ </ul>
+ )}
+ </Fold>
+
+ {/* Every write the ticket file recorded, newest first. */}
+ <Fold
+ title={S.company.tickets.history}
+ summary={history.length === 0 ? S.common.none : `${history.length}`}
+ >
+ {history.length === 0 ? (
+ <p className="text-xs text-gray-400 dark:text-gray-500">
+ {S.company.tickets.historyEmpty}
+ </p>
+ ) : (
+ <ol className="space-y-1.5 text-xs">
+ {history.map((h) => {
+ const parts: ReactNode[] = [
+ // A ticket converted from the format that predates the history has no
+ // time on its first entry; the line then starts with who did it.
+ ...(h.at === ""
+ ? []
+ : [
+ <span
+ key="at"
+ className="shrink-0 font-mono tabular-nums text-gray-400 dark:text-gray-500"
+ title={h.at}
+ >
+ {formatDateTime(h.at)}
+ </span>,
+ ]),
+ <span key="by" className="text-gray-700 dark:text-gray-200">
+ {historyPrincipal(h.by)}
+ </span>,
+ <span key="action" className="text-gray-500 dark:text-gray-400">
+ {S.company.tickets.historyActions[h.action] ?? h.action}
+ </span>,
+ ];
+ return (
+ <li
+ key={h.key}
+ className="flex flex-wrap items-baseline gap-x-1.5 gap-y-0.5 text-gray-600 dark:text-gray-300"
+ >
+ {parts.map((part, i) => (
+ <Fragment key={i}>
+ {i > 0 && (
+ <span aria-hidden className="text-gray-300 dark:text-gray-600">
+ ·
+ </span>
+ )}
+ {part}
+ </Fragment>
+ ))}
+ </li>
+ );
+ })}
+ </ol>
+ )}
+ </Fold>
+ </>
+ )}
+ </div>
+
+ {/* Footer: block / unblock on the left, the move on the right. */}
+ {detail !== null && (
+ <div className="flex shrink-0 flex-wrap items-center gap-2 border-t border-gray-200 px-4 py-3 dark:border-gray-800">
+ {blocked ? (
+ <Button size="sm" disabled={busy} onClick={() => setConfirmUnblock(true)}>
+ {S.company.tickets.unblock}
+ </Button>
+ ) : (
+ <Button size="sm" disabled={busy} onClick={() => setBlockOpen(true)}>
+ {S.company.tickets.block}
+ </Button>
+ )}
+ <div className="ml-auto flex items-center gap-2">
+ <div className="w-36">
+ <Select
+ size="sm"
+ aria-label={S.company.tickets.moveTitle}
+ value={moveTarget}
+ onChange={(e) => setMoveTarget(e.target.value)}
+ >
+ <option value="">{S.company.tickets.moveTo}</option>
+ {TICKET_COLUMNS.filter((s) => s !== detail.status).map((s) => (
+ <option key={s} value={s}>
+ {S.company.tickets.columns[s] ?? s}
+ </option>
+ ))}
+ </Select>
+ </div>
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={busy || moveTarget === ""}
+ onClick={() => {
+ const to = TICKET_COLUMNS.find((s) => s === moveTarget);
+ if (to !== undefined) setPendingMove(to);
+ }}
+ >
+ {S.company.tickets.move}
+ </Button>
+ </div>
+ </div>
+ )}
+ </div>
+
+ <MoveTicketConfirm
+ move={
+ detail === null || pendingMove === null ? null : { title: detail.title, to: pendingMove }
+ }
+ busy={busy}
+ onClose={() => (busy ? undefined : setPendingMove(null))}
+ onConfirm={commitMove}
+ />
+ <ConfirmModal
+ open={pendingSave !== null}
+ title={S.common.confirmSaveTitle}
+ tone="primary"
+ confirmLabel={S.common.save}
+ busy={busy}
+ onClose={() => (busy ? undefined : setPendingSave(null))}
+ onConfirm={commitSave}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {S.company.tickets.saveConfirm(detail?.title ?? "")}
+ </p>
+ </ConfirmModal>
+ <ConfirmModal
+ open={confirmUnblock}
+ title={S.company.tickets.unblock}
+ tone="primary"
+ confirmLabel={S.common.confirm}
+ busy={busy}
+ onClose={() => (busy ? undefined : setConfirmUnblock(false))}
+ onConfirm={() => {
+ if (detail === null) return;
+ setConfirmUnblock(false);
+ void run(async () => {
+ await api.unblockOrgTicket(projectId, orgId, detail.ticketId);
+ });
+ }}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {S.company.tickets.unblockConfirm(detail?.title ?? "")}
+ </p>
+ </ConfirmModal>
+ <Modal
+ open={blockOpen}
+ title={S.company.tickets.blockTitle}
+ onClose={() => setBlockOpen(false)}
+ footer={
+ <>
+ <Button size="sm" onClick={() => setBlockOpen(false)} disabled={busy}>
+ {S.common.cancel}
+ </Button>
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={busy || !blockReason.trim()}
+ onClick={() => {
+ if (detail === null) return;
+ setBlockOpen(false);
+ void run(async () => {
+ await api.blockOrgTicket(projectId, orgId, detail.ticketId, {
+ reason: blockReason.trim(),
+ ...(blockBy.trim() ? { by: blockBy.trim() } : {}),
+ });
+ setBlockReason("");
+ setBlockBy("");
+ });
+ }}
+ >
+ {S.company.tickets.block}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ <Input
+ size="sm"
+ label={S.company.tickets.blockedReason}
+ required
+ value={blockReason}
+ hint={S.company.tickets.blockReasonHint}
+ autoFocus
+ onChange={(e) => setBlockReason(e.target.value)}
+ />
+ <Input
+ size="sm"
+ label={S.company.tickets.blockedBy}
+ value={blockBy}
+ hint={S.company.tickets.blockByHint}
+ className="font-mono"
+ onChange={(e) => setBlockBy(e.target.value)}
+ />
+ </div>
+ </Modal>
+ </Modal>
+ );
+}
+
+/**
+ * The confirmation every move goes through, wherever the move was asked for — the board's
+ * drag-and-drop and the dialog's footer — so a card dropped in a column and a ticket moved
+ * from its detail ask the same question. Moving into rejected also asks for the one-line
+ * reason that is recorded under the ticket's result; the box empties whenever a new move is
+ * proposed, so yesterday's wording cannot ride along.
+ */
+export function MoveTicketConfirm({
+ move,
+ busy,
+ onClose,
+ onConfirm,
+}: {
+ /** The move waiting for an answer, or null when none is. */
+ move: { title: string; to: OrgTicketStatus } | null;
+ busy: boolean;
+ onClose: () => void;
+ onConfirm: (reason: string) => void;
+}) {
+ const [reason, setReason] = useState("");
+ // Emptied on the move itself, never on the object carrying it: the callers build that inline,
+ // so a dependency on its identity would clear the box on every keystroke's render.
+ const movedTitle = move?.title ?? null;
+ const movedTo = move?.to ?? null;
+ useEffect(() => {
+ setReason("");
+ }, [movedTitle, movedTo]);
+ const needsReason = move !== null && moveNeedsReason(move.to);
+ return (
+ <ConfirmModal
+ open={move !== null}
+ title={S.company.tickets.moveTitle}
+ tone={move?.to === "rejected" ? "danger" : "primary"}
+ confirmLabel={S.common.confirm}
+ confirmDisabled={needsReason && reason.trim() === ""}
+ busy={busy}
+ onClose={onClose}
+ onConfirm={() => onConfirm(reason)}
+ >
+ <div className="space-y-2">
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {move !== null
+ ? S.company.tickets.moveConfirm(
+ move.title,
+ S.company.tickets.columns[move.to] ?? move.to,
+ )
+ : ""}
+ </p>
+ {needsReason && (
+ <Input
+ size="sm"
+ label={S.company.tickets.rejectReason}
+ required
+ value={reason}
+ hint={S.company.tickets.rejectReasonHint}
+ autoFocus
+ onChange={(e) => setReason(e.target.value)}
+ />
+ )}
+ </div>
+ </ConfirmModal>
+ );
+}
+
+/**
+ * A section of the dialog that is folded on every visit: the ruled header of `OrgSection`
+ * with the app's one collapse chevron in front of it, and what it holds after it — a count,
+ * a count and a cost — so a reader decides from the closed row whether to open it. The panel
+ * stays in the DOM and is `hidden` while collapsed — the WAI-ARIA disclosure pattern, so
+ * `aria-controls` always resolves — and nothing is persisted: what hangs off a ticket is
+ * looked up, not tracked.
+ */
+function Fold({
+ title,
+ summary,
+ children,
+}: {
+ title: string;
+ /** What the closed row reports: the counts, or "none" when there is nothing inside. */
+ summary: string;
+ children: ReactNode;
+}) {
+ const [open, setOpen] = useState(false);
+ const panelId = useId();
+ return (
+ <section className="min-w-0">
+ <button
+ type="button"
+ aria-expanded={open}
+ aria-controls={panelId}
+ onClick={() => setOpen((v) => !v)}
+ className={`flex w-full items-center ${ICON_GAP.row} border-b border-gray-200 pb-2 text-left text-[11px] font-semibold uppercase tracking-wide text-gray-500 transition-colors duration-150 hover:text-gray-800 dark:border-gray-800 dark:text-gray-400 dark:hover:text-gray-200`}
+ >
+ <Chevron open={open} size={ICON_SIZE.chevronDense} />
+ <span className="min-w-0 truncate">{title}</span>
+ <span className="min-w-0 truncate font-normal normal-case tracking-normal text-gray-400 dark:text-gray-500">
+ · {summary}
+ </span>
+ </button>
+ <div id={panelId} hidden={!open} className="mt-3 space-y-4">
+ {children}
+ </div>
+ </section>
+ );
+}
diff --git a/packages/web/src/features/company/ticket-history.ts b/packages/web/src/features/company/ticket-history.ts
new file mode 100644
index 00000000..57bb6192
--- /dev/null
+++ b/packages/web/src/features/company/ticket-history.ts
@@ -0,0 +1,52 @@
+/**
+ * The drawer's shaping of what hangs off a ticket (pure, unit tested): the operation history
+ * the ticket's frontmatter carries — newest first, and as a bare `time · principal · action`
+ * line, because what an action wrote is already the section it wrote into — and the counts
+ * the two folded lists report from their closed headers.
+ */
+import type {
+ OrgTicketDetail,
+ OrgTicketHistoryAction,
+ OrgTicketHistoryEntry,
+} from "@prismshadow/penguin-server/api";
+
+export interface TicketHistoryRow {
+ /** Stable across refetches: the entries themselves carry no id. */
+ key: string;
+ at: string;
+ by: string;
+ action: OrgTicketHistoryAction;
+}
+
+/**
+ * The history as the drawer lists it: newest first, and only what happened — an entry's
+ * `note` is left unread, so the history stays a log of operations rather than a second copy
+ * of the progress, the block reason and the fields an edit touched.
+ */
+export function ticketHistoryRows(history: readonly OrgTicketHistoryEntry[]): TicketHistoryRow[] {
+ return history
+ .map((entry, i) => ({
+ key: `${i}-${entry.at}-${entry.action}`,
+ at: entry.at,
+ by: entry.by,
+ action: entry.action,
+ }))
+ .reverse();
+}
+
+export interface TicketSummaryCounts {
+ children: number;
+ sessions: number;
+ /** Per list: an empty one still shows its fold, with "none" where the count would be. */
+ childrenEmpty: boolean;
+ sessionsEmpty: boolean;
+}
+
+/** What each folded list's header counts: the child tickets, and the ticket's own sessions. */
+export function ticketSummaryCounts(
+ detail: Pick<OrgTicketDetail, "children" | "sessionItems">,
+): TicketSummaryCounts {
+ const children = detail.children.length;
+ const sessions = detail.sessionItems.length;
+ return { children, sessions, childrenEmpty: children === 0, sessionsEmpty: sessions === 0 };
+}
diff --git a/packages/web/src/features/company/tickets-page.tsx b/packages/web/src/features/company/tickets-page.tsx
new file mode 100644
index 00000000..a04dbe41
--- /dev/null
+++ b/packages/web/src/features/company/tickets-page.tsx
@@ -0,0 +1,755 @@
+/**
+ * The ticket board: five columns in lifecycle order (shaping in ticket-board.ts), each with
+ * its colour bar and count, a card per ticket — title, priority, due date (danger once
+ * passed), the blocked badge, a muted line naming its parent, and its owner — a search box
+ * and a blocked-only switch, drag-and-drop between columns that confirms the move (a move
+ * into rejected asks for a one-line reason) before posting it, the create form, and the
+ * tickets and files the server could not accept.
+ * The whole card is the drag handle, and its title is the one click target: the title is a
+ * text button that opens the detail dialog (the shell's one host renders it, so the board
+ * stays where it is), the rest of the card is inert, and a drag never fires a click — so
+ * dragging anywhere (the title included) moves the ticket while clicking the title opens it.
+ * The priority rides on the title's line, one size under it. What a card deliberately does
+ * not carry is the session count, the cost and any live session status — those are the
+ * dialog's, and a ticket is not the place to watch a session run.
+ * The board is always on screen: a skeleton of it until the first fetch, the empty columns
+ * as drop zones — with a one-line note above them while the organization has no tickets at
+ * all, dismissible and repeated in the page's "?" — the board plus an error strip when a
+ * refetch fails.
+ * `?column=` / `?blocked=1` deep links arrive from the overview, and `?ticket=` is this
+ * page's own: it opens the dialog on arrival and follows it while it is open, so a ticket
+ * being read can be linked to and survives a reload. No other page writes it — the dialog is
+ * shell state, not a route.
+ */
+import { useCallback, useEffect, useRef, useState } from "react";
+import type { DragEvent as ReactDragEvent } from "react";
+import { useSearchParams } from "react-router";
+import type {
+ OrgChartResponse,
+ OrgTicketItem,
+ OrgTicketPriority,
+ OrgTicketStatus,
+ OrgTicketsResponse,
+} from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { useDocumentTitle } from "../../lib/use-document-title";
+import { toneDot, toneInk, toneStrip } from "../../lib/tone";
+import { ICON_SIZE } from "../../lib/icon-scale";
+import { useAuth } from "../../state/auth";
+import { useCompany } from "../../state/company";
+import { Button } from "../../components/ui/button";
+import { Switch } from "../../components/ui/switch";
+import { Segmented } from "../../components/ui/segmented";
+import { Modal } from "../../components/ui/modal";
+import { Input, Textarea } from "../../components/ui/input";
+import { Select } from "../../components/ui/select";
+import { FieldLabel } from "../../components/ui/field";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { CloseIcon } from "../../components/ui/icons";
+import { Skeleton } from "../../components/ui/skeleton";
+import { toastError, toastSuccess } from "../../components/ui/toast";
+import { OrgPage, useOrg } from "./org-layout";
+import {
+ BlockedBadge,
+ INVALID_ICON,
+ PrincipalChip,
+ PriorityBadge,
+ TitleButton,
+ principalLabel,
+} from "./shared";
+import {
+ TICKET_COLUMNS,
+ allTickets,
+ boardColumns,
+ canMove,
+ invalidTickets,
+ isBlocked,
+ isOverdue,
+ isTicketSlug,
+ isTicketStatus,
+ moveNeedsReason,
+} from "./ticket-board";
+import { MoveTicketConfirm } from "./ticket-dialog";
+import { dismissHint, hintKey, isHintDismissed } from "./page-hints";
+import { agentPrincipal, splitPrincipalList } from "./principals";
+import { dayKey } from "./calendar-geom";
+
+/** Private drag payload type of a card move (never text/plain: a mis-aimed drop must not paste into a text field). */
+const TICKET_DRAG_MIME = "application/x-penguin-ticket-id";
+const PRIORITIES: readonly OrgTicketPriority[] = ["P0", "P1", "P2"];
+
+/** Clock face (lucide): the due-date mark on a card. */
+const DUE_ICON = "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zm0-14v5l3 2";
+
+/**
+ * The colour bar atop each column. Proposed is neutral, in-progress takes the accent (it is
+ * the column being worked, not a judgement), review waits on a person (attention), done is
+ * finished well (success), rejected is danger.
+ */
+const COLUMN_BAR: Record<OrgTicketStatus, string> = {
+ proposed: "bg-gray-300 dark:bg-gray-600",
+ in_progress: "bg-[var(--accent-bg)]",
+ review: toneDot.attention,
+ done: toneDot.success,
+ rejected: toneDot.danger,
+};
+
+const columnClass =
+ "flex min-h-[26rem] flex-col rounded-md border border-gray-200 bg-gray-50/60 transition-colors duration-150 dark:border-gray-800 dark:bg-gray-900/40";
+
+export function TicketsPage() {
+ const { projectId, orgId, org } = useOrg();
+ const company = useCompany();
+ const { user } = useAuth();
+ const [params, setParams] = useSearchParams();
+ useDocumentTitle(org ? `${org.name} · ${S.nav.org.tickets}` : S.nav.org.tickets);
+ const [board, setBoard] = useState<OrgTicketsResponse | null>(null);
+ const [chart, setChart] = useState<OrgChartResponse | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [blockedOnly, setBlockedOnly] = useState(params.get("blocked") === "1");
+ const [query, setQuery] = useState("");
+ const [drag, setDrag] = useState<{ ticketId: string; from: OrgTicketStatus } | null>(null);
+ const [dropOver, setDropOver] = useState<OrgTicketStatus | null>(null);
+ const [move, setMove] = useState<{ ticket: OrgTicketItem; to: OrgTicketStatus } | null>(null);
+ const [createOpen, setCreateOpen] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const highlightColumn = params.get("column");
+ // The empty-board note goes away for good once read; the page's "?" carries the same
+ // sentence. The key holds the organization, so switching to another one — which does not
+ // unmount this page — re-reads the dismissal instead of carrying the last answer over.
+ const emptyHintKey = hintKey(user?.userId ?? null, projectId, orgId, "tickets");
+ const [hintDismissed, setHintDismissed] = useState(() => isHintDismissed(emptyHintKey));
+ useEffect(() => {
+ setHintDismissed(isHintDismissed(emptyHintKey));
+ }, [emptyHintKey]);
+
+ const load = useCallback(async () => {
+ try {
+ const [b, c] = await Promise.all([
+ api.listOrgTickets(projectId, orgId),
+ api.getOrgChart(projectId, orgId),
+ ]);
+ setBoard(b);
+ setChart(c);
+ setError(null);
+ } catch (e) {
+ setError(apiErrorText(e));
+ }
+ }, [projectId, orgId]);
+ const { tickets: ticketsVersion, runs } = company.versions;
+ useEffect(() => {
+ void load();
+ }, [load, ticketsVersion, runs]);
+
+ const employees = chart?.employees ?? [];
+ const names = new Map(employees.map((e) => [e.agentId, e.name]));
+ const titles = new Map(
+ (board === null ? [] : allTickets(board)).map((t) => [t.ticketId, t.title]),
+ );
+ const todayKey = dayKey(Date.now());
+
+ const setQueryParams = (patch: Record<string, string | null>) => {
+ const next = new URLSearchParams(params);
+ for (const [k, v] of Object.entries(patch)) {
+ if (v === null) next.delete(k);
+ else next.set(k, v);
+ }
+ setParams(next, { replace: true });
+ };
+ const openTicket = (ticketId: string) => company.openTicket(projectId, orgId, ticketId);
+
+ // `?ticket=` and the open dialog, kept in step in both directions: the query opens the
+ // dialog on arrival (a deep link, a reload), and the dialog writes itself back into the
+ // query as it moves and clears it when it closes. One effect rather than two, and one ref
+ // holding the value last read or written — two effects writing to each other would chase
+ // one round trip behind and reopen a ticket the reader had just left.
+ const urlTicket = params.get("ticket");
+ const openDialog = company.ticketDialog;
+ const dialogTicket =
+ openDialog !== null && openDialog.projectId === projectId && openDialog.orgId === orgId
+ ? openDialog.ticketId
+ : null;
+ const syncedTicket = useRef<string | null>(null);
+ const { openTicket: openTicketInShell } = company;
+ useEffect(() => {
+ if (urlTicket !== syncedTicket.current) {
+ syncedTicket.current = urlTicket;
+ if (urlTicket !== null) {
+ openTicketInShell(projectId, orgId, urlTicket);
+ return;
+ }
+ }
+ if (dialogTicket === urlTicket) return;
+ syncedTicket.current = dialogTicket;
+ setParams(
+ (prev) => {
+ const next = new URLSearchParams(prev);
+ if (dialogTicket === null) next.delete("ticket");
+ else next.set("ticket", dialogTicket);
+ return next;
+ },
+ { replace: true },
+ );
+ }, [urlTicket, dialogTicket, projectId, orgId, openTicketInShell, setParams]);
+
+ const confirmMove = async (reason: string) => {
+ if (move === null) return;
+ setBusy(true);
+ try {
+ await api.moveOrgTicket(projectId, orgId, move.ticket.ticketId, {
+ status: move.to,
+ ...(moveNeedsReason(move.to) ? { reason: reason.trim() } : {}),
+ });
+ toastSuccess(S.company.tickets.moved);
+ setMove(null);
+ // One signal for a ticket written here: this board, the open dialog and the
+ // organization summaries all refetch off it.
+ company.ticketsChanged();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const columnDrop = (status: OrgTicketStatus) => ({
+ onDragOver: (e: ReactDragEvent) => {
+ if (
+ drag === null ||
+ !e.dataTransfer.types.includes(TICKET_DRAG_MIME) ||
+ !canMove(drag.from, status)
+ )
+ return;
+ e.preventDefault();
+ e.dataTransfer.dropEffect = "move";
+ if (dropOver !== status) setDropOver(status);
+ },
+ onDragLeave: (e: ReactDragEvent) => {
+ const to = e.relatedTarget;
+ if (to instanceof Node && e.currentTarget.contains(to)) return;
+ setDropOver((prev) => (prev === status ? null : prev));
+ },
+ onDrop: (e: ReactDragEvent) => {
+ if (drag === null || !canMove(drag.from, status) || board === null) return;
+ e.preventDefault();
+ const ticket = allTickets(board).find((t) => t.ticketId === drag.ticketId);
+ setDrag(null);
+ setDropOver(null);
+ if (ticket === undefined) return;
+ setMove({ ticket, to: status });
+ },
+ });
+
+ /** A card: the title with its priority first (the title is the button that opens it), then what decides its urgency, then where it hangs and who holds it. */
+ const card = (t: OrgTicketItem) => {
+ const overdue = isOverdue(t.due, todayKey) && t.status !== "done" && t.status !== "rejected";
+ return (
+ <div
+ key={t.ticketId}
+ draggable
+ onDragStart={(e) => {
+ e.dataTransfer.setData(TICKET_DRAG_MIME, t.ticketId);
+ e.dataTransfer.effectAllowed = "move";
+ setDrag({ ticketId: t.ticketId, from: t.status });
+ }}
+ onDragEnd={() => {
+ setDrag(null);
+ setDropOver(null);
+ }}
+ title={`${t.title} · ${t.ticketId} · ${S.company.tickets.dragHint}`}
+ className={`block w-full cursor-grab rounded-md border bg-white p-2.5 text-left text-xs transition-colors duration-150 hover:border-gray-300 dark:bg-gray-900 dark:hover:border-gray-600 ${
+ t.invalid !== undefined
+ ? "border-red-300 dark:border-red-800"
+ : "border-gray-200 dark:border-gray-800"
+ } ${drag?.ticketId === t.ticketId ? "opacity-50" : ""}`}
+ >
+ <div className="flex items-start gap-1.5">
+ <TitleButton
+ title={S.company.tickets.openTicket}
+ className="line-clamp-2 flex-1 text-[13px] font-medium leading-snug text-gray-900 dark:text-gray-100"
+ onClick={() => openTicket(t.ticketId)}
+ >
+ {t.title}
+ </TitleButton>
+ {/* The priority reads with the title and shares its line, a size under it; the line
+ below carries what is time-bound — the due date and the blocked mark. */}
+ <span className="mt-px shrink-0">
+ <PriorityBadge priority={t.priority} />
+ </span>
+ {t.invalid !== undefined && (
+ <span className={`mt-0.5 shrink-0 ${toneInk.danger}`} title={t.invalid}>
+ <GlyphIcon d={INVALID_ICON} size={ICON_SIZE.inlineGlyph} />
+ <span className="sr-only">{S.company.tickets.invalid}</span>
+ </span>
+ )}
+ </div>
+ {/* The time-bound line, drawn only when there is something on it: the priority has
+ moved up to the title and an empty row would leave a gap under it. */}
+ {(t.due !== undefined || isBlocked(t)) && (
+ <div className="mt-2 flex flex-wrap items-center gap-1.5 text-[11px] text-gray-500 dark:text-gray-400">
+ {t.due !== undefined && (
+ <span
+ className={`inline-flex items-center gap-1 font-mono tabular-nums ${overdue ? toneInk.danger : ""}`}
+ title={overdue ? `${S.company.tickets.overdue} · ${t.due}` : S.company.tickets.due}
+ >
+ <GlyphIcon d={DUE_ICON} size={ICON_SIZE.inlineGlyph} />
+ {t.due}
+ {overdue && <span className="sr-only">{S.company.tickets.overdue}</span>}
+ </span>
+ )}
+ {isBlocked(t) && (
+ <span className="ml-auto">
+ <BlockedBadge
+ reason={t.blocked ?? ""}
+ {...(t.blockedBy !== undefined ? { by: t.blockedBy } : {})}
+ />
+ </span>
+ )}
+ </div>
+ )}
+ {t.parent !== undefined && (
+ <p
+ className="mt-2 truncate text-[11px] text-gray-400 dark:text-gray-500"
+ title={t.parent}
+ >
+ {S.company.tickets.parentLine(titles.get(t.parent) ?? t.parent)}
+ </p>
+ )}
+ <div className="mt-2 flex items-center gap-2 text-[11px] text-gray-500 dark:text-gray-400">
+ <span
+ className="flex min-w-0 text-gray-700 dark:text-gray-200"
+ title={`${S.company.tickets.owner} ${principalLabel(t.owner, names)}`}
+ >
+ <PrincipalChip principal={t.owner} names={names} size={ICON_SIZE.rowLead} />
+ </span>
+ </div>
+ </div>
+ );
+ };
+
+ const columns = board === null ? null : boardColumns(board, { blockedOnly, query, names });
+ const narrowed = blockedOnly || query.trim() !== "";
+ const invalids = board === null ? [] : invalidTickets(board);
+
+ return (
+ <OrgPage
+ title={S.nav.org.tickets}
+ info={S.company.tickets.info}
+ wide
+ actions={
+ <>
+ <div className="w-44">
+ <Input
+ size="sm"
+ type="search"
+ aria-label={S.company.tickets.searchPlaceholder}
+ placeholder={S.company.tickets.searchPlaceholder}
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ />
+ </div>
+ <label className="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-300">
+ {S.company.tickets.blockedOnly}
+ <Switch
+ checked={blockedOnly}
+ onChange={(v) => {
+ setBlockedOnly(v);
+ setQueryParams({ blocked: v ? "1" : null });
+ }}
+ />
+ </label>
+ <Button variant="primary" size="sm" onClick={() => setCreateOpen(true)}>
+ {S.company.tickets.create}
+ </Button>
+ </>
+ }
+ >
+ {error !== null && (
+ <div
+ className={`mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border px-3 py-2 text-xs ${toneStrip.danger}`}
+ >
+ <span>{S.company.tickets.loadFailed(error)}</span>
+ <Button size="sm" onClick={() => void load()}>
+ {S.common.retry}
+ </Button>
+ </div>
+ )}
+
+ {board !== null &&
+ allTickets(board).length === 0 &&
+ board.invalidFiles.length === 0 &&
+ !hintDismissed && (
+ <div
+ className={`mb-3 flex items-center gap-2 rounded-md border px-3 py-2 text-xs ${toneStrip.muted}`}
+ >
+ <span className="min-w-0 flex-1">{S.company.tickets.emptyHint}</span>
+ <Button
+ size="icon"
+ variant="ghost"
+ className="shrink-0"
+ title={S.company.tickets.dismissHint}
+ aria-label={S.company.tickets.dismissHint}
+ onClick={() => {
+ dismissHint(emptyHintKey);
+ setHintDismissed(true);
+ }}
+ >
+ <CloseIcon />
+ </Button>
+ </div>
+ )}
+
+ <div className="overflow-x-auto pb-2">
+ <div className="grid min-w-[50rem] grid-cols-5 gap-3">
+ {columns === null
+ ? TICKET_COLUMNS.map((status) => <ColumnSkeleton key={status} status={status} />)
+ : columns.map((col) => (
+ <div
+ key={col.status}
+ role="group"
+ aria-label={`${S.company.tickets.columns[col.status] ?? col.status} · ${col.tickets.length}`}
+ {...columnDrop(col.status)}
+ className={`${columnClass} ${
+ dropOver === col.status
+ ? "border-[var(--accent-bg)] ring-1 ring-[var(--accent-bg)]"
+ : highlightColumn === col.status && isTicketStatus(highlightColumn)
+ ? "border-gray-400 dark:border-gray-600"
+ : ""
+ }`}
+ >
+ <div className={`h-1 rounded-t-md ${COLUMN_BAR[col.status]}`} />
+ <div className="flex items-center justify-between gap-2 px-2.5 py-2">
+ <span className="text-xs font-semibold text-gray-700 dark:text-gray-200">
+ {S.company.tickets.columns[col.status] ?? col.status}
+ </span>
+ <span className="rounded-full bg-gray-200/70 px-1.5 py-px text-[11px] font-medium tabular-nums text-gray-600 dark:bg-gray-800 dark:text-gray-300">
+ {col.tickets.length}
+ </span>
+ </div>
+ <div className="flex flex-1 flex-col gap-2 px-2 pb-2">
+ {col.tickets.map(card)}
+ {col.tickets.length === 0 && (
+ <div
+ className={`flex min-h-20 flex-1 items-center justify-center rounded-md border border-dashed px-2 text-center text-[11px] ${
+ dropOver === col.status
+ ? "border-[var(--accent-bg)] text-gray-600 dark:text-gray-300"
+ : "border-gray-300 text-gray-400 dark:border-gray-700 dark:text-gray-500"
+ }`}
+ >
+ {drag !== null && canMove(drag.from, col.status)
+ ? S.company.tickets.dropHere
+ : narrowed
+ ? S.company.tickets.searchNoMatch
+ : S.company.tickets.columnEmpty}
+ </div>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {(invalids.length > 0 || (board !== null && board.invalidFiles.length > 0)) && (
+ <div className={`mt-2 rounded-md border px-3 py-2 text-xs ${toneStrip.danger}`}>
+ {invalids.length > 0 && (
+ <>
+ <p className="mb-1 flex items-center gap-1.5 font-medium">
+ <GlyphIcon d={INVALID_ICON} size={ICON_SIZE.inlineGlyph} />
+ {S.company.tickets.invalidTickets}
+ </p>
+ <ul className="mb-2 space-y-0.5">
+ {invalids.map((t) => (
+ <li key={t.ticketId} className="flex items-baseline">
+ <TitleButton
+ title={S.company.tickets.openTicket}
+ className="shrink-0 font-mono"
+ onClick={() => openTicket(t.ticketId)}
+ >
+ {t.ticketId}
+ </TitleButton>
+ <span className="min-w-0">: {t.invalid}</span>
+ </li>
+ ))}
+ </ul>
+ </>
+ )}
+ {board !== null && board.invalidFiles.length > 0 && (
+ <>
+ <p className="mb-1 flex items-center gap-1.5 font-medium">
+ <GlyphIcon d={INVALID_ICON} size={ICON_SIZE.inlineGlyph} />
+ {S.company.tickets.invalidFiles}
+ </p>
+ <ul className="space-y-0.5 font-mono">
+ {board.invalidFiles.map((f) => (
+ <li key={f.path}>
+ {f.path}: {f.error}
+ </li>
+ ))}
+ </ul>
+ </>
+ )}
+ </div>
+ )}
+
+ {/* Move confirmation: the target column, and a reason when the target is rejected —
+ the same dialog the detail's own move goes through. */}
+ <MoveTicketConfirm
+ move={move === null ? null : { title: move.ticket.title, to: move.to }}
+ busy={busy}
+ onClose={() => (busy ? undefined : setMove(null))}
+ onConfirm={(reason) => void confirmMove(reason)}
+ />
+
+ <CreateTicketDialog
+ open={createOpen}
+ projectId={projectId}
+ orgId={orgId}
+ employees={employees.map((e) => ({ agentId: e.agentId, name: e.name }))}
+ tickets={board === null ? [] : allTickets(board)}
+ onClose={() => setCreateOpen(false)}
+ onCreated={(ticketId) => {
+ setCreateOpen(false);
+ company.ticketsChanged();
+ openTicket(ticketId);
+ }}
+ />
+ </OrgPage>
+ );
+}
+
+/** A column while the first fetch is out: the bar and header in place, two card-shaped placeholders. */
+function ColumnSkeleton({ status }: { status: OrgTicketStatus }) {
+ return (
+ <div className={columnClass}>
+ <div className={`h-1 rounded-t-md ${COLUMN_BAR[status]}`} />
+ <div className="flex items-center justify-between gap-2 px-2.5 py-2">
+ <span className="text-xs font-semibold text-gray-700 dark:text-gray-200">
+ {S.company.tickets.columns[status] ?? status}
+ </span>
+ <Skeleton className="h-4 w-6 rounded-full" />
+ </div>
+ <div className="flex flex-col gap-2 px-2 pb-2">
+ {Array.from(
+ { length: status === "proposed" || status === "in_progress" ? 2 : 1 },
+ (_, i) => (
+ <div
+ key={i}
+ className="space-y-2 rounded-md border border-gray-200 bg-white p-2.5 dark:border-gray-800 dark:bg-gray-900"
+ >
+ <Skeleton className="h-3.5 w-4/5" />
+ <Skeleton className="h-3 w-2/5" />
+ <Skeleton className="h-3 w-3/5" />
+ </div>
+ ),
+ )}
+ </div>
+ </div>
+ );
+}
+
+function CreateTicketDialog({
+ open,
+ projectId,
+ orgId,
+ employees,
+ tickets,
+ onClose,
+ onCreated,
+}: {
+ open: boolean;
+ projectId: string;
+ orgId: string;
+ employees: ReadonlyArray<{ agentId: string; name: string }>;
+ tickets: readonly OrgTicketItem[];
+ onClose: () => void;
+ onCreated: (ticketId: string) => void;
+}) {
+ const [title, setTitle] = useState("");
+ const [slug, setSlug] = useState("");
+ const [goal, setGoal] = useState("");
+ const [acceptance, setAcceptance] = useState("");
+ const [owner, setOwner] = useState("");
+ const [parent, setParent] = useState("");
+ const [notify, setNotify] = useState("");
+ const [priority, setPriority] = useState<OrgTicketPriority>("P1");
+ const [due, setDue] = useState("");
+ const [titleError, setTitleError] = useState<string | undefined>(undefined);
+ const [slugError, setSlugError] = useState<string | undefined>(undefined);
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ if (!open) return;
+ setTitle("");
+ setSlug("");
+ setGoal("");
+ setAcceptance("");
+ setOwner("");
+ setParent("");
+ setNotify("");
+ setPriority("P1");
+ setDue("");
+ setTitleError(undefined);
+ setSlugError(undefined);
+ }, [open]);
+
+ const submit = async () => {
+ if (!title.trim()) {
+ setTitleError(S.common.requiredField);
+ return;
+ }
+ if (slug.trim() !== "" && !isTicketSlug(slug.trim())) {
+ setSlugError(S.company.tickets.slugInvalid);
+ return;
+ }
+ setBusy(true);
+ try {
+ const detail = await api.createOrgTicket(projectId, orgId, {
+ title: title.trim(),
+ ...(slug.trim() ? { slug: slug.trim() } : {}),
+ ...(goal.trim() ? { goal: goal.trim() } : {}),
+ ...(acceptance.trim() ? { acceptanceCriteria: acceptance.trim() } : {}),
+ ...(owner ? { owner } : {}),
+ ...(parent ? { parent } : {}),
+ ...(notify.trim() ? { notify: splitPrincipalList(notify) } : {}),
+ priority,
+ ...(due ? { due } : {}),
+ });
+ toastSuccess(S.company.tickets.created);
+ onCreated(detail.ticketId);
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <Modal
+ open={open}
+ title={S.company.tickets.createTitle}
+ onClose={onClose}
+ widthClass="sm:max-w-lg"
+ footer={
+ <>
+ <Button size="sm" onClick={onClose} disabled={busy}>
+ {S.common.cancel}
+ </Button>
+ <Button size="sm" variant="primary" disabled={busy} onClick={() => void submit()}>
+ {S.common.create}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ <Input
+ size="sm"
+ label={S.company.tickets.ticketTitle}
+ required
+ value={title}
+ error={titleError}
+ autoFocus
+ onChange={(e) => {
+ setTitle(e.target.value);
+ setTitleError(undefined);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ void submit();
+ }
+ }}
+ />
+ <Input
+ size="sm"
+ label={S.company.tickets.slug}
+ value={slug}
+ hint={S.company.tickets.slugHint}
+ error={slugError}
+ className="font-mono"
+ onChange={(e) => {
+ const next = e.target.value;
+ setSlug(next);
+ // The rule is short and the box is small: say so while it is typed, not on submit.
+ setSlugError(
+ next.trim() === "" || isTicketSlug(next.trim())
+ ? undefined
+ : S.company.tickets.slugInvalid,
+ );
+ }}
+ />
+ <Textarea
+ size="sm"
+ label={S.company.tickets.goal}
+ rows={3}
+ value={goal}
+ hint={S.company.tickets.goalHint}
+ onChange={(e) => setGoal(e.target.value)}
+ />
+ <Textarea
+ size="sm"
+ label={S.company.tickets.acceptance}
+ rows={3}
+ value={acceptance}
+ hint={S.company.tickets.acceptanceHint}
+ onChange={(e) => setAcceptance(e.target.value)}
+ />
+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
+ <Select
+ size="sm"
+ label={S.company.tickets.owner}
+ value={owner}
+ hint={S.company.tickets.ownerSelfHint}
+ onChange={(e) => setOwner(e.target.value)}
+ >
+ <option value="">{S.company.tickets.ownerSelf}</option>
+ {employees.map((e) => (
+ <option key={e.agentId} value={agentPrincipal(e.agentId)}>
+ {e.name}
+ </option>
+ ))}
+ </Select>
+ <Select
+ size="sm"
+ label={S.company.tickets.parent}
+ value={parent}
+ onChange={(e) => setParent(e.target.value)}
+ >
+ <option value="">{S.company.tickets.noParent}</option>
+ {tickets.map((t) => (
+ <option key={t.ticketId} value={t.ticketId}>
+ {t.title}
+ </option>
+ ))}
+ </Select>
+ <div>
+ <FieldLabel>{S.company.tickets.priority}</FieldLabel>
+ <Segmented
+ options={PRIORITIES.map((p) => ({ value: p, label: p }))}
+ value={priority}
+ onChange={setPriority}
+ cols={3}
+ />
+ </div>
+ <Input
+ size="sm"
+ label={S.company.tickets.due}
+ type="date"
+ value={due}
+ className="font-mono"
+ onChange={(e) => setDue(e.target.value)}
+ />
+ </div>
+ <Input
+ size="sm"
+ label={S.company.tickets.notify}
+ value={notify}
+ hint={S.company.tickets.notifyHint}
+ className="font-mono"
+ onChange={(e) => setNotify(e.target.value)}
+ />
+ </div>
+ </Modal>
+ );
+}
diff --git a/packages/web/src/features/messaging/messaging-binding-modal.tsx b/packages/web/src/features/messaging/messaging-binding-modal.tsx
index 3e8c049d..679be08c 100644
--- a/packages/web/src/features/messaging/messaging-binding-modal.tsx
+++ b/packages/web/src/features/messaging/messaging-binding-modal.tsx
@@ -3,10 +3,12 @@
* shared channel-aware binding editor — the same hook + body the conversation's Messaging
* dock panel renders, so the sidebar can manage bindings without opening the chat and
* the two surfaces can never drift. This host contributes only the Modal frame, the
- * footer's Close / Save placement, and the FAQ folds' position at the body's end; every
- * behavior (channel switching, save/enable split, single-enabled gating, models-style
- * secret clearing, status poll) lives in the editor. There is no unbind action —
- * removing a credential is the secret field's clear checkbox.
+ * footer's Close / Save placement, the FAQ folds' position at the body's end, and the choice
+ * to close on a failed load (optionally telling the host first, so a host that opened the
+ * dialog from a cached row can re-read that cache); every behavior (channel switching,
+ * save/enable split, single-enabled gating, models-style secret clearing, status poll) lives
+ * in the editor. There is no unbind action — removing a credential is the secret field's
+ * clear checkbox.
*/
import type { MessagingChannel } from "@prismshadow/penguin-server/api";
import { S } from "../../lib/strings";
@@ -22,17 +24,27 @@ export function MessagingBindingModal({
sessionId,
onClose,
onChanged,
+ onLoadFailed,
}: {
sessionId: string;
onClose: () => void;
/** Fired when the ENABLED channel changed (null = none); callers refresh their row/list indicator. */
onChanged?: (sessionId: string, channel: MessagingChannel | null) => void;
+ /**
+ * The binding could not be read at all — the Session is gone, or the reader lost access to
+ * it. The editor has already shown the reason as a toast and this dialog closes either way;
+ * a host whose row came from its own cache uses this to re-read that cache.
+ */
+ onLoadFailed?: () => void;
}) {
// The dialog polls for its whole lifetime (it unmounts on close).
const b = useMessagingBinding(sessionId, {
poll: true,
...(onChanged ? { onChanged } : {}),
- onLoadFailed: onClose,
+ onLoadFailed: () => {
+ onLoadFailed?.();
+ onClose();
+ },
});
return (
diff --git a/packages/web/src/features/settings/company-mode-write.ts b/packages/web/src/features/settings/company-mode-write.ts
new file mode 100644
index 00000000..ebac2f64
--- /dev/null
+++ b/packages/web/src/features/settings/company-mode-write.ts
@@ -0,0 +1,42 @@
+/**
+ * The write behind the company-mode master switch, kept out of the component because this
+ * package's unit tests run without a DOM. It is where "the flip is the save" lives: the PUT a
+ * flipped switch fires at once, the server's answer as the value to settle on, and — when the
+ * request fails — the value to put the switch back to, with the reason to name under it.
+ *
+ * The answer is adopted rather than assumed: a server that stored something other than what was
+ * asked for is what the switch must show.
+ */
+import type {
+ ServerSettingsResponse,
+ ServerSettingsUpdateRequest,
+} from "@prismshadow/penguin-server/api";
+
+/** What a flip settled on: the stored value now, or the value to revert to and why. */
+export type CompanyModeWriteResult =
+ | { status: "applied"; companyMode: boolean }
+ | { status: "failed"; revertTo: boolean; error: string };
+
+export interface CompanyModeWriteDeps {
+ /** `api.adminPutSettings` in the app; a stub in tests. */
+ put: (body: ServerSettingsUpdateRequest) => Promise<ServerSettingsResponse>;
+ /** Turns a rejection into the line shown under the switch (`apiErrorText` in the app). */
+ describeError: (error: unknown) => string;
+}
+
+/**
+ * Writes `next` as the master switch. `stored` is the last value the server confirmed — the one
+ * a failed write reverts to, so the switch never sits on a state the server does not hold.
+ */
+export async function writeCompanyMode(
+ next: boolean,
+ stored: boolean,
+ deps: CompanyModeWriteDeps,
+): Promise<CompanyModeWriteResult> {
+ try {
+ const res = await deps.put({ companyMode: next });
+ return { status: "applied", companyMode: res.settings.companyMode };
+ } catch (error) {
+ return { status: "failed", revertTo: stored, error: deps.describeError(error) };
+ }
+}
diff --git a/packages/web/src/features/settings/company-section.tsx b/packages/web/src/features/settings/company-section.tsx
new file mode 100644
index 00000000..46df0db8
--- /dev/null
+++ b/packages/web/src/features/settings/company-section.tsx
@@ -0,0 +1,96 @@
+/**
+ * Company mode (admin only, server-global): one switch that applies the moment it is flipped —
+ * a single PUT to /api/admin/settings, no Save button, and so no draft state to lose. The switch
+ * is off on a server nobody has turned it on, which is why the pre-hydration state below is off
+ * rather than on; it stays disabled until the stored value arrives and again while a write is in
+ * flight, so a second flip cannot race the first. Off stops the organization scheduler, 404s
+ * every organization route and hides the mode switch for everyone; on again resumes without
+ * backfilling what was missed. A write that fails puts the switch back on the stored value and
+ * names the reason on a line under it (a toast would leave the switch and the message on
+ * separate surfaces). The auth context is refreshed afterwards because the shell reads the flag
+ * from /api/me, not from this page. The mode is a beta; the line under the switch says so
+ * wherever the switch stands.
+ */
+import { useEffect, useState } from "react";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { toneInk } from "../../lib/tone";
+import { useAuth } from "../../state/auth";
+import { Switch } from "../../components/ui/switch";
+import { toastError } from "../../components/ui/toast";
+import { writeCompanyMode } from "./company-mode-write";
+import { SectionShell } from "./section-shell";
+
+export function CompanySection() {
+ const { refresh } = useAuth();
+ /** The last value the server confirmed; null until the settings load. */
+ const [stored, setStored] = useState<boolean | null>(null);
+ /** What the switch shows: the stored value, or the pending one while a write is in flight. */
+ const [companyMode, setCompanyMode] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | undefined>(undefined);
+
+ useEffect(() => {
+ let cancelled = false;
+ void api
+ .adminGetSettings()
+ .then((res) => {
+ if (cancelled) return;
+ setStored(res.settings.companyMode);
+ setCompanyMode(res.settings.companyMode);
+ })
+ .catch((e: unknown) => {
+ if (!cancelled) toastError(apiErrorText(e));
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ const toggle = async (next: boolean) => {
+ if (stored === null || busy) return;
+ // Optimistic: the knob moves with the click, and only a failure moves it back.
+ setCompanyMode(next);
+ setError(undefined);
+ setBusy(true);
+ const result = await writeCompanyMode(next, stored, {
+ put: api.adminPutSettings,
+ describeError: apiErrorText,
+ });
+ if (result.status === "applied") {
+ setStored(result.companyMode);
+ setCompanyMode(result.companyMode);
+ // The shell decides whether to draw the mode switch from /api/me; re-pull it so this
+ // tab follows its own change without a reload.
+ await refresh().catch(() => {});
+ } else {
+ setCompanyMode(result.revertTo);
+ setError(result.error);
+ }
+ setBusy(false);
+ };
+
+ const hydrated = stored !== null;
+ return (
+ <SectionShell>
+ <div>
+ <div className="flex items-center justify-between gap-3">
+ <span className="text-sm font-medium">{S.settings.companyModeServer}</span>
+ <Switch
+ checked={companyMode}
+ onChange={(next) => void toggle(next)}
+ disabled={!hydrated || busy}
+ aria-label={S.settings.companyModeServer}
+ />
+ </div>
+ {/* The reason the switch went back, under the switch it went back on. */}
+ {error !== undefined && <p className={`mt-2 text-xs ${toneInk.danger}`}>{error}</p>}
+ {/* The mode is a beta, and this switch signs a whole server up for it: the warning
+ stands under it unconditionally rather than behind the page's "?", which is a
+ click away and is read once. */}
+ <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">{S.company.betaNotice}</p>
+ </div>
+ </SectionShell>
+ );
+}
diff --git a/packages/web/src/features/settings/general-section.tsx b/packages/web/src/features/settings/general-section.tsx
index 4fbc33aa..937fd287 100644
--- a/packages/web/src/features/settings/general-section.tsx
+++ b/packages/web/src/features/settings/general-section.tsx
@@ -23,6 +23,7 @@ import {
writeNotificationsEnabled,
} from "../../lib/notification-pref";
import type { NotificationAccess } from "../../lib/notification-pref";
+import { useCompany } from "../../state/company";
import { useLocale } from "../../state/locale";
import type { LangPref } from "../../state/locale";
import { useTheme } from "../../state/theme";
@@ -33,6 +34,7 @@ import { TraceImportRow } from "./trace-import-row";
export function GeneralSection() {
const { lang, setLang } = useLocale();
const { currency, setCurrency } = useTheme();
+ const { serverEnabled, personalEnabled, setPersonalEnabled } = useCompany();
useSyncExternalStore(subscribeNotificationsEnabled, notificationsEnabledVersion);
const notificationsOn = readNotificationsEnabled();
@@ -92,6 +94,18 @@ export function GeneralSection() {
}}
/>
</PrefRow>
+ {/* The personal company-mode switch: off hides this user's mode switch and nothing else.
+ Offered only while the server allows company mode at all — a switch that changes
+ nothing would only invite the question of why. */}
+ {serverEnabled && (
+ <PrefRow label={S.settings.companyModePersonal} info={S.settings.companyModePersonalInfo}>
+ <Switch
+ checked={personalEnabled}
+ onChange={setPersonalEnabled}
+ aria-label={S.settings.companyModePersonal}
+ />
+ </PrefRow>
+ )}
<TraceImportRow />
</div>
);
diff --git a/packages/web/src/features/settings/settings-dialog.tsx b/packages/web/src/features/settings/settings-dialog.tsx
index 23ff2d54..3b62755e 100644
--- a/packages/web/src/features/settings/settings-dialog.tsx
+++ b/packages/web/src/features/settings/settings-dialog.tsx
@@ -19,13 +19,14 @@ import { useAuth } from "../../state/auth";
import { PagedDialog } from "../../components/ui/paged-dialog";
import type { PagedDialogGroup } from "../../components/ui/paged-dialog";
import { Icon } from "../../components/ui/group-list";
-import { GEAR_ICON } from "../../components/ui/icons";
+import { COMPANY_MODE_ICON, GEAR_ICON } from "../../components/ui/icons";
import { ProfileSection } from "./profile-section";
import { GeneralSection } from "./general-section";
import { AppearanceSection } from "./appearance-section";
import { AccountSection } from "./account-section";
import { ProxySection } from "./proxy-section";
import { UploadsSection } from "./uploads-section";
+import { CompanySection } from "./company-section";
import { AdminUsersSection } from "../admin/admin-users-page";
/** Rail glyphs, on the shared 24x24 stroke grid (see NAV_ICONS' conventions). */
@@ -44,6 +45,8 @@ const SECTION_ICONS: Record<SettingsSectionKey, string> = {
"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM3.6 9h16.8M3.6 15h16.8M12 3a15 15 0 0 0 0 18M12 3a15 15 0 0 1 0 18",
/** Up arrow over a base: uploads. */
uploads: "M12 15V4m0 0L7 9m5-5l5 5M4 20h16",
+ /** The building the mode switch wears: company mode. */
+ company: COMPANY_MODE_ICON,
/** Two people: user management. */
users:
"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75",
@@ -77,6 +80,7 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =
account: S.settings.accountTitle,
proxy: S.settings.proxyTitle,
uploads: S.settings.uploadLimitsTitle,
+ company: S.settings.companyModeTitle,
users: S.admin.users,
};
const groupLabel: Record<SettingsGroupKey, string> = {
@@ -88,6 +92,7 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =
const sectionInfo: Partial<Record<SettingsSectionKey, string>> = {
proxy: S.settings.proxyInfo,
uploads: S.settings.uploadLimitsInfo(uploadLimits.attachmentMaxCount, uploadLimits.imageMaxMb),
+ company: S.settings.companyModeServerInfo,
};
const groups: Array<PagedDialogGroup<SettingsSectionKey>> = settingsGroups(sections).map(
@@ -120,6 +125,7 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =
{current === "account" && <AccountSection />}
{current === "proxy" && <ProxySection />}
{current === "uploads" && <UploadsSection />}
+ {current === "company" && <CompanySection />}
{current === "users" && <AdminUsersSection />}
</PagedDialog>
);
diff --git a/packages/web/src/lib/category-colors.ts b/packages/web/src/lib/category-colors.ts
index ff3cdfd3..4dde6e7e 100644
--- a/packages/web/src/lib/category-colors.ts
+++ b/packages/web/src/lib/category-colors.ts
@@ -73,3 +73,54 @@ export const NEUTRAL_SERIES: SeriesColor = {
text: "text-gray-400 dark:text-gray-500",
swatch: "bg-gray-400 dark:bg-gray-500",
};
+
+/**
+ * Employee colours for the organization calendar: one hue per employee, identity again and
+ * not severity, so the set may grow without any hue reading as a state. Each entry is a chip
+ * (a tinted event block with its own readable ink) and the matching dot for the legend and
+ * filter; index by an employee's position in the chart, cycling past the end (the legend and
+ * the chip's own text keep identity from ever resting on colour alone).
+ */
+export interface EmployeeColor {
+ chip: string;
+ dot: string;
+}
+
+export const EMPLOYEE_COLORS: readonly EmployeeColor[] = [
+ {
+ chip: "bg-violet-100 text-violet-900 dark:bg-violet-950 dark:text-violet-200",
+ dot: "bg-violet-500",
+ },
+ {
+ chip: "bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-200",
+ dot: "bg-amber-500 dark:bg-amber-600",
+ },
+ {
+ chip: "bg-sky-100 text-sky-900 dark:bg-sky-950 dark:text-sky-200",
+ dot: "bg-sky-500 dark:bg-sky-600",
+ },
+ { chip: "bg-rose-100 text-rose-900 dark:bg-rose-950 dark:text-rose-200", dot: "bg-rose-500" },
+ {
+ chip: "bg-emerald-100 text-emerald-900 dark:bg-emerald-950 dark:text-emerald-200",
+ dot: "bg-emerald-500 dark:bg-emerald-600",
+ },
+ {
+ chip: "bg-fuchsia-100 text-fuchsia-900 dark:bg-fuchsia-950 dark:text-fuchsia-200",
+ dot: "bg-fuchsia-500 dark:bg-fuchsia-600",
+ },
+ {
+ chip: "bg-teal-100 text-teal-900 dark:bg-teal-950 dark:text-teal-200",
+ dot: "bg-teal-500 dark:bg-teal-600",
+ },
+ {
+ chip: "bg-orange-100 text-orange-900 dark:bg-orange-950 dark:text-orange-200",
+ dot: "bg-orange-500 dark:bg-orange-600",
+ },
+];
+
+/** Colour for the i-th employee (cycles once past the end). */
+export function employeeColor(i: number): EmployeeColor {
+ return EMPLOYEE_COLORS[
+ ((i % EMPLOYEE_COLORS.length) + EMPLOYEE_COLORS.length) % EMPLOYEE_COLORS.length
+ ]!;
+}
diff --git a/packages/web/src/lib/install-scope.ts b/packages/web/src/lib/install-scope.ts
index acee02a5..cc0cdf34 100644
--- a/packages/web/src/lib/install-scope.ts
+++ b/packages/web/src/lib/install-scope.ts
@@ -271,6 +271,36 @@ export const KEY_RULES: readonly KeyRule[] = [
scope: "install",
why: "The Project id last selected.",
},
+ {
+ kind: "exact",
+ key: "penguin.workMode",
+ scope: "browser",
+ why: "Development vs company mode — the MODE, mirrored from ui_prefs; valid against any root.",
+ },
+ {
+ kind: "exact",
+ key: "penguin.companyBetaNoticeShown",
+ scope: "browser",
+ why: "That company mode's beta notice has been shown in this browser; it names nothing on the server, and a wipe is not a request to show it again.",
+ },
+ {
+ kind: "exact",
+ key: "penguin.lastOrgKey",
+ scope: "install",
+ why: "The organization last opened in company mode, as <projectId>/<orgId> of this root.",
+ },
+ {
+ kind: "family",
+ key: "penguin.orgCreateDraft.",
+ scope: "install",
+ why: "An unsubmitted create-organization form, keyed by user and Project id and holding a Workspace path and model ref of this root.",
+ },
+ {
+ kind: "family",
+ key: "penguin.orgPageHint.",
+ scope: "install",
+ why: "A dismissed empty-page note, keyed by user, Project and organization id of this root.",
+ },
{
kind: "family",
key: "penguin.lastAgentId.",
diff --git a/packages/web/src/lib/remark-autolink-boundary.ts b/packages/web/src/lib/remark-autolink-boundary.ts
index 4a272091..32c9830e 100644
--- a/packages/web/src/lib/remark-autolink-boundary.ts
+++ b/packages/web/src/lib/remark-autolink-boundary.ts
@@ -1,20 +1,44 @@
/**
- * Ends a bare URL at the last ASCII character.
+ * Where a bare URL ends.
*
- * GFM's autolink-literal extension ends a bare URL at whitespace, then trims a short list of
- * trailing ASCII punctuation. Neither rule sees CJK: `见 https://penguin.ooo,然后继续` is not
+ * GFM's autolink-literal extension ends a bare URL at whitespace and then hands the tail to its own
+ * "trail" check, which drops trailing punctuation — `*`, `_`, `~`, `)`, `.`, `,` and the rest. That
+ * check only fires when the run is followed by whitespace, a `<`, or the end of the input, so it
+ * never sees what CJK does to a sentence: `见 https://penguin.ooo,然后继续` is not
* whitespace-separated after the host, so the comma and the clause after it are swallowed into the
- * href, which then 404s, and the sentence loses its punctuation to link styling. English is
- * unaffected — `see https://penguin.ooo, then` already trims correctly — so this only ever fires on
- * text GFM was not written for.
+ * href, which then 404s; `请**打开 http://127.0.0.1:4321/**查看` puts the closing `**` in the href
+ * the same way. English is unaffected — `see https://penguin.ooo, then` already ends correctly.
*
- * A URL is ASCII by RFC 3986; anything outside it belongs percent-encoded. So the boundary is the
- * last ASCII character, and a trailing non-ASCII run is handed back to the paragraph as text.
+ * This pass re-applies the boundary where GFM stopped looking. On an autolink literal's URL only —
+ * an explicit `[text](url)` link is never touched — it cuts from the right, repeatedly, until
+ * nothing matches:
*
- * The trade this makes: a URL carrying *unencoded* CJK in its path — `…/wiki/中文` pasted raw
- * rather than percent-encoded — is trimmed at the last ASCII character. That form is invalid per
- * the RFC and browsers only accept it by encoding it for you; the same link pasted in its encoded
- * form is untouched. Explicit `[text](url)` links are never touched at all.
+ * - a run of non-ASCII characters. A URL is ASCII by RFC 3986; anything else belongs
+ * percent-encoded.
+ * - a run of `*`, `~` or `` ` ``. Those are Markdown span markers, they are never meaningful at the
+ * end of a URL, and GFM's own trail already drops `*` and `~` when it gets to look.
+ * - a run of `_`, but only when a text node before the link in the same parent holds one too. `_`
+ * is ordinary inside a path (`a_b`) and only reads as a closing marker when something opened.
+ * - a single `)` or `]` that nothing inside the URL opened, or a `>` (a `<` ends a URL, so a
+ * trailing `>` never has a partner).
+ *
+ * Only a *trailing* run is ever cut, so `…/a_b` and `…?q=*b` keep what is in their middle.
+ *
+ * The cut characters are handed back to the paragraph as a text node, so the sentence keeps them.
+ * What this cannot do is re-close the emphasis: emphasis is resolved while parsing and this runs on
+ * the tree that came out, so a `**` handed back renders as the two characters it is. For the shape
+ * this was written against that is what CommonMark asks for anyway — in `请**打开 <url>/**查看` the
+ * closing `**` sits between a `/` and a CJK character, which is neither left- nor right-flanking,
+ * and `请**打开 abc/**查看` is not bold either. The one shape where it differs is a URL ending in a
+ * letter (`…/index**查看`), where the emphasis would have closed had the autolink not eaten the
+ * markers; re-pairing delimiter runs on a finished tree is a whole second parser, so those markers
+ * stay literal. Written with a space or a line end after the closing `**` the emphasis closes
+ * during parsing, the markers never reach the URL, and this pass has nothing left to do.
+ *
+ * The trade the non-ASCII cut makes: a URL carrying *unencoded* CJK in its path — `…/wiki/中文`
+ * pasted raw rather than percent-encoded — is trimmed at the last ASCII character. That form is
+ * invalid per the RFC and browsers only accept it by encoding it for you; the same link pasted in
+ * its encoded form is untouched.
*/
/**
* The mdast shapes this touches, declared structurally rather than pulling `@types/mdast` in as a
@@ -37,6 +61,19 @@ interface Parent {
/** Trailing characters outside ASCII: never part of a well-formed URL. */
const TRAILING_NON_ASCII = /[^\x00-\x7F]+$/;
+/** Trailing Markdown span markers: emphasis, strikethrough and inline code, none of them URL syntax. */
+const TRAILING_SPAN_MARKERS = /[*~`]+$/;
+
+/** A trailing run of `_`, cut only when the paragraph opened emphasis with one. */
+const TRAILING_UNDERSCORES = /_+$/;
+
+/** Closers whose opener, if there is one, would be inside the URL. */
+const CLOSERS: ReadonlyArray<readonly [close: string, open: string]> = [
+ [")", "("],
+ ["]", "["],
+ [">", "<"],
+];
+
/** True when this link came from autolinking rather than `[text](url)` syntax. */
function isAutolinkLiteral(node: LinkNode): boolean {
if (node.children.length !== 1) return false;
@@ -47,17 +84,60 @@ function isAutolinkLiteral(node: LinkNode): boolean {
return node.url === value || node.url === `http://${value}`;
}
-function trimNode(node: LinkNode): TextNode | null {
+/** True when the final character of `value` closes something the rest of `value` never opened. */
+function closesNothing(value: string, close: string, open: string): boolean {
+ let depth = 0;
+ for (const ch of value) {
+ if (ch === open) depth += 1;
+ else if (ch === close) depth -= 1;
+ }
+ return depth < 0;
+}
+
+/**
+ * How much of `value` is still URL. Each cut can expose another — `…/**)` is a full-width bracket
+ * over a `**` — so they run in a loop until the value stops shrinking.
+ */
+function boundaryOf(value: string, underscoreOpened: boolean): number {
+ let kept = value;
+ for (;;) {
+ const before = kept;
+ kept = kept.replace(TRAILING_NON_ASCII, "").replace(TRAILING_SPAN_MARKERS, "");
+ if (underscoreOpened) kept = kept.replace(TRAILING_UNDERSCORES, "");
+ for (const [close, open] of CLOSERS) {
+ if (kept.endsWith(close) && closesNothing(kept, close, open)) kept = kept.slice(0, -1);
+ }
+ if (kept === before) return kept.length;
+ }
+}
+
+/** The cut characters, as the text node they go back to, or null when the URL already ended right. */
+function trimNode(node: LinkNode, underscoreOpened: boolean): TextNode | null {
if (!isAutolinkLiteral(node)) return null;
const child = node.children[0] as TextNode;
- const match = TRAILING_NON_ASCII.exec(child.value);
- if (!match) return null;
- const kept = child.value.slice(0, match.index);
- // A "URL" that is non-ASCII all the way to its scheme is not one this should be splitting.
+ const boundary = boundaryOf(child.value, underscoreOpened);
+ if (boundary === child.value.length) return null;
+ const kept = child.value.slice(0, boundary);
+ // A "URL" that is punctuation or non-ASCII all the way to its scheme is not one this should be
+ // splitting.
if (!kept.includes("://") && !kept.startsWith("www.")) return null;
+ const spilled = child.value.slice(boundary);
child.value = kept;
node.url = node.url.startsWith("http://") && !kept.startsWith("http") ? `http://${kept}` : kept;
- return { type: "text", value: match[0] };
+ return { type: "text", value: spilled };
+}
+
+/**
+ * Whether anything before this position in the same parent spells a `_`. The cheap stand-in for
+ * "emphasis was opened with `_`": had the emphasis actually closed, the marker would be a node
+ * boundary rather than text, so a `_` still sitting in the text is one that opened nothing yet.
+ */
+function underscoreOpenedBefore(children: Node[], index: number): boolean {
+ for (let i = 0; i < index; i += 1) {
+ const sibling = children[i]!;
+ if (sibling.type === "text" && (sibling as TextNode).value.includes("_")) return true;
+ }
+ return false;
}
/** Walks every parent, so a link nested in emphasis or a list item is covered too. */
@@ -65,7 +145,7 @@ function walk(parent: Parent): void {
for (let i = 0; i < parent.children.length; i += 1) {
const node = parent.children[i]!;
if (node.type === "link") {
- const spill = trimNode(node as LinkNode);
+ const spill = trimNode(node as LinkNode, underscoreOpenedBefore(parent.children, i));
if (spill) parent.children.splice(i + 1, 0, spill);
}
const children = (node as { children?: Node[] }).children;
diff --git a/packages/web/src/lib/session-grouping.ts b/packages/web/src/lib/session-grouping.ts
index e55392c2..a357f3d9 100644
--- a/packages/web/src/lib/session-grouping.ts
+++ b/packages/web/src/lib/session-grouping.ts
@@ -568,3 +568,107 @@ export function pinnedFirst<T>(
for (const item of items) (pinned.has(keyOf(item)) ? pin : rest).push(item);
return [...pin, ...rest];
}
+
+/**
+ * The two marks a Session an organization owns can carry — a desk session of one of its
+ * employees, or a session contributing to one of its tickets. `client` is stamped on the row
+ * when the organization runtime creates the Session and never changes; `orgId` is resolved per
+ * read from the organization's own caches. Both are optional on the wire, and a row is an
+ * organization's when either says so.
+ */
+export interface OrgSessionMarks {
+ /** The owning organization, resolved per read; absent once the organization is deleted. */
+ orgId?: string;
+ /** The client that created the Session; "org" is the organization runtime's own stamp. */
+ client?: string;
+}
+
+/**
+ * Whether a Session belongs to an organization. The durable stamp answers even after the
+ * organization is gone, which is the case `orgId` alone cannot: the caches it is read from no
+ * longer hold the Session, and the row would otherwise reappear somewhere it never belonged.
+ */
+export function isOrgSession(row: OrgSessionMarks): boolean {
+ return (row.orgId !== undefined && row.orgId !== "") || row.client === "org";
+}
+
+/**
+ * The development list's own rows, and the ones an organization owns.
+ *
+ * Development mode lists only the first half, and it does so ALWAYS. An organization's
+ * Sessions are driven by its scheduler rather than by the user, which is a fact about the
+ * Session and not about the shell around it — so neither company mode being switched off (the
+ * admin's master switch or the user's own) nor the organization being deleted turns one back
+ * into a conversation of this list. They are reached as themselves in company mode — a desk
+ * from the 工位 group, a ticket session from the ticket that started it — and stay reachable
+ * by their own url and through the Trace page regardless.
+ *
+ * The second half is not waste: the server's totals count those rows, so the group headers
+ * and the "show the rest" arithmetic have to subtract them (countsWithoutOrgSessions).
+ */
+export function splitDevelopmentList<T extends { sessionId: string } & OrgSessionMarks>(
+ rows: readonly T[],
+): { own: T[]; organization: T[] } {
+ const own: T[] = [];
+ const organization: T[] = [];
+ for (const s of rows) (isOrgSession(s) ? organization : own).push(s);
+ return { own, organization };
+}
+
+/** Just the rows the development list shows — splitDevelopmentList's first half. */
+export function withoutOrgSessions<T extends { sessionId: string } & OrgSessionMarks>(
+ rows: readonly T[],
+): T[] {
+ return splitDevelopmentList(rows).own;
+}
+
+/** A per-category counter set, copied so the correction below never writes into the store's. */
+function copyCounts(counts: SessionCategoryCounts): SessionCategoryCounts {
+ return { ...counts };
+}
+
+/**
+ * The server's per-category totals with the organization rows the list does not show taken
+ * back out — the per-Agent totals and their per-Workspace breakdown together, in one pass, so
+ * the two can never disagree about the same group.
+ *
+ * The server counts every Session of an Agent, an organization's desks and ticket sessions
+ * included, while the development list draws the user's own. A group header promising five
+ * where three rows follow is the visible half of that gap; a "show the rest" row that reveals
+ * nothing is the other. Only rows already LOADED can be subtracted, so a group whose
+ * organization rows sit past the fetched pages still counts a little high — the direction
+ * this number has always erred in, and it settles as those pages arrive.
+ *
+ * The fetch logic reads the store's raw counts, not these: what is worth fetching does not
+ * change because a row will not be drawn.
+ */
+export function countsWithoutOrgSessions(
+ byAgent: ReadonlyMap<string, SessionCategoryCounts>,
+ byWorkspace: ReadonlyMap<string, Readonly<Record<string, SessionCategoryCounts>>>,
+ organizationRows: readonly SessionInfo[],
+): {
+ byAgent: ReadonlyMap<string, SessionCategoryCounts>;
+ byWorkspace: ReadonlyMap<string, Readonly<Record<string, SessionCategoryCounts>>>;
+} {
+ if (organizationRows.length === 0) return { byAgent, byWorkspace };
+ const agents = new Map([...byAgent].map(([id, counts]) => [id, copyCounts(counts)]));
+ const workspaces = new Map(
+ [...byWorkspace].map(
+ ([id, perWorkspace]) =>
+ [
+ id,
+ Object.fromEntries(
+ Object.entries(perWorkspace).map(([path, counts]) => [path, copyCounts(counts)]),
+ ),
+ ] as const,
+ ),
+ );
+ for (const row of organizationRows) {
+ const category = sessionCategory(row);
+ const counts = agents.get(row.agentId);
+ if (counts) counts[category] = Math.max(counts[category] - 1, 0);
+ const perWorkspace = workspaces.get(row.agentId)?.[row.workspace];
+ if (perWorkspace) perWorkspace[category] = Math.max(perWorkspace[category] - 1, 0);
+ }
+ return { byAgent: agents, byWorkspace: workspaces };
+}
diff --git a/packages/web/src/lib/settings-sections.ts b/packages/web/src/lib/settings-sections.ts
index 7ffbbc0b..2cc59139 100644
--- a/packages/web/src/lib/settings-sections.ts
+++ b/packages/web/src/lib/settings-sections.ts
@@ -25,7 +25,7 @@ import type { AccountMenuSession } from "./account-menu";
/** A page of the System settings dialog. */
export type SettingsSectionKey =
- "profile" | "general" | "appearance" | "account" | "proxy" | "uploads" | "users";
+ "profile" | "general" | "appearance" | "account" | "proxy" | "uploads" | "company" | "users";
/** Rail heading a page sits under: the viewer's own preferences vs. the whole server's. */
export type SettingsGroupKey = "personal" | "server";
@@ -57,6 +57,8 @@ const SECTION_RULES: ReadonlyArray<SettingsSection & { visible(viewer: SettingsV
{ key: "account", group: "personal", visible: (v) => offersChangePassword(v) },
{ key: "proxy", group: "server", visible: (v) => v.isAdmin },
{ key: "uploads", group: "server", visible: (v) => v.isAdmin },
+ // The company-mode master switch: server-global like the proxy and upload limits.
+ { key: "company", group: "server", visible: (v) => v.isAdmin },
// Single-user under the desktop shell: the server rejects the admin user routes there.
{ key: "users", group: "server", visible: (v) => v.isAdmin && !v.desktopMode },
];
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 6b87dbb8..d9275b48 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -30,6 +30,15 @@ export const en: Strings = {
expandGroup: "Expand",
pinGroup: "Pin group",
unpinGroup: "Unpin group",
+ /** Company mode's page entries (S.nav.org.<key>, the COMPANY_NAV_KEYS manifest), and the mode switch's option names. */
+ org: {
+ overview: "Overview",
+ chart: "Org Chart",
+ calendar: "Calendar",
+ tickets: "Tickets",
+ finance: "Finance",
+ handbook: "Handbook",
+ },
},
/** Machines page: the server's own ssh hosts, and installing this build on one. */
@@ -227,6 +236,14 @@ export const en: Strings = {
"The desktop app keeps an icon in the system tray — the Windows notification area, the macOS menu bar, the Linux tray — for as long as it runs: click it to come back to the window, right-click it to start a session or quit. On by default; turning it off removes the icon at once, no restart, and closing the window then no longer hides it, so the app stays in the Dock on macOS and quits on Windows and Linux.",
currencyInfo: "Display currency for prices; storage is always USD.",
changePasswordInfo: "Change this account's sign-in password.",
+ /** Personal company-mode switch (general page) and the admin master switch (its own server page). */
+ companyModeTitle: "Company mode",
+ companyModePersonal: "Company mode",
+ companyModePersonalInfo:
+ "Off only hides your own mode switch; organizations keep running. The admin master switch sits under Server.",
+ companyModeServer: "Enable company mode",
+ companyModeServerInfo:
+ "The server-wide master switch, off until an admin turns it on here. Off stops the organization scheduler and every organization route and hides the mode switch for everyone. Organizations on disk are untouched, and turning it back on backfills no missed trigger. Beta: it may be unstable; please report what you hit.",
accentNames: {
neutral: "Neutral",
blue: "Blue",
@@ -2228,6 +2245,16 @@ Scenarios:
/** Toast when the session-state (locked) model display is clicked: points at the `/model` command. */
modelLockedHint: "Type /model to switch models",
scheduledFrom: (name: string) => `Triggered by scheduled task "${name}"`,
+ /** `[org_trigger]` banner: what the organization scheduler sent this desk or ticket session, folded into one line. */
+ orgTriggerFrom: (org: string): string => `Triggered by organization "${org}"`,
+ orgTriggerKinds: {
+ init: "Initialization",
+ event: "Calendar event",
+ mention: "Channel mention",
+ ticket_notice: "Ticket notice",
+ ticket_work: "Ticket work",
+ } as Record<string, string>,
+ orgTriggerBudget: (budget: string): string => `budget ${budget}`,
/** One-line notice of a `[background_task_done]` harness message (run_in_background completion): the collapsed row's whole label. */
backgroundDone: (kind: "command" | "subagent", status: "completed" | "failed" | "stopped") => {
const what = kind === "command" ? "Background command" : "Background task";
@@ -3244,6 +3271,793 @@ Scenarios:
"Finish by reporting the scores before and after, the retained version, and each round's change and decision.",
},
+ /** Company mode: the organization switcher and dialogs, and the six organization pages. */
+ company: {
+ /** The mode switch (top-left of the sidebar, above the Project switcher) and its two options. */
+ workMode: "Work mode",
+ modeDev: "Development",
+ modeCompany: "Company",
+ switchToCompany: "Switch to company mode",
+ switchToDev: "Switch to development mode",
+ /**
+ * Company mode is a beta, said in three shapes: the mini tag at the top-right of 「公司」 in
+ * the work-mode switch (and the suffix the collapsed rail's tooltip carries in its place),
+ * the tag's own tooltip, and the one sentence shown both under the admin's master switch
+ * and as the notice a person gets the first time they enter the mode.
+ */
+ beta: "Beta",
+ betaTitle: "Company mode is in beta and may be unstable.",
+ betaNotice: "Beta: it may be unstable; please report what you hit.",
+ /** The organization switcher that replaces the Project switcher in company mode. */
+ switcher: "Organization",
+ noOrganizations: "No organizations yet",
+ createOrg: "New organization",
+ orgSettings: "Organization settings",
+ orgInvalid: "Invalid configuration",
+ orgPaused: "Paused",
+ /** The switcher's check mark beside the open organization (sr text). */
+ switcherCurrent: "Current organization",
+ /** `<project> / <org>` in the switcher: the Project half of the label. */
+ inProject: (project: string, org: string): string => `${project} / ${org}`,
+ /** The empty landing of `/org` when the user has no organization anywhere. */
+ landingTitle: "Company mode",
+ landingBody:
+ "An organization is a group of employee Agents working along a reporting line: a CEO, the employees it hires, a shared board and its channels, and the calendar that drives them. Create one and start by talking to the CEO about its mission.",
+ /** The page a stale deep link lands on: the organization it names is gone. */
+ orgGoneTitle: "Organization not found",
+ orgGoneBody:
+ "It may have been deleted, or you may no longer have access to the Project it belongs to.",
+ backToOrgs: "Back to organizations",
+ /** Create dialog. */
+ createTitle: "New organization",
+ 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",
+ missionHint:
+ "One sentence on why this organization exists; the CEO's first session starts from it",
+ missionPlaceholder:
+ "e.g. Maintain the PenguinHarness docs site and publish a weekly update digest",
+ /** The three examples under the mission field (org-examples.ts holds their order). */
+ missionExampleHint: "Click to fill the mission",
+ missionExamples: {
+ research: {
+ name: "Research Paper Lab",
+ mission:
+ "Set up a company that does research for me: keeps drafting and reviewing papers and produces work that can be submitted to top-tier conferences.",
+ },
+ agentTuning: {
+ name: "Agent Tuning Studio",
+ mission:
+ "Set up a company that optimizes my product Agent: raise its accuracy in real business use and improve the product experience.",
+ },
+ cloudReseller: {
+ name: "Cloud Service Reseller",
+ mission:
+ "Set up a company that runs a cloud-service-style website for me: collect every low-priced service on the market, bundle and resell them at a markup to make money, and grow the site's SEO and visibility.",
+ },
+ mirror: {
+ name: "Digital-twin company",
+ mission:
+ "Set up a company that mirrors our real company: I will give the CEO our real org chart and the CEO creates one digital twin per real employee; each twin's desk session is bound to that colleague's Feishu bot. A twin only receives its own colleague's messages by default, answers what it can on its own and relays the rest to the relevant colleague's twin, who passes it on to the real person. The CEO hires nobody on its own, schedules nothing and files no tickets; the company only relays and solves what it can.",
+ },
+ },
+ createdOpeningCeo: "Organization created — opening the CEO's desk session",
+ /** Create and settings dialogs: the model and the shared workspace, both optional. */
+ modelField: "Model",
+ modelInfo:
+ "The model desk and ticket sessions run on by default; an employee given its own model in the org chart uses that instead. Takes effect from the next work round.",
+ modelHint: "Leave empty to use the Project's default model",
+ modelClear: "Back to the Project default",
+ modelStale: "This model is no longer in the Project's model list",
+ modelProjectDefault: "Project default",
+ modelProjectDefaultNamed: (name: string): string => `Project default (${name})`,
+ modelsLoadFailed:
+ "The model list could not be read; you can still create with the Project default",
+ workspaceField: "Company workspace",
+ workspaceInfo:
+ "The directory the employees work in together: each employee's workspace is one of its sub-directories (or all of it), and desk and ticket sessions run inside it.",
+ workspaceHint:
+ "Leave empty for the organization's own workspace/ directory; a path must be an existing directory on the server",
+ workspaceEmpty: "The organization's own workspace/ directory",
+ workspaceMenuHint: "Pick an existing directory as the company workspace",
+ workspaceClear: "Back to the organization's own directory",
+ /** CEO budget field (create dialog): the CEO's ceiling is the company's, since everyone reports to it. */
+ ceoBudget: "CEO budget",
+ ceoBudgetHint: "A monthly cap; the CEO's budget is the whole company's",
+ /** The create dialog's draft (org-draft.ts): restored on reopen, dropped on create or on demand. */
+ draftRestored: "Restored the draft you had not submitted",
+ clearDraft: "Clear draft",
+ creating: "Creating…",
+ /** Settings dialog (the switcher's entry). */
+ settingsTitle: "Organization settings",
+ timezone: "Timezone",
+ timezoneHint:
+ "An IANA timezone such as Asia/Shanghai; budget periods (calendar months) and channel day files follow it",
+ language: "Working language",
+ languageInfo:
+ "The language the organization works in: its handbook, the employee briefs, the CEO's initialization session and every desk's output are written in it; it is detected from the mission when the organization is created.",
+ languages: {
+ zh: "中文",
+ en: "English",
+ },
+ approvalMode: "Approval mode",
+ approvalModeInfo:
+ "How tool calls in desk and ticket sessions are approved. Unattended runs never stop to ask a person, so there is no always-ask here.",
+ approvalModes: {
+ "allow-all": "Allow all",
+ "read-only": "Read only",
+ "deny-all": "Deny all",
+ } as Record<string, string>,
+ status: "Status",
+ statusActive: "Active",
+ statusPaused: "Paused",
+ pause: "Pause organization",
+ resume: "Resume organization",
+ pauseInfo:
+ "Paused stops every automatic trigger — calendar events no longer fire and @-mentions are not delivered to employees; you can still open any desk session and talk directly. An organization is paused, never deleted: its conversations, employees and tickets stay reachable.",
+ settingsLoadFailed: "The organization's settings could not be read",
+ /** Employee state dot, and the CEO mark. */
+ employeeStates: {
+ running: "Running",
+ idle: "On desk",
+ paused: "Budget paused",
+ } as Record<string, string>,
+ ceo: "CEO",
+ reportsTo: (name: string): string => `Reports to ${name}`,
+ openDesk: "Open desk session",
+ openingDesk: "Opening the desk session…",
+ /** Principals as the chat and tickets name them. */
+ principalSystem: "System",
+ principalAll: "Everyone",
+ /** Spend against a budget, and the unbounded case. */
+ spendOfBudget: (spend: string, budget: string): string => `${spend} / ${budget}`,
+ noBudget: "Unbounded",
+ budgetUnit: (symbol: string): string => `${symbol} / month`,
+ budgetStoredAs: (amount: string): string => `Stored as ${amount} / month`,
+ /** The 工位 group under the company sidebar's channel list: one row per employee. */
+ sessionList: {
+ desks: (n: number): string => `Desks (${n})`,
+ deskOf: (name: string): string => `${name}'s desk`,
+ running: "Running",
+ noEmployees: "This organization has no employees yet",
+ untitledSession: "Untitled session",
+ loadFailed: "The employee list could not be loaded",
+ },
+ overview: {
+ title: "Overview",
+ info: "The organization on one page: employees, the board, today's calendar and this period's budget, plus what needs your decision. A corner button on each block opens its page.",
+ employees: "Employees",
+ onDesk: "On desk",
+ running: "Running",
+ paused: "Budget paused",
+ board: "Board",
+ blocked: "Blocked",
+ today: "Today's calendar",
+ todayEmpty: "Nothing scheduled today",
+ spend: "This period's spend",
+ reviewTickets: "Tickets in review",
+ alerts: "Alerts",
+ alertsEmpty: "No budget alerts this period",
+ /** A fresh organization: point the user at the CEO. */
+ firstStep:
+ "The organization is brand new: open the CEO's desk session to confirm the mission, hire employees and set up the calendar.",
+ /** The hero: who made it, how big it is, which period the spend counts. */
+ createdBy: (user: string): string => `Created by ${user}`,
+ employeesCount: (n: number): string => `${n} employee${n === 1 ? "" : "s"}`,
+ period: (period: string): string => `Period ${period}`,
+ openCeoDesk: "Open the CEO's desk",
+ refreshFailed: "The refresh failed; this is the last data read",
+ /** The hero's mission, clamped to one line until the toggle opens it. */
+ mission: "Mission",
+ expand: "Expand",
+ collapse: "Collapse",
+ /** The KPI strip. */
+ openTickets: "Open tickets",
+ boardTotal: (n: number): string => `${n} in total`,
+ todayCount: (n: number): string => `${n} event${n === 1 ? "" : "s"}`,
+ upcoming: "Upcoming",
+ failed: "Not on time",
+ budgetLeft: (amount: string): string => `${amount} left`,
+ overBudget: (amount: string): string => `${amount} over`,
+ /** The corner button of a KPI cell and of the hero's spend block: where it jumps to. */
+ openChart: "Open the org chart",
+ openBoard: "Open the ticket board",
+ openCalendar: "Open the calendar",
+ openFinance: "Open finance",
+ /** The tooltip of an inbox row's title: the row is inert, its title is what goes there. */
+ openTicket: "Open the ticket",
+ openChannel: "Open the channel",
+ /** The counts under the board bar: each opens the board filtered to the column it counts. */
+ openColumn: (column: string): string => `Open the "${column}" tickets`,
+ /** The three first steps of a new organization (replaces the empty sections). */
+ firstStepsTitle: "First steps",
+ firstStepsInfo:
+ "The guide for a brand-new organization: talk to the CEO about the mission, hire, schedule. Once the first employee is hired or the first ticket filed, the dashboard takes its place.",
+ stepCeoTitle: "Talk to the CEO",
+ stepCeoBody:
+ "Open the CEO's desk session, confirm the mission and let it propose the structure and the first tickets.",
+ stepHireTitle: "Hire employees",
+ stepHireBody:
+ "On the org chart, hire subordinates for the CEO: an existing Agent or a new one, with a title and a budget.",
+ stepScheduleTitle: "Schedule the work",
+ stepScheduleBody:
+ "On the calendar, give employees their rounds: when one is due, its prompt goes to the employee's desk session.",
+ stepDone: "Done",
+ goToChart: "Open the org chart",
+ goToCalendar: "Open the calendar",
+ /** The inbox: what names the reader, what is stuck and what has landed, newest first. */
+ inbox: "Inbox",
+ inboxInfo:
+ "The three things the organization has to tell you, newest first: messages naming you (or everyone) in the all-hands channel, blocked tickets, and the tickets closed as done this period. For anything else, read the channel and the board themselves.",
+ inboxEmpty: "Nothing in the inbox.",
+ /** The filter chips over the rows, each with its own count. */
+ inboxFilters: { all: "All", mention: "@me", blocked: "Blocked", done: "Done" },
+ /** The chip that leads a row, naming what the row is. */
+ inboxCategories: { mention: "@me", blocked: "Blocked", done: "Done" },
+ /** Today's timeline. */
+ timelineMore: (n: number): string => `${n} more — open the calendar`,
+ },
+ calendarOutcomes: {
+ fired: "Fired",
+ queued: "Queued",
+ paused: "Paused",
+ missed: "Missed",
+ error: "Error",
+ } as Record<string, string>,
+ chart: {
+ title: "Org Chart",
+ info: "The employee tree is the reporting line: the CEO at the root, every node an employee Agent. The menu in a node's top-right corner opens its desk session and holds the personnel actions, each of which rewrites the chart file. The canvas zooms with the wheel and pans by dragging; click the percentage to fit the whole chart in the window again.",
+ empty: "The chart is empty",
+ nodeMenu: "Employee actions",
+ hire: "Hire a subordinate",
+ setBudget: "Set budget",
+ changeReportsTo: "Change reporting line",
+ renewDesk: "New desk session",
+ leave: "Leave the organization",
+ ceoCannotLeave: "The CEO cannot leave",
+ invalidEntry: "This entry is invalid",
+ workspaceTail: "Workspace",
+ /** Hire dialog. */
+ hireTitle: (manager: string): string => `Hire a subordinate for ${manager}`,
+ hireSource: "Source",
+ hireExisting: "Pick an existing Agent",
+ hireNew: "Create a new Agent",
+ agent: "Agent",
+ pickAgent: "Pick an Agent…",
+ noAgentsLeft: "No Agent in this Project is left to hire",
+ agentId: "Agent id",
+ agentIdHint:
+ "2–64 characters: a lowercase letter, then lowercase letters, digits or underscores",
+ agentName: "Name",
+ agentNameHint: "Leave empty to use the Agent id",
+ agentDescription: "Description",
+ plugins: "Plugins",
+ pluginsHint:
+ "agent-company (the organization procedures) and agent-development (development skills) are installed by default",
+ pluginsPlaceholder: "No plugins picked",
+ pluginsPicked: (n: number): string => `${n} plugin${n === 1 ? "" : "s"} picked`,
+ pluginsEmpty: "The plugin library has nothing to install",
+ employeeTitle: "Title",
+ employeeTitlePlaceholder: "e.g. Docs engineer",
+ duties: "Duties",
+ dutiesHint: "Written into the chart; the employee reads it at every work run",
+ workspace: "Workspace",
+ workspaceHint:
+ "A sub-directory of the shared workspace (`.` for all of it), or an absolute path that already exists",
+ /** Hiring: the same spec, with the default the server fills in when the field is left empty. */
+ hireWorkspaceHint:
+ "A sub-directory of the shared workspace, or an absolute path that already exists; left empty, a sub-directory named after the employee's Agent id",
+ budget: "Monthly budget",
+ budgetHint:
+ "A monthly cap, leave empty for unbounded; counts the employee plus every subordinate",
+ hireConfirm: (name: string, manager: string): string =>
+ `Add ${name} to the organization, reporting to ${manager}? This rewrites the chart file.`,
+ hired: (name: string): string => `Hired ${name}`,
+ /** Budget / reporting line / desk renewal / leave dialogs. */
+ budgetTitle: (name: string): string => `Set the budget of ${name}`,
+ budgetConfirm: (name: string, budget: string): string =>
+ `Set the monthly budget of ${name} to ${budget}? Past 80% warns; at 100% its automatic triggers pause.`,
+ reportsToTitle: (name: string): string => `Change who ${name} reports to`,
+ reportsToConfirm: (name: string, manager: string): string =>
+ `Have ${name} report to ${manager}? Its subordinates move along with it.`,
+ reportsToCycle: "Cannot report to itself or to one of its own subordinates",
+ renewDeskTitle: (name: string): string => `A new desk session for ${name}`,
+ renewDeskExplain:
+ "A new desk session opens with a fresh context; a changed workspace is written to the org chart.",
+ workspaceInvalid:
+ "Invalid workspace: it must be a sub-directory of the shared workspace, or an absolute path that already exists.",
+ renewed: "Moved to a new desk session",
+ leaveConfirm: (name: string): string =>
+ `Have ${name} leave? It is removed from the chart and its subordinates report to its manager instead; the Agent and every session are kept.`,
+ left: (name: string): string => `${name} has left`,
+ saved: "Chart updated",
+ /** The page: the canvas and its zoom control, the legend, counts, a failed refresh, the detached row. */
+ canvas: "Org chart canvas",
+ zoom: "Zoom",
+ zoomIn: "Zoom in",
+ zoomOut: "Zoom out",
+ zoomFit: "Fit to window",
+ legend: "State legend",
+ employeeCount: (n: number): string => `${n} employee${n === 1 ? "" : "s"}`,
+ spend: "This period's spend",
+ refreshFailed: (error: string): string => `Refresh failed: ${error}`,
+ detached: "Manager not in the chart",
+ detachedNotice: (n: number): string =>
+ `${n} employee${n === 1 ? "" : "s"} cannot reach the CEO along the reporting line: the manager left the organization, or the line loops. Use "Change reporting line" to reattach them.`,
+ /** Hire and edit dialogs: the two sections, the current value, and the field hints. */
+ hireAgentSection: "Agent",
+ hirePositionSection: "Position",
+ agentHint: "Only Agents of this Project not yet in the organization",
+ budgetPlaceholder: "e.g. 30",
+ clearBudget: "Set unbounded",
+ currentValue: (value: string): string => `Current: ${value}`,
+ manager: "Manager",
+ reportsToHint: "Only employees outside its own subtree are listed",
+ },
+ calendar: {
+ title: "Calendar",
+ info: "Every employee's calendar events in a month / week / day view. Each event belongs to one employee and sends its prompt to that employee's desk session when due; colours tell employees apart, and past instances show what the trigger did. Calendar events drive employees' desk sessions to check the board and push tickets on time; use New event, top right, to schedule one for an employee.",
+ month: "Month",
+ week: "Week",
+ day: "Day",
+ today: "Today",
+ prev: "Previous",
+ next: "Next",
+ allEmployees: "All employees",
+ filterEmployee: "Filter by employee",
+ create: "New event",
+ createTitle: "New calendar event",
+ editTitle: (name: string): string => `Edit event "${name}"`,
+ employee: "Employee",
+ name: "Name",
+ nameHint: "The file name (without .toml); fixed once created",
+ prompt: "Prompt",
+ enabled: "Enabled",
+ startAt: "Start",
+ endAt: "End",
+ period: "Period",
+ periodHint: "30m / 12h / 7d, empty for a one-off; 5m at the shortest",
+ delete: "Delete event",
+ deleteConfirm: (name: string): string => `Delete event "${name}"?`,
+ saveConfirm: (name: string): string =>
+ `Save event "${name}"? This rewrites its calendar file.`,
+ outcome: "Outcome",
+ lastFired: "Last fired",
+ nextFire: "Next fire",
+ past: "Past",
+ pausedNote: "Paused: due slots are skipped, not fired",
+ disabledNote: "Disabled",
+ invalidFiles: "Calendar files that failed to parse",
+ empty: "No events yet",
+ emptyHint:
+ "Calendar events drive employees' desk sessions to check the board and push tickets on time; use New event, top right, to schedule one for an employee.",
+ moreEvents: (n: number): string => `${n} more`,
+ /** The month cell's "+N more" is a button: its accessible name, and the day panel it opens. */
+ moreEventsExpand: (n: number): string => `${n} more, expand`,
+ openDay: "Open the day",
+ weekdays: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] as readonly string[],
+ allDay: "All day",
+ promptHint:
+ "What the employee should sweep at this moment, e.g. check the board, push its tickets, report in a channel",
+ monthTitle: (year: number, month: number): string =>
+ `${
+ [
+ "January",
+ "February",
+ "March",
+ "April",
+ "May",
+ "June",
+ "July",
+ "August",
+ "September",
+ "October",
+ "November",
+ "December",
+ ][month - 1] ?? month
+ } ${year}`,
+ /** How an event recurs, for the legend: the period read as a cadence with the time of day. */
+ cadence: {
+ once: "One-off",
+ minutes: (n: number): string => `Every ${n} min`,
+ hours: (n: number): string => `Every ${n} h`,
+ daily: (time: string): string => `Daily ${time}`,
+ days: (n: number, time: string): string => `Every ${n} days ${time}`,
+ weekly: (time: string): string => `Weekly ${time}`,
+ weeks: (n: number, time: string): string => `Every ${n} weeks ${time}`,
+ invalid: "Invalid period",
+ },
+ legendEmpty: "No events yet",
+ legendFilter: (name: string): string => `Show only ${name}'s events`,
+ createAt: (label: string): string => `New event at ${label}`,
+ loadFailed: (error: string): string => `Could not load the calendar: ${error}`,
+ /** The "×" that puts the empty-calendar note away for good (the same sentence stays in the page's "?"). */
+ dismissHint: "Got it",
+ /** Under the start time: why two employees should not share one minute. */
+ staggerHint:
+ "Stagger the rota: give every employee its own minute; desks that fire together compete for the same budget and tickets.",
+ /** Heads the advisory lines a calendar write answers with (the lines themselves come from the server, in English). */
+ warningsPrefix: "Rota notice",
+ },
+ tickets: {
+ title: "Tickets",
+ info: "Five columns are a ticket's life: proposed → in progress → review → done / rejected. Drag a card to move it between columns, click a card's title to open its detail in place; a blocked ticket stays in its column with a badge. A ticket is the organization's unit of work: use New ticket, top right, to create one and name an owner, and the owner's desk session starts a ticket session for it.",
+ columns: {
+ proposed: "Proposed",
+ in_progress: "In progress",
+ review: "Review",
+ done: "Done",
+ rejected: "Rejected",
+ } as Record<string, string>,
+ blockedOnly: "Blocked only",
+ create: "New ticket",
+ createTitle: "New ticket",
+ empty: "No tickets yet",
+ emptyHint:
+ "A ticket is the organization's unit of work: use New ticket, top right, to create one and name an owner, and the owner's desk session starts a ticket session for it.",
+ /** The "×" that puts the empty-board note away for good (the same sentence stays in the page's "?"). */
+ dismissHint: "Got it",
+ columnEmpty: "Empty",
+ ticketTitle: "Title",
+ goal: "Goal",
+ goalHint: "What to achieve, in a paragraph",
+ acceptance: "Acceptance criteria",
+ acceptanceHint: "What counts as done; checked one by one at review",
+ result: "Result",
+ owner: "Owner",
+ noOwner: "Unassigned",
+ ownerSelf: "Yourself",
+ ownerSelfHint: "Left empty, the owner is you",
+ parent: "Parent ticket",
+ noParent: "None",
+ notify: "Notify",
+ notifyHint:
+ "Comma-separated principals, e.g. agent:ceo, user:alice; notified on status changes",
+ priority: "Priority",
+ due: "Due",
+ noDue: "None",
+ blocked: "Blocked",
+ blockedReason: "Blocked reason",
+ blockedBy: "Waiting on",
+ blockedTooltip: (reason: string, by: string): string =>
+ `Blocked: ${reason} (waiting on ${by})`,
+ unblock: "Unblock",
+ unblockConfirm: (title: string): string => `Unblock "${title}"?`,
+ block: "Mark blocked",
+ blockTitle: "Mark blocked",
+ blockReasonHint: "One line on what it is stuck on",
+ blockByHint: "The ticket or principal it waits on",
+ sessions: "Ticket sessions",
+ sessionsCount: (n: number): string => `${n} session${n === 1 ? "" : "s"}`,
+ openSession: "Open session",
+ openTicket: "Open ticket",
+ progress: "Progress",
+ progressEmpty: "No progress recorded yet",
+ addProgress: "Add progress",
+ progressPlaceholder: "One line on what moved…",
+ children: "Child tickets",
+ childrenEmpty: "No child tickets",
+ cost: "This ticket's cost",
+ rolledUpCost: "Total cost",
+ parentLine: (title: string): string => `Parent ticket: ${title}`,
+ moveTitle: "Move ticket",
+ moveConfirm: (title: string, column: string): string => `Move "${title}" to "${column}"?`,
+ rejectReason: "Rejection reason",
+ rejectReasonHint: "One line on why, recorded under the ticket's result",
+ moved: "Ticket moved",
+ invalid:
+ "This ticket is invalid: its status disagrees with its column, or its id is duplicated",
+ invalidFiles: "Ticket files that failed to parse",
+ edit: "Edit fields",
+ saveConfirm: (title: string): string =>
+ `Save the changes to "${title}"? This rewrites the ticket file.`,
+ saved: "Ticket saved",
+ created: "Ticket created",
+ detail: "Ticket detail",
+ back: "Back",
+ dragHint: "Drag to another column to move it",
+ searchPlaceholder: "Search title or id",
+ searchNoMatch: "No matching tickets",
+ dropHere: "Drop here",
+ overdue: "Overdue",
+ summary: "Details",
+ history: "History",
+ historyEmpty: "No history yet",
+ historyActions: {
+ created: "created",
+ assigned: "assigned to",
+ moved: "moved to",
+ blocked: "blocked",
+ unblocked: "unblocked",
+ progress: "noted progress",
+ session_started: "started a session",
+ session_attached: "attached a session",
+ edited: "edited",
+ } as Record<string, string>,
+ slug: "Id slug",
+ slugHint:
+ "Lowercase English words joined by hyphens, e.g. marketplace-site; no digits, derived from the title when left empty",
+ slugInvalid: "Lowercase English words joined by hyphens only, no digits",
+ noGoal: "No goal yet",
+ noAcceptance: "No acceptance criteria yet",
+ noResult: "No result yet",
+ moveTo: "Move to…",
+ move: "Move",
+ copyId: "Copy ticket id",
+ invalidTickets: "Invalid tickets",
+ loadFailed: (error: string): string => `Could not load the board: ${error}`,
+ },
+ finance: {
+ title: "Finance",
+ info: "Budgets are set per employee and count the employee plus every subordinate; a period is a calendar month in the organization's timezone. Reaching 80% warns, reaching 100% pauses that employee's automatic triggers.",
+ period: "Period",
+ thisPeriod: "This period",
+ prevPeriod: "Previous period",
+ total: "Total",
+ unpriced: "* Some usage ran on a model without pricing; the cost is a lower bound",
+ budget: "Budget",
+ editBudget: "Edit budget",
+ budgetPlaceholder: "Unbounded",
+ clearBudget: "Clear",
+ budgetSaved: "Budget updated",
+ own: "Own spend",
+ cumulative: "Cumulative",
+ /** The spend tree reads cumulative against budget in one column; own spend rides in the row tooltip. */
+ cumulativeBudget: "Cumulative spend / budget",
+ ratio: "Ratio",
+ warned: "Warned",
+ paused: "Paused",
+ spendTree: "Spend tree",
+ spendTreeInfo:
+ "Expanded along the reporting line: cumulative spend includes every subordinate, and budget and ratio use the same measure.",
+ ticketsTable: "Ticket spend",
+ ticketsInfo:
+ "Each ticket's contributing-session cost; the total cost adds up along parent tickets. A session attached to several tickets is shared between them.",
+ ticketsEmpty: "No ticket spend this period",
+ rolledUp: "Total cost",
+ /** The ledger's fold: child tickets are hidden until the parent's chevron opens them. */
+ expandChildren: "Show child tickets",
+ collapseChildren: "Hide child tickets",
+ childCount: (n: number): string => `${n} child ticket${n === 1 ? "" : "s"}`,
+ trend: "Trend",
+ alerts: "Alerts and pauses",
+ alertsEmpty: "No alerts this period",
+ alertWarned: (name: string, at: string): string =>
+ `${name} reached 80% of its budget at ${at}`,
+ alertPaused: (name: string, at: string): string =>
+ `${name} reached its budget at ${at}; automatic triggers paused`,
+ alertsHint:
+ "To lift a pause, raise the employee's budget or clear it; the next check resumes it automatically.",
+ /** The KPI row under the title. */
+ kpiTotal: "Total spend",
+ orgBudget: "Organization budget (CEO)",
+ kpiEmployees: "Employees",
+ budgetsSet: (n: number): string => `${n} with a budget`,
+ thresholds: "80% warns, 100% pauses",
+ kpiAlerts: "Alerts",
+ alertsSummary: (warned: number, paused: number): string =>
+ `${warned} warned · ${paused} paused`,
+ /** Column header explanations, and the tree's root mark. */
+ cumulativeInfo:
+ "The employee's own spend plus every subordinate's; budget and ratio use this measure.",
+ rolledUpInfo: "This ticket plus its children.",
+ root: "Root",
+ /** The inline budget editor. */
+ budgetEmptyHint: "Leave empty for unbounded",
+ saveBudget: "Save budget",
+ cancelEdit: "Cancel",
+ editBudgetOf: (name: string): string => `Edit the budget of ${name}`,
+ /** The ticket table's owner column and row action. */
+ openTicket: "Open ticket",
+ /** The trend section. */
+ trendInfo:
+ "The daily cost of every session in the organization, by the organization's timezone; only days with spend are drawn.",
+ trendEmpty: "No spend recorded this period yet",
+ /** The alert list. */
+ alertsInfo:
+ "Every check compares cumulative spend with the budget: reaching 80% records a warning, reaching 100% pauses the employee's and its subordinates' automatic triggers; lifting the pause resumes them.",
+ pausedGroup: "Automatic triggers paused",
+ warnedGroup: "Warned",
+ warnedAt: (at: string): string => `reached 80% at ${at}`,
+ pausedAt: (at: string): string => `reached 100% at ${at}`,
+ /** A refetch failed while the last good data is still on screen. */
+ refreshFailed: "Refresh failed; showing the last loaded data",
+ },
+ channels: {
+ listTitle: "Channels",
+ drawerLabel: "Channel list",
+ allHands: "All hands",
+ mine: "My channels",
+ others: "Other channels",
+ archivedGroup: "Archived",
+ newChannel: "New channel",
+ noChannels: "No channels yet",
+ loadFailed: "Could not load the channels",
+ join: "Join",
+ joining: "Joining…",
+ joined: "Joined the channel",
+ joinTitle: "Join channel",
+ joinConfirm:
+ "Once you join, messages in this channel that @ you reach you, and you can post here.",
+ mentionChip: "@me",
+ badgeUnread: (n: number): string => `${n} unread`,
+ badgeMentions: (n: number): string => `${n} mentioning me`,
+ streamLabel: (name: string): string => `Messages in ${name}`,
+ purpose: "Purpose",
+ purposeEmpty: "No purpose written yet",
+ memberCount: (n: number): string => `${n} member${n === 1 ? "" : "s"}`,
+ memberList: "Channel members",
+ invite: "Invite",
+ inviteTitle: "Invite to the channel",
+ inviteSearch: "Search employees and members",
+ inviteEmpty: "Nobody left to invite",
+ invited: (name: string): string => `Invited ${name}`,
+ leave: "Leave",
+ leaveTitle: "Leave the channel",
+ leaveConfirm: (name: string): string =>
+ `Leave "${name}"? You can still read it, but no @ will reach you and you cannot post until you join again.`,
+ left: "Left the channel",
+ channelMenu: "Channel actions",
+ rename: "Rename",
+ renameTitle: "Rename the channel",
+ editPurpose: "Edit purpose",
+ purposeTitle: "Edit the channel's purpose",
+ archive: "Archive",
+ unarchive: "Unarchive",
+ archiveTitle: "Archive the channel",
+ archiveConfirm: (name: string): string =>
+ `Archive "${name}"? It becomes read-only and folds away under Archived; you can unarchive it at any time.`,
+ archived: "Channel archived",
+ unarchived: "Channel unarchived",
+ archivedNotice: "This channel is archived and read-only. Unarchive it to post again.",
+ notMemberNotice: "You are not in this channel yet. Join it to post.",
+ channelLoadFailed: "Could not load the channel",
+ allHandsInfo:
+ "The all-hands channel is created with the organization: everyone in the organization is here — every employee, every Project member, and you, reading along — nobody can leave it and it cannot be archived. System notices — budget alerts and the like — are posted here.",
+ channelInfo:
+ "An invitation-only channel: an employee joins only when a member invites it, and an @ delivers within the channel's membership. People may join any channel themselves, and can read every channel.",
+ allHandsNoArchive: "The all-hands channel cannot be archived",
+ createTitle: "New channel",
+ creating: "Creating…",
+ created: "Channel created",
+ idField: "Channel id",
+ idHint: "2–64 characters: a lowercase letter, then lowercase letters, digits or underscores",
+ idReserved: "default_channel belongs to the all-hands channel",
+ idTaken: "That id is already taken",
+ nameField: "Display name",
+ nameHint: "Defaults to the id",
+ purposeHint: "One line on what this channel is for",
+ empty: "No messages yet",
+ emptyHint:
+ "Only an @ reaches an employee: @employee delivers to its desk session, @all to every member of the channel; a message without one is just a note.",
+ placeholder: "Type a message — Enter sends, Shift+Enter breaks the line, @ mentions a member",
+ send: "Send",
+ you: "You",
+ mentionAll: "Everyone",
+ mentionAllDesc: "Every member of the channel",
+ employees: "Employees",
+ members: "Members",
+ earlierDays: "Earlier days",
+ ticketRef: (id: string): string => `Ticket ${id}`,
+ sessionRef: "View session",
+ replyTo: "Reply to",
+ /** The ref chips' tooltips: what the chip's own text does not say — where it lands. */
+ openTicketRef: "Open the ticket",
+ replyToJump: "Jump to the message this replies to",
+ hop: (n: number): string => `Relay · hop ${n}`,
+ hopInfo:
+ "Sent automatically by an employee's work run, N relays down an @-chain: a message from a person or the calendar is hop 0, an employee's reply from the run it triggered is hop 1 (unmarked), the reply of the next employee it @-mentioned is hop 2 … At the organization's chain limit (3 by default) an @ is recorded but triggers nobody, so two employees cannot @ each other all night.",
+ hopSummary:
+ 'A mentioned employee may @ somebody else in its reply, which is an @-chain: from hop 2 a message is marked "Relay · hop N", and at the organization\'s chain limit (3 by default) an @ is recorded but triggers nobody.',
+ today: "Today",
+ yesterday: "Yesterday",
+ noEarlier: "No earlier messages",
+ unreadDivider: "Unread",
+ newMessages: (n: number): string => `${n} new message${n === 1 ? "" : "s"}`,
+ mentionPanel: "Mention",
+ mentionsYou: "Mentions you",
+ systemMessage: "System message",
+ sentAt: (time: string): string => `Sent at ${time}`,
+ notices: {
+ employee_joined: (agent: string, title: string, manager: string): string =>
+ `${agent} joined as ${title}, reporting to ${manager}.`,
+ employee_left: (agent: string, manager: string): string =>
+ `${agent} left the organization; reports now go to ${manager}.`,
+ channel_created: (by: string): string => `${by} created the channel.`,
+ channel_archived: (by: string): string => `${by} archived the channel.`,
+ channel_unarchived: (by: string): string => `${by} unarchived the channel.`,
+ channel_joined: (principal: string): string => `${principal} joined the channel.`,
+ channel_invited: (by: string, principal: string): string =>
+ `${by} invited ${principal} to the channel.`,
+ channel_left: (principal: string): string => `${principal} left the channel.`,
+ channel_removed: (by: string, principal: string): string =>
+ `${by} removed ${principal} from the channel.`,
+ budget_warned: (
+ agent: string,
+ percent: string,
+ period: string,
+ cost: string,
+ budget: string,
+ ): string =>
+ `Budget warning: ${agent} has used ${percent}% of its ${period} budget (${cost} / ${budget} USD).`,
+ budget_paused: (
+ agent: string,
+ percent: string,
+ period: string,
+ cost: string,
+ budget: string,
+ ): string =>
+ `Budget pause: ${agent} reached ${percent}% of its ${period} budget (${cost} / ${budget} USD). Its calendar and its subordinates' are paused until the next month or a raised budget; mentions and direct conversations still work.`,
+ ticket_blocked: (ticket: string, title: string): string =>
+ `Ticket ${ticket} (${title}) is blocked.`,
+ ticket_done: (ticket: string, title: string): string =>
+ `Ticket ${ticket} (${title}) is done.`,
+ ticket_rejected: (ticket: string, title: string): string =>
+ `Ticket ${ticket} (${title}) was rejected.`,
+ },
+ },
+ /** The handbook page: the knowledge base directory, its index and its documents. */
+ handbook: {
+ info: "The company's knowledge base: the Markdown documents under handbook/. The index (README.md) is the page every trigger makes the employee Agent read first; the other documents are listed from it and read on demand.",
+ /** The pinned first row: the index, and why it is pinned. */
+ indexLabel: "Index · read first every run",
+ documents: "Documents",
+ /** The tree's own controls: closing every folder, and what a folder row's count means. */
+ collapseAll: "Collapse all",
+ documentsInFolder: (n: number): string => `${n} document${n === 1 ? "" : "s"}`,
+ noOtherDocuments: "No other documents yet. Create one and list it in the index.",
+ emptyDocument: "This document is still empty.",
+ newDocument: "New document",
+ creating: "Creating…",
+ pathField: "Path",
+ pathPlaceholder: "decisions/2026-09-02-hire-plan.md",
+ pathHint:
+ "Relative to handbook/, folders separated by /; each segment starts with a letter or digit and uses only letters, digits, . _ -; .md is added when the extension is left out.",
+ pathInvalid:
+ "Invalid path: each segment starts with a letter or digit and uses only letters, digits, . _ -, folders separated by /, at most eight levels.",
+ pathExists: "That document already exists.",
+ documentCreated: "Document created",
+ deleteDocument: "Delete document",
+ deleteConfirm: (path: string): string =>
+ `Delete ${path}? The document is removed from handbook/; the index entry pointing at it is not updated automatically.`,
+ documentDeleted: "Document deleted",
+ loadFailed: "Could not load the handbook",
+ documentLoadFailed: "Could not load the document",
+ /** A row's tooltip: when the file was last written, and its size. */
+ updatedAt: (time: string, size: string): string => `Updated ${time} · ${size}`,
+ /** Beside the editor's buttons: what the text is, and the shortcut. */
+ editorHint: "Markdown · Ctrl/⌘+S to save",
+ },
+ },
errors: {
networkError: "Network error, please check your connection",
modelCredentialMissing: (modelId: string) =>
@@ -3343,6 +4157,23 @@ Scenarios:
"Disable this channel's connection before clearing its credential.",
messaging_disable_before_scan:
"Disable this channel's connection before rebinding it by scan.",
+ company_mode_off: "Company mode is turned off on this server.",
+ org_not_found: "This organization no longer exists.",
+ org_exists: "That organization id is already taken.",
+ org_invalid:
+ "This organization's configuration needs repair; it accepts no changes until then.",
+ invalid_org_id:
+ "Invalid organization id: 2–64 characters, a lowercase letter first, then lowercase letters, digits or underscores.",
+ employee_not_found: "That Agent is not an employee of this organization.",
+ employee_exists: "That Agent is already an employee of this organization.",
+ calendar_event_exists: "A calendar event with that name already exists.",
+ calendar_event_not_found: "That calendar event no longer exists.",
+ desk_unavailable: "The desk session could not be opened.",
+ ticket_not_found: "That ticket no longer exists.",
+ ticket_invalid: "This ticket file needs repair; it accepts no changes until then.",
+ ticket_session_failed: "The ticket session could not be started.",
+ handbook_file_not_found: "That document no longer exists.",
+ handbook_index_required: "The handbook index (README.md) cannot be deleted.",
},
},
};
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index c3b5d25b..84c13e3c 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -34,6 +34,15 @@ export const zh = {
expandGroup: "展开",
pinGroup: "置顶分组",
unpinGroup: "取消置顶",
+ /** Company mode's page entries (S.nav.org.<key>, the COMPANY_NAV_KEYS manifest), and the mode switch's option names. */
+ org: {
+ overview: "概览",
+ chart: "组织图",
+ calendar: "日历",
+ tickets: "工单",
+ finance: "财务",
+ handbook: "手册",
+ },
},
/** Machines page: the server's own ssh hosts, and installing this build on one. */
@@ -242,6 +251,14 @@ export const zh = {
"桌面应用运行期间在系统托盘(Windows 通知区、macOS 菜单栏、Linux 托盘)常驻一个图标,点击即可回到窗口,右键可开新会话或退出。默认开启;关掉后图标立即消失,无需重启,此时关闭窗口不再收进托盘:macOS 应用留在 Dock,Windows 与 Linux 关窗即退出。",
currencyInfo: "价格显示币种;存储始终为美元。",
changePasswordInfo: "更改当前账号的登录密码。",
+ /** Personal company-mode switch (general page) and the admin master switch (its own server page). */
+ companyModeTitle: "公司模式",
+ companyModePersonal: "公司模式",
+ companyModePersonalInfo:
+ "关闭只隐藏本人的模式切换,组织照常运转;管理员的总开关在「服务器」分组。",
+ companyModeServer: "启用公司模式",
+ companyModeServerInfo:
+ "服务器总开关,缺省关闭,需由管理员在此打开。关闭即停用组织调度器与全部组织路由,并隐藏所有人的模式切换;磁盘上的组织不受影响,重新打开后不会补发错过的触发。内测功能:可能有不稳定的现象,遇到问题请反馈。",
accentNames: {
neutral: "灰白",
blue: "蓝",
@@ -2226,6 +2243,16 @@ Benchmark:
/** Toast when the session-state (locked) model display is clicked: points at the `/model` command. */
modelLockedHint: "输入 /model 切换模型",
scheduledFrom: (name: string) => `由定时任务「${name}」触发`,
+ /** `[org_trigger]` banner: what the organization scheduler sent this desk or ticket session, folded into one line. */
+ orgTriggerFrom: (org: string): string => `由组织「${org}」触发`,
+ orgTriggerKinds: {
+ init: "初始化",
+ event: "日程",
+ mention: "频道 @",
+ ticket_notice: "工单通知",
+ ticket_work: "工单任务",
+ } as Record<string, string>,
+ orgTriggerBudget: (budget: string): string => `预算 ${budget}`,
/** One-line notice of a `[background_task_done]` harness message (run_in_background completion): the collapsed row's whole label. */
backgroundDone: (
kind: "command" | "subagent",
@@ -3222,6 +3249,777 @@ Benchmark:
},
// Server error code → localized copy (the server's message is hardcoded Chinese; this is only a fallback for unknown codes).
+ /** Company mode: the organization switcher and dialogs, and the six organization pages. */
+ company: {
+ /** The mode switch (top-left of the sidebar, above the Project switcher) and its two options. */
+ workMode: "工作模式",
+ modeDev: "开发",
+ modeCompany: "公司",
+ switchToCompany: "切换到公司模式",
+ switchToDev: "切换到开发模式",
+ /**
+ * Company mode is a beta, said in three shapes: the mini tag at the top-right of 「公司」 in
+ * the work-mode switch (and the suffix the collapsed rail's tooltip carries in its place),
+ * the tag's own tooltip, and the one sentence shown both under the admin's master switch
+ * and as the notice a person gets the first time they enter the mode.
+ */
+ beta: "内测版",
+ betaTitle: "公司模式是内测功能,可能有不稳定的现象",
+ betaNotice: "内测功能:可能有不稳定的现象,遇到问题请反馈。",
+ /** The organization switcher that replaces the Project switcher in company mode. */
+ switcher: "组织",
+ noOrganizations: "还没有组织",
+ createOrg: "新建组织",
+ orgSettings: "组织设置",
+ orgInvalid: "配置无效",
+ orgPaused: "已暂停",
+ /** The switcher's check mark beside the open organization (sr text). */
+ switcherCurrent: "当前组织",
+ /** `<project> / <org>` in the switcher: the Project half of the label. */
+ inProject: (project: string, org: string): string => `${project} / ${org}`,
+ /** The empty landing of `/org` when the user has no organization anywhere. */
+ landingTitle: "公司模式",
+ landingBody:
+ "组织是一群员工 Agent 按汇报线协作:一位 CEO、它招募的员工、共享的看板与频道,以及驱动它们的日程。新建一个组织,先和 CEO 谈谈使命。",
+ /** The page a stale deep link lands on: the organization it names is gone. */
+ orgGoneTitle: "组织不存在",
+ orgGoneBody: "它可能已被删除,或者你不再能访问它所属的 Project。",
+ backToOrgs: "回到组织列表",
+ /** Create dialog. */
+ 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: "使命",
+ missionHint: "一句话说明这个组织存在的目的;CEO 的初始化会话从它开始",
+ missionPlaceholder: "例如:为 PenguinHarness 维护文档站,并每周发布一期更新摘要",
+ /** The three examples under the mission field (org-examples.ts holds their order). */
+ missionExampleHint: "点一下填入使命",
+ missionExamples: {
+ research: {
+ name: "科研论文公司",
+ mission: "新建一个公司帮我做科研,不断写稿审稿,产出可以投稿顶级会议的学术论文",
+ },
+ agentTuning: {
+ name: "Agent 优化公司",
+ mission: "新建一个公司帮我优化产品 Agent,提高 Agent 在实际业务中的准确度和产品体验",
+ },
+ cloudReseller: {
+ name: "云服务转售站",
+ mission:
+ "新建一个公司帮我运营一个类似云服务的网站,收集市面上所有的低价服务,并且加价以后打包出售,目的是帮我赚钱,并且要提高站点的 SEO 和曝光程度",
+ },
+ mirror: {
+ name: "员工数字分身公司",
+ mission:
+ "新建一个公司,作为我们现实公司的镜像:我会把现实公司的组织图告诉 CEO,CEO 为每位现实员工创建一个数字分身;每个分身的工位会话绑定到那位同事的飞书机器人。分身默认只被动接收自己同事的消息,能自己解决的就直接回答,解决不了的转给相关同事的分身、再由对方分身转给真人。CEO 不主动招募、不排日程、不开工单,公司只做传话和自主解决问题。",
+ },
+ },
+ createdOpeningCeo: "组织已创建,正在打开 CEO 的工位会话",
+ /** Create and settings dialogs: the model and the shared workspace, both optional. */
+ modelField: "模型",
+ modelInfo:
+ "工位会话与工单会话默认使用的模型;员工在组织图里另有指定时以员工的为准。改动从下一次工作轮起生效。",
+ modelHint: "留空则使用 Project 的默认模型",
+ /** The picker offers models only, so the way back to the Project default is its own control. */
+ modelClear: "改回 Project 默认",
+ /** The stored model is no longer in the Project's model list. */
+ modelStale: "这个模型已不在 Project 的模型列表里",
+ modelProjectDefault: "Project 默认",
+ modelProjectDefaultNamed: (name: string): string => `Project 默认(${name})`,
+ modelsLoadFailed: "模型列表读取失败;仍可按 Project 默认模型创建",
+ workspaceField: "公司工作区",
+ workspaceInfo:
+ "员工共同工作的目录:每位员工的工作区是它的一个子目录(或整个目录),工位会话与工单会话都在其中运行。",
+ workspaceHint: "留空则使用组织自己的 workspace/ 目录;指定时必须是服务器上已存在的目录",
+ workspaceEmpty: "组织自己的 workspace/ 目录",
+ workspaceMenuHint: "选一个已存在的目录作为公司工作区",
+ workspaceClear: "改回组织自己的目录",
+ /** CEO budget field (create dialog): the CEO's ceiling is the company's, since everyone reports to it. */
+ ceoBudget: "CEO 预算",
+ ceoBudgetHint: "每月上限;CEO 的预算就是整家公司的预算",
+ /** The create dialog's draft (org-draft.ts): restored on reopen, dropped on create or on demand. */
+ draftRestored: "已恢复上次未提交的草稿",
+ clearDraft: "清空草稿",
+ creating: "创建中…",
+ /** Settings dialog (the switcher's entry). */
+ settingsTitle: "组织设置",
+ timezone: "时区",
+ timezoneHint: "IANA 时区名,如 Asia/Shanghai;预算周期(自然月)与频道日志按它划分",
+ language: "工作语言",
+ languageInfo:
+ "组织的工作语言:手册、员工简报、CEO 初始化会话与各工位的输出都用这个语言;创建时按使命的语言自动判断。",
+ languages: {
+ zh: "中文",
+ en: "English",
+ },
+ approvalMode: "审批模式",
+ approvalModeInfo:
+ "工位会话与工单会话的工具审批口径。无人值守的运行不会停下来等人拍板,所以这里没有「总是询问」。",
+ approvalModes: {
+ "allow-all": "全部放行",
+ "read-only": "只读",
+ "deny-all": "全部拒绝",
+ } as Record<string, string>,
+ status: "状态",
+ statusActive: "运行中",
+ statusPaused: "已暂停",
+ pause: "暂停组织",
+ resume: "恢复组织",
+ pauseInfo:
+ "暂停后所有自动触发停止——日程不再到点、@ 不再送达员工;你仍可以打开任意工位会话直接对话。组织只会被暂停,不会被删除:它的对话、员工与工单始终可以回去看。",
+ settingsLoadFailed: "组织设置读取失败",
+ /** Employee state dot, and the CEO mark. */
+ employeeStates: {
+ running: "运行中",
+ idle: "在岗",
+ paused: "预算暂停",
+ } as Record<string, string>,
+ ceo: "CEO",
+ reportsTo: (name: string): string => `汇报给 ${name}`,
+ openDesk: "打开工位会话",
+ openingDesk: "正在打开工位会话…",
+ /** Principals as the chat and tickets name them. */
+ principalSystem: "系统",
+ principalAll: "所有人",
+ /** Spend against a budget, and the unbounded case. */
+ spendOfBudget: (spend: string, budget: string): string => `${spend} / ${budget}`,
+ noBudget: "不限",
+ /**
+ * A budget is a monthly cap the server keeps in USD. A budget box speaks the currency the
+ * reader picked, so the unit rides after the box, and a box in CNY says under itself what
+ * it will actually store.
+ */
+ budgetUnit: (symbol: string): string => `${symbol} / 月`,
+ budgetStoredAs: (amount: string): string => `存为 ${amount} / 月`,
+ /** The 工位 group under the company sidebar's channel list: one row per employee. */
+ sessionList: {
+ desks: (n: number): string => `工位(${n})`,
+ deskOf: (name: string): string => `${name} 的工位`,
+ running: "运行中",
+ noEmployees: "这个组织还没有员工",
+ untitledSession: "未命名会话",
+ loadFailed: "员工列表加载失败",
+ },
+ overview: {
+ title: "概览",
+ info: "组织的全局一页:员工、看板、今日日程与本周期预算,以及需要你拍板的事。每块角上有一个按钮,点它进对应页面。",
+ employees: "员工",
+ onDesk: "在岗",
+ running: "运行中",
+ paused: "预算暂停",
+ board: "看板",
+ blocked: "被阻塞",
+ today: "今日日程",
+ todayEmpty: "今天没有日程",
+ spend: "本周期支出",
+ reviewTickets: "审核中的工单",
+ alerts: "告警",
+ alertsEmpty: "本周期没有预算告警",
+ /** A fresh organization: point the user at the CEO. */
+ firstStep: "组织刚建立:先打开 CEO 的工位会话,确认使命、招募员工并安排日程。",
+ /** The hero: who made it, how big it is, which period the spend counts. */
+ createdBy: (user: string): string => `由 ${user} 创建`,
+ employeesCount: (n: number): string => `${n} 位员工`,
+ period: (period: string): string => `${period} 周期`,
+ openCeoDesk: "打开 CEO 工位",
+ refreshFailed: "刷新失败,显示的是上次读取的数据",
+ /** The hero's mission, clamped to one line until the toggle opens it. */
+ mission: "使命",
+ expand: "展开",
+ collapse: "收起",
+ /** The KPI strip. */
+ openTickets: "未完结工单",
+ boardTotal: (n: number): string => `共 ${n} 张`,
+ todayCount: (n: number): string => `${n} 项`,
+ upcoming: "待触发",
+ failed: "未按时",
+ budgetLeft: (amount: string): string => `剩余 ${amount}`,
+ overBudget: (amount: string): string => `超支 ${amount}`,
+ /** The corner button of a KPI cell and of the hero's spend block: where it jumps to. */
+ openChart: "打开组织图",
+ openBoard: "打开工单看板",
+ openCalendar: "打开日历",
+ openFinance: "打开财务",
+ /** The tooltip of an inbox row's title: the row is inert, its title is what goes there. */
+ openTicket: "查看工单",
+ openChannel: "打开频道",
+ /** The counts under the board bar: each opens the board filtered to the column it counts. */
+ openColumn: (column: string): string => `查看「${column}」的工单`,
+ /** The three first steps of a new organization (replaces the empty sections). */
+ firstStepsTitle: "三步上手",
+ firstStepsInfo:
+ "组织刚建立时的引导:和 CEO 谈使命、招募员工、安排日程。招到第一位员工或开出第一张工单后,这里换成日常仪表盘。",
+ stepCeoTitle: "和 CEO 谈使命",
+ stepCeoBody: "打开 CEO 的工位会话,确认使命,让它提出组织结构与首批工单。",
+ stepHireTitle: "招募员工",
+ stepHireBody: "在组织图里为 CEO 招募下属:选已有 Agent 或新建一个,给头衔与预算。",
+ stepScheduleTitle: "安排日程",
+ stepScheduleBody: "在日历里为员工安排巡检:到点即向它的工位会话发送提示词。",
+ stepDone: "已完成",
+ goToChart: "去组织图",
+ goToCalendar: "去日历",
+ /** The inbox: what names the reader, what is stuck and what has landed, newest first. */
+ inbox: "收件箱",
+ inboxInfo:
+ "按时间倒序列出组织要对你说的三件事:全员频道里 @我(或 @所有人)的消息、被阻塞的工单、本周期已完成的工单。其余的去频道与看板本身看。",
+ inboxEmpty: "收件箱是空的",
+ /** The filter chips over the rows, each with its own count. */
+ inboxFilters: { all: "全部", mention: "@我", blocked: "阻塞", done: "已完成" },
+ /** The chip that leads a row, naming what the row is. */
+ inboxCategories: { mention: "@我", blocked: "阻塞", done: "已完成" },
+ /** Today's timeline. */
+ timelineMore: (n: number): string => `还有 ${n} 项,打开日历查看`,
+ },
+ calendarOutcomes: {
+ fired: "已触发",
+ queued: "排队",
+ paused: "已暂停",
+ missed: "已错过",
+ error: "出错",
+ } as Record<string, string>,
+ chart: {
+ title: "组织图",
+ info: "员工树即汇报线:CEO 为根,每个节点是一位员工 Agent。节点右上角的菜单里是「打开工位会话」和人事操作,每一项人事操作都会改写组织图文件。画布可滚轮缩放、拖拽平移;点右上角的百分比回到适应窗口。",
+ empty: "组织图为空",
+ nodeMenu: "员工操作",
+ hire: "招募下属",
+ setBudget: "设预算",
+ changeReportsTo: "调整汇报线",
+ renewDesk: "换工位",
+ leave: "离任",
+ ceoCannotLeave: "CEO 不能离任",
+ invalidEntry: "该条目无效",
+ workspaceTail: "工作区",
+ /** Hire dialog. */
+ hireTitle: (manager: string): string => `为 ${manager} 招募下属`,
+ hireSource: "来源",
+ hireExisting: "选择已有 Agent",
+ hireNew: "新建 Agent",
+ agent: "Agent",
+ pickAgent: "选择 Agent…",
+ noAgentsLeft: "本 Project 没有可招募的 Agent",
+ agentId: "Agent id",
+ agentIdHint: "2~64 位:小写字母开头,仅小写字母、数字与下划线",
+ agentName: "名称",
+ agentNameHint: "留空则使用 Agent id",
+ agentDescription: "描述",
+ plugins: "插件",
+ pluginsHint: "缺省安装 agent-company(组织流程)与 agent-development(开发技能)",
+ pluginsPlaceholder: "未选择插件",
+ pluginsPicked: (n: number): string => `已选 ${n} 个插件`,
+ pluginsEmpty: "插件库暂无可安装的插件",
+ employeeTitle: "头衔",
+ employeeTitlePlaceholder: "例如:文档工程师",
+ duties: "职责",
+ dutiesHint: "写进组织图,员工每次工作轮都会读到",
+ workspace: "工作区",
+ workspaceHint: "公共工作区下的子目录(`.` 为整个公共工作区),或一个已存在的绝对路径",
+ /** Hiring: the same spec, with the default the server fills in when the field is left empty. */
+ hireWorkspaceHint:
+ "公共工作区下的子目录,或一个已存在的绝对路径;留空即以该员工的 Agent id 命名的子目录",
+ budget: "月预算",
+ budgetHint: "每月上限,留空为不限;口径是本人加全部下属的累计支出",
+ hireConfirm: (name: string, manager: string): string =>
+ `将 ${name} 加入组织,汇报给 ${manager}?会改写组织图文件。`,
+ hired: (name: string): string => `已招募 ${name}`,
+ /** Budget / reporting line / desk renewal / leave dialogs. */
+ budgetTitle: (name: string): string => `设置 ${name} 的预算`,
+ budgetConfirm: (name: string, budget: string): string =>
+ `将 ${name} 的月预算改为 ${budget}?超过 80% 告警,达到 100% 暂停其自动触发。`,
+ reportsToTitle: (name: string): string => `调整 ${name} 的汇报线`,
+ reportsToConfirm: (name: string, manager: string): string =>
+ `让 ${name} 改为汇报给 ${manager}?其下属随之一起移动。`,
+ reportsToCycle: "不能汇报给自己或自己的下属",
+ renewDeskTitle: (name: string): string => `为 ${name} 换工位`,
+ renewDeskExplain: "换工位会开一个新的工位会话并重置上下文;改了工作区就写入员工树。",
+ workspaceInvalid: "工作区无效:需要是公共工作区下的子目录,或一个已存在的绝对路径。",
+ renewed: "已换到新的工位会话",
+ leaveConfirm: (name: string): string =>
+ `让 ${name} 离任?它会移出组织图,其下属改为汇报给它的上级;Agent 本身与所有会话保留。`,
+ left: (name: string): string => `${name} 已离任`,
+ saved: "组织图已更新",
+ /** The page: the canvas and its zoom control, the legend, counts, a failed refresh, the detached row. */
+ canvas: "组织图画布",
+ zoom: "缩放",
+ zoomIn: "放大",
+ zoomOut: "缩小",
+ zoomFit: "适应窗口",
+ legend: "运行态图例",
+ employeeCount: (n: number): string => `${n} 位员工`,
+ spend: "本周期支出",
+ refreshFailed: (error: string): string => `刷新失败:${error}`,
+ detached: "上级不在组织图中",
+ detachedNotice: (n: number): string =>
+ `${n} 位员工的汇报线接不到 CEO:上级已离开组织,或汇报线成环。用「调整汇报线」把它们接回员工树。`,
+ /** Hire and edit dialogs: the two sections, the current value, and the field hints. */
+ hireAgentSection: "Agent",
+ hirePositionSection: "职位",
+ agentHint: "只列出本 Project 中尚未加入组织的 Agent",
+ budgetPlaceholder: "例如 30",
+ clearBudget: "设为不限",
+ currentValue: (value: string): string => `当前:${value}`,
+ manager: "上级",
+ reportsToHint: "只列出不在其下属范围内的员工",
+ },
+ calendar: {
+ title: "日历",
+ info: "全员日程项的月 / 周 / 日视图。每条日程属于一位员工,到点即向它的工位会话发送提示词;颜色按员工区分,已过去的实例标出触发结果。日程驱动员工的工位会话按时巡检看板、推进工单,点右上角「新建日程」为某位员工安排一条。",
+ month: "月",
+ week: "周",
+ day: "日",
+ today: "今天",
+ prev: "上一段",
+ next: "下一段",
+ allEmployees: "全部员工",
+ filterEmployee: "按员工筛选",
+ create: "新建日程",
+ createTitle: "新建日程",
+ editTitle: (name: string): string => `编辑日程「${name}」`,
+ employee: "员工",
+ name: "名称",
+ nameHint: "即文件名(不含 .toml),创建后不可改",
+ prompt: "提示词",
+ enabled: "启用",
+ startAt: "开始时间",
+ endAt: "结束时间",
+ period: "周期",
+ periodHint: "30m / 12h / 7d,留空为一次性;最短 5m",
+ delete: "删除日程",
+ deleteConfirm: (name: string): string => `确认删除日程「${name}」?`,
+ saveConfirm: (name: string): string => `保存日程「${name}」?会改写它的日程文件。`,
+ outcome: "结果",
+ lastFired: "最近触发",
+ nextFire: "下次触发",
+ past: "已过去",
+ pausedNote: "已暂停:到点跳过,不触发",
+ disabledNote: "已停用",
+ invalidFiles: "解析失败的日程文件",
+ empty: "还没有日程",
+ emptyHint:
+ "日程驱动员工的工位会话按时巡检看板、推进工单,点右上角「新建日程」为某位员工安排一条。",
+ moreEvents: (n: number): string => `还有 ${n} 项`,
+ /** The month cell's "+N more" is a button: its accessible name, and the day panel it opens. */
+ moreEventsExpand: (n: number): string => `还有 ${n} 项,展开`,
+ openDay: "查看当天",
+ weekdays: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"] as readonly string[],
+ allDay: "全天",
+ promptHint: "写下你希望员工在这一刻做的巡检,例如:检查看板、推进自己的工单、在频道汇报",
+ monthTitle: (year: number, month: number): string => `${year} 年 ${month} 月`,
+ /** How an event recurs, for the legend: the period read as a cadence with the time of day. */
+ cadence: {
+ once: "一次性",
+ minutes: (n: number): string => `每 ${n} 分钟`,
+ hours: (n: number): string => `每 ${n} 小时`,
+ daily: (time: string): string => `每天 ${time}`,
+ days: (n: number, time: string): string => `每 ${n} 天 ${time}`,
+ weekly: (time: string): string => `每周 ${time}`,
+ weeks: (n: number, time: string): string => `每 ${n} 周 ${time}`,
+ invalid: "周期无效",
+ },
+ legendEmpty: "还没有日程",
+ legendFilter: (name: string): string => `只看 ${name} 的日程`,
+ createAt: (label: string): string => `在 ${label} 新建日程`,
+ loadFailed: (error: string): string => `日历加载失败:${error}`,
+ /** The "×" that puts the empty-calendar note away for good (the same sentence stays in the page's "?"). */
+ dismissHint: "知道了",
+ /** Under the start time: why two employees should not share one minute. */
+ staggerHint:
+ "错峰安排:给每位员工各自的时刻,不要让多位员工在同一分钟触发,避免争抢预算与工单。",
+ /** Heads the advisory lines a calendar write answers with (the lines themselves come from the server, in English). */
+ warningsPrefix: "排班提醒",
+ },
+ tickets: {
+ title: "工单",
+ info: "五列看板即工单的生命周期:提议 → 进行中 → 审核中 → 已完成 / 已拒绝。拖拽卡片移列,点卡片标题在原地弹出详情窗口;被阻塞的工单留在原列并带角标。工单是组织的工作单位:点右上角「新建工单」建一张并指定负责人,它的工位会话会为这张工单发起工单会话。",
+ columns: {
+ proposed: "提议",
+ in_progress: "进行中",
+ review: "审核中",
+ done: "已完成",
+ rejected: "已拒绝",
+ } as Record<string, string>,
+ blockedOnly: "只看被阻塞",
+ create: "新建工单",
+ createTitle: "新建工单",
+ empty: "还没有工单",
+ emptyHint:
+ "工单是组织的工作单位:点右上角「新建工单」建一张并指定负责人,它的工位会话会为这张工单发起工单会话。",
+ /** The "×" that puts the empty-board note away for good (the same sentence stays in the page's "?"). */
+ dismissHint: "知道了",
+ columnEmpty: "空",
+ ticketTitle: "标题",
+ goal: "目标",
+ goalHint: "要达成什么,一段话即可",
+ acceptance: "验收标准",
+ acceptanceHint: "怎样算完成;审核时逐条核对",
+ result: "结果",
+ owner: "负责人",
+ noOwner: "未指定",
+ /** The create dialog's default owner: whoever is filing the ticket. */
+ ownerSelf: "自己",
+ ownerSelfHint: "留空则为自己",
+ parent: "父工单",
+ noParent: "无",
+ notify: "通知人",
+ notifyHint: "逗号分隔的主体,如 agent:ceo, user:alice;状态变化时通知",
+ priority: "优先级",
+ due: "截止",
+ noDue: "无",
+ blocked: "被阻塞",
+ blockedReason: "阻塞原因",
+ blockedBy: "等谁",
+ blockedTooltip: (reason: string, by: string): string => `被阻塞:${reason}(等 ${by})`,
+ unblock: "解除阻塞",
+ unblockConfirm: (title: string): string => `解除「${title}」的阻塞?`,
+ block: "标记阻塞",
+ blockTitle: "标记阻塞",
+ blockReasonHint: "一句话说明卡在哪里",
+ blockByHint: "等哪张工单或哪位主体",
+ sessions: "关联工单会话",
+ sessionsCount: (n: number): string => `${n} 个会话`,
+ openSession: "打开会话",
+ /** The row action of a child ticket, and the tooltip of every ticket title that opens one. */
+ openTicket: "打开工单",
+ progress: "进度",
+ progressEmpty: "还没有进度记录",
+ addProgress: "追加进度",
+ progressPlaceholder: "一句话记下进展…",
+ children: "子工单",
+ childrenEmpty: "没有子工单",
+ cost: "本单成本",
+ rolledUpCost: "总成本",
+ /** The card's muted parent line; the drawer names the parent in a labelled field instead. */
+ parentLine: (title: string): string => `父工单:${title}`,
+ moveTitle: "移动工单",
+ moveConfirm: (title: string, column: string): string => `将「${title}」移到「${column}」?`,
+ rejectReason: "拒绝理由",
+ rejectReasonHint: "一句话说明为什么拒绝,记入工单的结果",
+ moved: "工单已移动",
+ invalid: "该工单无效:状态与所在列不符,或 id 重复",
+ invalidFiles: "无法解析的工单文件",
+ edit: "编辑字段",
+ saveConfirm: (title: string): string => `保存对「${title}」的修改?会改写工单文件。`,
+ saved: "工单已保存",
+ created: "工单已创建",
+ detail: "工单详情",
+ /** Header control of the detail dialog: back to the ticket this one was opened from (a parent, a child). */
+ back: "返回",
+ dragHint: "拖到另一列即可移动",
+ searchPlaceholder: "搜索标题或 id",
+ searchNoMatch: "没有匹配的工单",
+ dropHere: "拖到这里",
+ overdue: "已逾期",
+ summary: "基本信息",
+ history: "操作历史",
+ historyEmpty: "还没有操作记录",
+ /** The frontmatter's history actions; a history line names one and nothing else. */
+ historyActions: {
+ created: "创建",
+ assigned: "指派给",
+ moved: "移到",
+ blocked: "阻塞",
+ unblocked: "解除阻塞",
+ progress: "写进展",
+ session_started: "发起会话",
+ session_attached: "挂接会话",
+ edited: "编辑",
+ } as Record<string, string>,
+ slug: "id 短名",
+ slugHint: "小写英文单词用连字符连接,如 marketplace-site;不能有数字,留空则由标题生成",
+ slugInvalid: "只能用小写英文单词,以连字符连接,不能有数字",
+ noGoal: "还没有写目标",
+ noAcceptance: "还没有写验收标准",
+ noResult: "还没有结果",
+ moveTo: "移到…",
+ move: "移动",
+ copyId: "复制工单 id",
+ invalidTickets: "无效的工单",
+ loadFailed: (error: string): string => `看板加载失败:${error}`,
+ },
+ finance: {
+ title: "财务",
+ info: "预算按员工设置,口径是本人加全部下属的累计支出;周期为自然月(组织时区)。达到 80% 告警,达到 100% 暂停该员工的自动触发。",
+ period: "周期",
+ thisPeriod: "本周期",
+ prevPeriod: "上周期",
+ total: "合计",
+ unpriced: "* 部分用量使用了未配置价格的模型,成本为下限",
+ budget: "预算",
+ editBudget: "编辑预算",
+ budgetPlaceholder: "不限",
+ clearBudget: "清空",
+ budgetSaved: "预算已更新",
+ own: "本人支出",
+ cumulative: "累计支出",
+ /** The spend tree reads cumulative against budget in one column; own spend rides in the row tooltip. */
+ cumulativeBudget: "累计成本 / 预算",
+ ratio: "占比",
+ warned: "已告警",
+ paused: "已暂停",
+ spendTree: "支出树",
+ spendTreeInfo: "沿汇报线展开:累计支出包含全部下属,预算与占比按同一口径。",
+ ticketsTable: "工单支出",
+ ticketsInfo: "每张工单的贡献会话成本;总成本沿父工单累加。挂到多张工单的会话按份数分摊。",
+ ticketsEmpty: "本周期没有工单支出",
+ rolledUp: "总成本",
+ /** The ledger's fold: child tickets are hidden until the parent's chevron opens them. */
+ expandChildren: "展开子工单",
+ collapseChildren: "收起子工单",
+ childCount: (n: number): string => `${n} 张子工单`,
+ trend: "趋势",
+ alerts: "告警与暂停",
+ alertsEmpty: "本周期没有告警",
+ alertWarned: (name: string, at: string): string => `${name} 于 ${at} 达到预算 80%`,
+ alertPaused: (name: string, at: string): string =>
+ `${name} 于 ${at} 达到预算上限,已暂停自动触发`,
+ alertsHint: "解除方式:调高该员工的预算,或清空预算;下一次巡检自动恢复。",
+ /** The KPI row under the title. */
+ kpiTotal: "合计支出",
+ orgBudget: "组织预算(CEO)",
+ kpiEmployees: "员工",
+ budgetsSet: (n: number): string => `${n} 人设了预算`,
+ thresholds: "达到 80% 告警,达到 100% 暂停",
+ kpiAlerts: "告警",
+ alertsSummary: (warned: number, paused: number): string => `${warned} 告警 · ${paused} 暂停`,
+ /** Column header explanations, and the tree's root mark. */
+ cumulativeInfo: "本人加全部下属的支出之和;预算与占比按这个口径。",
+ rolledUpInfo: "本工单与子工单的成本之和。",
+ root: "根",
+ /** The inline budget editor. */
+ budgetEmptyHint: "留空为不限",
+ saveBudget: "保存预算",
+ cancelEdit: "取消",
+ editBudgetOf: (name: string): string => `编辑 ${name} 的预算`,
+ /** The ticket table's owner column and row action. */
+ openTicket: "打开工单",
+ /** The trend section. */
+ trendInfo: "组织全部会话每天的成本合计,按组织时区分日;只画有支出的日子。",
+ trendEmpty: "本周期还没有支出记录",
+ /** The alert list. */
+ alertsInfo:
+ "每次巡检核对累计支出与预算:达到 80% 记一次告警,达到 100% 暂停该员工及其下属的自动触发;解除后自动恢复。",
+ pausedGroup: "已暂停自动触发",
+ warnedGroup: "已告警",
+ warnedAt: (at: string): string => `${at} 达到 80%`,
+ pausedAt: (at: string): string => `${at} 达到 100%`,
+ /** A refetch failed while the last good data is still on screen. */
+ refreshFailed: "刷新失败,显示的是上次加载的数据",
+ },
+ /**
+ * Channels — company mode's home surface. The sidebar lists them where development mode
+ * lists conversations; the channel view holds the header, the message stream and the
+ * composer. The all-hands channel's stored name is never shown: `allHands` is its label
+ * everywhere.
+ */
+ channels: {
+ /** The sidebar's list, its groups and the dialog above it. */
+ listTitle: "频道",
+ /** The phone drawer's hamburger, which opens the channel list (development mode names it S.chat.sessionList). */
+ drawerLabel: "频道列表",
+ allHands: "全员频道",
+ mine: "我的频道",
+ others: "其他频道",
+ archivedGroup: "已归档",
+ newChannel: "新建频道",
+ noChannels: "还没有频道",
+ loadFailed: "频道列表加载失败",
+ join: "加入",
+ joining: "加入中…",
+ joined: "已加入频道",
+ joinTitle: "加入频道",
+ joinConfirm: "加入后你会收到这个频道里 @你 的消息,也能在这里发言。",
+ /** A row's badges, and the sentence they lend to its accessible name. */
+ mentionChip: "@我",
+ badgeUnread: (n: number): string => `${n} 条未读`,
+ badgeMentions: (n: number): string => `${n} 条 @我`,
+ /** The channel header and what its controls do. */
+ streamLabel: (name: string): string => `「${name}」的消息`,
+ purpose: "主题",
+ purposeEmpty: "还没有写主题",
+ memberCount: (n: number): string => `${n} 人`,
+ memberList: "频道成员",
+ invite: "邀请",
+ inviteTitle: "邀请到频道",
+ inviteSearch: "搜索员工或成员",
+ inviteEmpty: "没有可邀请的人了",
+ invited: (name: string): string => `已邀请 ${name}`,
+ leave: "离开",
+ leaveTitle: "离开频道",
+ leaveConfirm: (name: string): string =>
+ `确认离开「${name}」?你仍然可以阅读,但不会再收到 @,也不能发言,直到重新加入。`,
+ left: "已离开频道",
+ channelMenu: "频道操作",
+ rename: "重命名",
+ renameTitle: "重命名频道",
+ editPurpose: "改主题",
+ purposeTitle: "修改频道主题",
+ archive: "归档",
+ unarchive: "取消归档",
+ archiveTitle: "归档频道",
+ archiveConfirm: (name: string): string =>
+ `确认归档「${name}」?归档后频道只读,并折叠进「已归档」,随时可以取消归档。`,
+ archived: "频道已归档",
+ unarchived: "已取消归档",
+ archivedNotice: "这个频道已归档,只读。取消归档后才能继续发言。",
+ notMemberNotice: "你还不是这个频道的成员。加入后才能发言。",
+ channelLoadFailed: "频道加载失败",
+ /** The "?" beside the channel name, in its two kinds. */
+ allHandsInfo:
+ "全员频道随组织一起创建:组织里的每个人都在这里——每位员工、每位 Project 成员,你也在这里看——谁也不能退出,也不能归档;预算告警等系统通知都发在这里。",
+ channelInfo:
+ "受邀频道:员工只能由成员邀请进来,@ 也只在频道成员之间送达;人可以自行加入,并且可以阅读任何频道。",
+ /** Why the all-hands channel's menu has no archive row; what that channel IS stays in the "?" above. */
+ allHandsNoArchive: "全员频道不可归档",
+ /** The new-channel dialog. */
+ createTitle: "新建频道",
+ creating: "创建中…",
+ created: "频道已创建",
+ idField: "频道 id",
+ idHint: "2–64 个字符:小写字母开头,仅小写字母、数字和下划线",
+ idReserved: "default_channel 留给全员频道",
+ idTaken: "这个 id 已经被占用",
+ nameField: "显示名",
+ nameHint: "留空则用 id",
+ purposeHint: "一句话说明这个频道是做什么的",
+ /** The message stream. */
+ empty: "还没有消息",
+ emptyHint:
+ "只有 @ 才会打扰员工:@某位员工 送进它的工位会话,@all 送给频道里所有成员;不带 @ 的消息只是留言。",
+ placeholder: "输入消息,Enter 发送,Shift+Enter 换行,@ 提及成员",
+ send: "发送",
+ you: "你",
+ mentionAll: "所有人",
+ mentionAllDesc: "频道全部成员",
+ employees: "员工",
+ members: "成员",
+ earlierDays: "更早的记录",
+ ticketRef: (id: string): string => `工单 ${id}`,
+ sessionRef: "查看会话",
+ replyTo: "回复",
+ /** The ref chips' tooltips: what the chip's own text does not say — where it lands. */
+ openTicketRef: "查看工单",
+ replyToJump: "跳到被回复的消息",
+ hop: (n: number): string => `自动接力 · 第 ${n} 跳`,
+ /** The chip's tooltip, and the one line about hops the channel header's "?" carries. */
+ hopInfo:
+ "这条消息由员工的工作轮自动发出,是一条 @ 连锁的第 N 跳:人或日程发起的消息是第 0 跳,员工被 @ 后在工作轮里的回复是第 1 跳(不标),再被 @ 的员工回复是第 2 跳……到达组织设置的连锁上限(缺省 3)后 @ 只记录、不再触发任何人,避免两个员工互相 @ 到天亮。",
+ hopSummary:
+ "被 @ 的员工在回复里再 @ 别人,就是一条 @ 连锁:从第 2 跳起消息会标出「自动接力 · 第 N 跳」,到达组织的连锁上限(缺省 3)后 @ 只记录、不再触发任何人。",
+ /** Day separators, paging and the read cursor in the stream. */
+ today: "今天",
+ yesterday: "昨天",
+ noEarlier: "没有更早的记录",
+ unreadDivider: "以下为未读",
+ newMessages: (n: number): string => `${n} 条新消息`,
+ /** The composer's @ autocomplete. */
+ mentionPanel: "提及",
+ mentionsYou: "提到了你",
+ /** Accessible name of a system banner and of a message's per-line time. */
+ systemMessage: "系统消息",
+ sentAt: (time: string): string => `发送于 ${time}`,
+ /**
+ * The system lines, one sentence per kind the server records (features/company/channel-notices.ts).
+ * Principals arrive already resolved to display names; a period is `yyyy-mm` and the money
+ * figures are the server's own, in USD.
+ */
+ notices: {
+ employee_joined: (agent: string, title: string, manager: string): string =>
+ `${agent} 以「${title}」身份加入,汇报给 ${manager}。`,
+ employee_left: (agent: string, manager: string): string =>
+ `${agent} 已离开组织,其下属改为汇报给 ${manager}。`,
+ channel_created: (by: string): string => `${by} 创建了这个频道。`,
+ channel_archived: (by: string): string => `${by} 归档了这个频道。`,
+ channel_unarchived: (by: string): string => `${by} 取消了这个频道的归档。`,
+ channel_joined: (principal: string): string => `${principal} 加入了频道。`,
+ channel_invited: (by: string, principal: string): string =>
+ `${by} 邀请 ${principal} 加入了频道。`,
+ channel_left: (principal: string): string => `${principal} 离开了频道。`,
+ channel_removed: (by: string, principal: string): string =>
+ `${by} 把 ${principal} 移出了频道。`,
+ budget_warned: (
+ agent: string,
+ percent: string,
+ period: string,
+ cost: string,
+ budget: string,
+ ): string =>
+ `预算提醒:${agent} 已用掉 ${period} 预算的 ${percent}%(${cost} / ${budget} USD)。`,
+ budget_paused: (
+ agent: string,
+ percent: string,
+ period: string,
+ cost: string,
+ budget: string,
+ ): string =>
+ `预算暂停:${agent} 已达到 ${period} 预算的 ${percent}%(${cost} / ${budget} USD)。它与下属的日历已暂停,直到下个月或调高预算;@ 提及和直接对话仍然可用。`,
+ ticket_blocked: (ticket: string, title: string): string =>
+ `工单 ${ticket}(${title})被阻塞了。`,
+ ticket_done: (ticket: string, title: string): string =>
+ `工单 ${ticket}(${title})已完成。`,
+ ticket_rejected: (ticket: string, title: string): string =>
+ `工单 ${ticket}(${title})已被拒绝。`,
+ },
+ },
+ /** The handbook page: the knowledge base directory, its index and its documents. */
+ handbook: {
+ info: "组织的知识库:handbook/ 目录下的 Markdown 文档。索引(README.md)是每次触发都会让员工 Agent 先读的那一页,其余文档由索引列出、按需再读。",
+ /** The pinned first row: the index, and why it is pinned. */
+ indexLabel: "索引 · 每轮先读",
+ documents: "文档",
+ /** The tree's own controls: closing every folder, and what a folder row's count means. */
+ collapseAll: "全部折叠",
+ documentsInFolder: (n: number): string => `${n} 篇文档`,
+ noOtherDocuments: "还没有其他文档。新建一篇,并在索引里列出它。",
+ emptyDocument: "这篇文档还是空的。",
+ newDocument: "新建文档",
+ creating: "创建中…",
+ pathField: "路径",
+ pathPlaceholder: "decisions/2026-09-02-hire-plan.md",
+ pathHint:
+ "相对于 handbook/ 的路径,用 / 分层;每段以字母或数字开头,仅字母、数字、. _ -;省略扩展名时补 .md。",
+ pathInvalid: "路径无效:每段以字母或数字开头,仅字母、数字、. _ -,用 / 分层,最多八层。",
+ pathExists: "该文档已存在。",
+ documentCreated: "文档已创建",
+ deleteDocument: "删除文档",
+ deleteConfirm: (path: string): string =>
+ `删除 ${path}?文档会从 handbook/ 目录移除;索引里指向它的条目不会自动更新。`,
+ documentDeleted: "文档已删除",
+ loadFailed: "手册加载失败",
+ documentLoadFailed: "文档加载失败",
+ /** A row's tooltip: when the file was last written, and its size. */
+ updatedAt: (time: string, size: string): string => `更新于 ${time} · ${size}`,
+ /** Beside the editor's buttons: what the text is, and the shortcut. */
+ editorHint: "Markdown · Ctrl/⌘+S 保存",
+ },
+ },
errors: {
networkError: "网络错误,请检查连接",
modelCredentialMissing: (modelId: string) =>
@@ -3310,6 +4108,21 @@ Benchmark:
account_enabled_elsewhere: "该机器人的连接已在另一个会话中启用:先在那边停用,再在此启用。",
messaging_disable_before_clear: "先停用该渠道的连接,才能清除其凭证。",
messaging_disable_before_scan: "先停用该渠道的连接,才能重新扫码绑定。",
+ company_mode_off: "本服务器已关闭公司模式。",
+ org_not_found: "该组织已不存在。",
+ org_exists: "该组织 id 已被占用。",
+ org_invalid: "该组织的配置文件需要修复,修好前不接受改动。",
+ invalid_org_id: "组织 id 无效:2~64 位,小写字母开头,仅小写字母、数字与下划线。",
+ employee_not_found: "该 Agent 不是本组织的员工。",
+ employee_exists: "该 Agent 已是本组织的员工。",
+ calendar_event_exists: "已存在同名日程。",
+ calendar_event_not_found: "该日程已不存在。",
+ desk_unavailable: "无法打开工位会话。",
+ ticket_not_found: "该工单已不存在。",
+ ticket_invalid: "该工单文件需要修复,修好前不接受改动。",
+ ticket_session_failed: "无法发起工单会话。",
+ handbook_file_not_found: "该文档已不存在。",
+ handbook_index_required: "手册索引(README.md)不能删除。",
},
},
};
diff --git a/packages/web/src/lib/work-mode.ts b/packages/web/src/lib/work-mode.ts
new file mode 100644
index 00000000..1adb205b
--- /dev/null
+++ b/packages/web/src/lib/work-mode.ts
@@ -0,0 +1,69 @@
+/**
+ * Browser-side memory of the shell's work mode and of the organization last opened in
+ * company mode. Both are also stored server-side in the user's `ui_prefs` (`workMode`,
+ * `lastOrgKey`), which is the copy that follows the user to another browser; these mirrors
+ * exist so the first render after a reload already stands in the right mode instead of
+ * flashing development mode until the preferences arrive — the same reason `lastProjectId`
+ * is mirrored. Storage is injectable (nav-group-collapse.ts convention: vitest runs in Node
+ * with no localStorage), and every read degrades to the default on anything unexpected.
+ */
+import type { WorkMode } from "../features/company/company-nav";
+import { parseOrgKey } from "../features/company/company-nav";
+
+/** Minimal storage interface (the subset of localStorage used here); tests inject an in-memory one. */
+export interface WorkModeStorage {
+ getItem(key: string): string | null;
+ setItem(key: string, value: string): void;
+ removeItem(key: string): void;
+}
+
+export const WORK_MODE_KEY = "penguin.workMode";
+export const LAST_ORG_KEY = "penguin.lastOrgKey";
+
+/** The remembered mode; only an explicit "company" switches — anything else (absent, unrecognized, throwing storage) is development, the default. */
+export function initialWorkMode(storage?: WorkModeStorage): WorkMode {
+ try {
+ return (storage ?? localStorage).getItem(WORK_MODE_KEY) === "company" ? "company" : "dev";
+ } catch {
+ return "dev";
+ }
+}
+
+export function storeWorkMode(mode: WorkMode, storage?: WorkModeStorage): void {
+ try {
+ (storage ?? localStorage).setItem(WORK_MODE_KEY, mode);
+ } catch {
+ /* best-effort persistence (quota limits / private browsing) */
+ }
+}
+
+/** The remembered organization key, or null when nothing valid is stored. */
+export function initialLastOrgKey(storage?: WorkModeStorage): string | null {
+ try {
+ const raw = (storage ?? localStorage).getItem(LAST_ORG_KEY);
+ return parseOrgKey(raw) === null ? null : raw;
+ } catch {
+ return null;
+ }
+}
+
+export function storeLastOrgKey(key: string, storage?: WorkModeStorage): void {
+ try {
+ (storage ?? localStorage).setItem(LAST_ORG_KEY, key);
+ } catch {
+ /* best-effort persistence */
+ }
+}
+
+/**
+ * Forgets the remembered organization — the one case a mirror is dropped rather than
+ * overwritten: the organization it named was deleted, and leaving the key behind would send
+ * the next reload straight back at it.
+ */
+export function clearLastOrgKey(storage?: WorkModeStorage): void {
+ try {
+ (storage ?? localStorage).removeItem(LAST_ORG_KEY);
+ } catch {
+ /* best-effort persistence */
+ }
+}
diff --git a/packages/web/src/router.tsx b/packages/web/src/router.tsx
index 0b32ab04..e66eeb9e 100644
--- a/packages/web/src/router.tsx
+++ b/packages/web/src/router.tsx
@@ -7,6 +7,7 @@ import { BrowserRouter, Navigate, Route, Routes } from "react-router";
import { useAuth } from "./state/auth";
import { ProjectProvider } from "./state/project";
import { SessionsProvider } from "./state/sessions";
+import { CompanyProvider } from "./state/company";
import { AppLayout } from "./components/layout/app-layout";
import { LoginPage } from "./pages/login";
import { ChatPage } from "./features/chat/chat-page";
@@ -18,6 +19,14 @@ import { UsagePage } from "./features/usage/usage-page";
import { BenchmarkPage } from "./features/benchmark/benchmark-page";
import { BenchmarkDetailPage } from "./features/benchmark/benchmark-detail-page";
import { TerminalPage } from "./features/terminal/terminal-page";
+import { OrgIndexRedirect, OrgLayout } from "./features/company/org-layout";
+import { OverviewPage } from "./features/company/overview-page";
+import { OrgChartPage } from "./features/company/org-chart-page";
+import { CalendarPage } from "./features/company/calendar-page";
+import { TicketsPage } from "./features/company/tickets-page";
+import { FinancePage } from "./features/company/finance-page";
+import { ChannelView } from "./features/company/channel-view";
+import { HandbookPage } from "./features/company/handbook-page";
import { MachinesPage } from "./features/machines/machines-page";
import { PAGES } from "./lib/pages";
import type { PageEntry } from "./lib/pages";
@@ -56,7 +65,9 @@ function RequireAuth() {
return (
<ProjectProvider>
<SessionsProvider>
- <AppLayout />
+ <CompanyProvider>
+ <AppLayout />
+ </CompanyProvider>
</SessionsProvider>
</ProjectProvider>
);
@@ -102,6 +113,22 @@ export function AppRouter() {
{PAGES.map((page) => (
<Route key={page.id} path={page.path} element={renderPage(page)} />
))}
+ {/* Company mode: /org resolves to an organization (or the empty landing), and an
+ organization opens on its overview — the page that says what the whole
+ organization is doing; its channels are the sidebar's own list beside it. Both
+ fall back to /chat while company mode is unavailable (see OrgLayout). */}
+ <Route path="/org" element={<OrgIndexRedirect />} />
+ <Route path="/org/:projectId/:orgId" element={<OrgLayout />}>
+ <Route index element={<Navigate to="overview" replace />} />
+ <Route path="overview" element={<OverviewPage />} />
+ <Route path="chart" element={<OrgChartPage />} />
+ <Route path="calendar" element={<CalendarPage />} />
+ <Route path="tickets" element={<TicketsPage />} />
+ <Route path="finance" element={<FinancePage />} />
+ <Route path="handbook" element={<HandbookPage />} />
+ <Route path="channels/:channelId" element={<ChannelView />} />
+ <Route path="*" element={<Navigate to="overview" replace />} />
+ </Route>
{/* System settings and user management live in the settings dialog now (see
SettingsDialog); their old routes fall through to the catch-all. */}
<Route path="*" element={<Navigate to="/chat" replace />} />
diff --git a/packages/web/src/state/auth.tsx b/packages/web/src/state/auth.tsx
index 66c2abaf..9994be56 100644
--- a/packages/web/src/state/auth.tsx
+++ b/packages/web/src/state/auth.tsx
@@ -55,6 +55,12 @@ interface AuthContextValue {
* check and the server check can never disagree about what "too large" means.
*/
uploadLimits: UploadLimits;
+ /**
+ * Whether company mode is enabled server-wide (the admin master switch in server settings,
+ * default on). Off hides the work-mode switch for everyone and 404s every organization
+ * route; the user's own preference (`UiPrefs.companyMode`) only hides the switch for them.
+ */
+ companyMode: boolean;
login: (userId: string, password: string) => Promise<void>;
logout: () => Promise<void>;
/** Refetch /api/me (e.g. to refresh the passwordIsInitial flag after a password change). */
@@ -78,6 +84,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const [desktopMode, setDesktopMode] = useState(false);
const [sessionVia, setSessionVia] = useState<MeResponse["sessionVia"]>("password");
const [uploadLimits, setUploadLimits] = useState<UploadLimits>(DEFAULT_UPLOAD_LIMITS);
+ // Off until /api/me says otherwise: the mode switch must not flash for a server that has
+ // turned company mode off, and the default on the server side is on anyway.
+ const [companyMode, setCompanyMode] = useState(false);
// Any API returning 401 (session expired / database rebuilt) clears the current user, and
// RequireAuth redirects back to the login page.
@@ -99,6 +108,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setDesktopMode(res.desktopMode);
setSessionVia(res.sessionVia);
setUploadLimits(res.uploadLimits);
+ setCompanyMode(res.companyMode);
})
.catch((err: unknown) => {
if (cancelled) return;
@@ -127,6 +137,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setDesktopMode(me.desktopMode);
setSessionVia(me.sessionVia);
setUploadLimits(me.uploadLimits);
+ setCompanyMode(me.companyMode);
} catch {
// Login itself succeeded; keep the optimistic default.
}
@@ -149,6 +160,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setDesktopMode(res.desktopMode);
setSessionVia(res.sessionVia);
setUploadLimits(res.uploadLimits);
+ setCompanyMode(res.companyMode);
}, []);
return (
@@ -159,6 +171,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
desktopMode,
sessionVia,
uploadLimits,
+ companyMode,
login,
logout,
refresh,
diff --git a/packages/web/src/state/company.tsx b/packages/web/src/state/company.tsx
new file mode 100644
index 00000000..c698480f
--- /dev/null
+++ b/packages/web/src/state/company.tsx
@@ -0,0 +1,729 @@
+/**
+ * Company-mode shell state: whether the mode is available at all, which mode the shell is
+ * in, which organization is open, the organizations this user can reach, the open
+ * organization's channels, and the live counters their badges show.
+ *
+ * Availability is two switches ANDed: the server's master switch (`MeResponse.companyMode`,
+ * read through the auth context) and the user's own (`UiPrefs.companyMode`, default on). Off
+ * on either side, the shell renders no mode switch and every `/org` route falls back to a
+ * Session's own page; organizations keep running regardless — the personal switch only hides the
+ * user's own view of them.
+ *
+ * Entering company mode is also where the shell says the mode is a beta: the first switch
+ * into it in a browser raises the notice once (features/company/beta-badge.tsx keeps the
+ * flag), which is why `setWorkMode` is the single handler both mode switches call.
+ *
+ * The chosen mode and the organization last opened are user preferences (`workMode`,
+ * `lastOrgKey` in ui_prefs) mirrored into localStorage (lib/work-mode.ts) so a reload stands
+ * in the right mode before the preferences arrive; the stored copy wins once it does. Both
+ * the open and the remembered organization are forgotten once a complete listing comes back
+ * without them: a deleted organization that keeps the shell aimed at it costs a broken
+ * sidebar on every later visit.
+ *
+ * The open ticket lives here too. A ticket's detail is a dialog opened in place from every
+ * company surface — the board, the finance ledger, the overview's inbox, a channel's ticket
+ * reference — so which ticket is open is shell state rather than one page's, and the single
+ * host (features/company/org-layout.tsx) renders whatever this says. Following a parent or a
+ * child inside the dialog pushes the ticket left behind onto a stack, which is what the
+ * dialog's back control pops.
+ *
+ * Company events ride the same user-level event stream the session list consumes
+ * (state/sessions.tsx forwards them through `publishCompanyEvent`): the store keeps the
+ * channel counters of the open organization in step and bumps a version per event family,
+ * which the pages watch to refetch — the query routes carry the durable state, the events only say
+ * that it moved.
+ *
+ * State lives in a zustand vanilla store (one instance per Provider mount) like the Project
+ * and Session stores; the Provider is the lifecycle component that hydrates it.
+ */
+import { createContext, useContext, useEffect, useMemo, useRef, useState } from "react";
+import type { ReactNode } from "react";
+import type {
+ CompanyServerEvent,
+ OrgChannelItem,
+ OrgChartResponse,
+ OrgSessionsResponse,
+ OrganizationSummary,
+ ServerEvent,
+} from "@prismshadow/penguin-server/api";
+import { useStore } from "zustand/react";
+import { createStore } from "zustand/vanilla";
+import * as api from "../api/endpoints";
+import { apiErrorText } from "../lib/api-error";
+import { S } from "../lib/strings";
+import { toastAttention } from "../components/ui/toast";
+import { markBetaNoticeShown, shouldShowBetaNotice } from "../features/company/beta-badge";
+import { channelBadgeCounts } from "../features/company/channel-list";
+import { orgKey, parseOrgKey } from "../features/company/company-nav";
+import type { WorkMode } from "../features/company/company-nav";
+import {
+ clearLastOrgKey,
+ initialLastOrgKey,
+ initialWorkMode,
+ storeLastOrgKey,
+ storeWorkMode,
+} from "../lib/work-mode";
+import { useAuth } from "./auth";
+import { useProject } from "./project";
+
+/** The event families the organization scheduler publishes on the user channel. */
+export function isCompanyEvent(ev: ServerEvent): ev is CompanyServerEvent {
+ return (
+ ev.type === "org_run" ||
+ ev.type === "org_channel" ||
+ ev.type === "org_ticket" ||
+ ev.type === "org_budget"
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Event fan-out: the one SSE connection (state/sessions.tsx) publishes here, and the store
+// plus any mounted page subscribe. Module level, because the connection outlives every page.
+// ---------------------------------------------------------------------------
+
+type CompanyEventListener = (ev: CompanyServerEvent) => void;
+const listeners = new Set<CompanyEventListener>();
+
+export function publishCompanyEvent(ev: CompanyServerEvent): void {
+ for (const listener of listeners) listener(ev);
+}
+
+export function subscribeCompanyEvents(listener: CompanyEventListener): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+/** Subscribes a component to company events for its mounted lifetime; the latest handler is always the one called. */
+export function useCompanyEvents(handler: CompanyEventListener): void {
+ const ref = useRef(handler);
+ ref.current = handler;
+ useEffect(() => subscribeCompanyEvents((ev) => ref.current(ev)), []);
+}
+
+/** Which ticket the detail dialog is showing; a ticket is always read inside one organization. */
+export interface TicketDialogTarget {
+ projectId: string;
+ orgId: string;
+ ticketId: string;
+}
+
+/** Version counters, one per event family: a page refetches when the one it depends on moves. */
+export interface CompanyVersions {
+ /** The organization list (an org's summary counts changed: a budget pause, a run). */
+ orgs: number;
+ /** A new message landed in one of the organization's channels. */
+ messages: number;
+ tickets: number;
+ /** A desk or ticket Session was opened by the scheduler. */
+ runs: number;
+ budget: number;
+}
+
+interface CompanyStoreState {
+ /** The user's own switch (`UiPrefs.companyMode`); on until the preferences say otherwise. */
+ personalEnabled: boolean;
+ /** The preferences have been read once (before that the mirrors below stand in). */
+ prefsLoaded: boolean;
+ workMode: WorkMode;
+ /** `<projectId>/<orgId>` of the organization last opened, or null. */
+ lastOrgKey: string | null;
+ /** The organization the shell is currently inside (set by the org routes), or null elsewhere. */
+ currentOrgKey: string | null;
+ /** Every organization of every Project the user can reach. */
+ organizations: OrganizationSummary[];
+ orgsLoading: boolean;
+ orgsLoaded: boolean;
+ /**
+ * At least one Project's listing failed in the last read, so `organizations` is missing
+ * whatever that Project holds. An absent organization then means "not listed this time",
+ * not "gone", which is what keeps a transient failure from forgetting the open one.
+ */
+ orgsPartial: boolean;
+ /**
+ * The open organization's channels, as `GET /channels` last answered them — the sidebar's
+ * list, the rail's rows and the channel view all read this one copy. Null before the first
+ * listing of the organization now open.
+ */
+ channels: OrgChannelItem[] | null;
+ /** The last listing attempt's failure, kept beside whatever the list still holds. */
+ channelsError: string | null;
+ /** When each channel was last marked read here, so a listing that left earlier cannot resurrect its badge. */
+ channelReadAt: ReadonlyMap<string, number>;
+ /** Unread messages waiting in the open organization's channels, and how many of those name the user. */
+ channelUnread: number;
+ channelMentions: number;
+ /** Desk and ticket Sessions per organization of the current Project, keyed by org key. */
+ orgSessions: ReadonlyMap<string, OrgSessionsResponse>;
+ /**
+ * The open organization's chart — the sidebar's 工位 group is one row per EMPLOYEE, and
+ * this is the only listing that holds employees whose desk has never been opened. Null
+ * before the first read of the organization now open.
+ */
+ orgChart: OrgChartResponse | null;
+ /** The last chart read's failure, kept beside whatever the roster still holds. */
+ orgChartError: string | null;
+ /** The ticket whose detail dialog is open, from wherever it was opened; null when none is. */
+ ticketDialog: TicketDialogTarget | null;
+ /**
+ * The tickets the open one was reached from, oldest first — one entry per parent or child
+ * followed inside the dialog. Ids only: they name tickets of the open organization.
+ */
+ ticketStack: readonly string[];
+ versions: CompanyVersions;
+
+ setWorkMode: (mode: WorkMode) => void;
+ setPersonalEnabled: (enabled: boolean) => void;
+ setCurrentOrg: (key: string | null) => void;
+ reloadChannels: (projectId: string, orgId: string) => Promise<void>;
+ markChannelRead: (channelId: string) => void;
+ reloadOrganizations: (projectIds: readonly string[]) => Promise<void>;
+ forgetMissingOrganizations: () => void;
+ reloadOrgSessions: (projectId: string) => Promise<void>;
+ reloadOrgChart: (projectId: string, orgId: string) => Promise<void>;
+ openTicket: (projectId: string, orgId: string, ticketId: string) => void;
+ closeTicket: () => void;
+ backTicket: () => void;
+ ticketsChanged: () => void;
+ applyCompanyEvent: (ev: CompanyServerEvent, userId: string | null) => void;
+}
+
+/** The two badge numbers of a channel listing (channel-list.ts), in the shape the store stores them. */
+function counters(channels: readonly OrgChannelItem[]): {
+ channelUnread: number;
+ channelMentions: number;
+} {
+ const { unread, mentions } = channelBadgeCounts(channels);
+ return { channelUnread: unread, channelMentions: mentions };
+}
+
+/**
+ * Builds one Provider's store. Exported as a test seam: the package's vitest runs in Node
+ * with no DOM, so the event routing below is exercised against the store directly.
+ */
+export function createCompanyStore() {
+ return createStore<CompanyStoreState>((set, get) => ({
+ personalEnabled: true,
+ prefsLoaded: false,
+ workMode: initialWorkMode(),
+ lastOrgKey: initialLastOrgKey(),
+ currentOrgKey: null,
+ organizations: [],
+ orgsLoading: false,
+ orgsLoaded: false,
+ orgsPartial: false,
+ channels: null,
+ channelsError: null,
+ channelReadAt: new Map(),
+ channelUnread: 0,
+ channelMentions: 0,
+ orgSessions: new Map(),
+ orgChart: null,
+ orgChartError: null,
+ ticketDialog: null,
+ ticketStack: [],
+ versions: { orgs: 0, messages: 0, tickets: 0, runs: 0, budget: 0 },
+
+ setWorkMode: (mode) => {
+ if (mode === get().workMode) return;
+ storeWorkMode(mode);
+ set({ workMode: mode });
+ // The mode is a beta, and this is the one place a person enters it: both switches and
+ // the `/org` landing come through here, and hydrating the stored preference does not
+ // (it sets the field directly), so the notice follows a deliberate move and never a
+ // reload. Once per browser — the flag is the only state it keeps.
+ if (mode === "company" && shouldShowBetaNotice()) {
+ markBetaNoticeShown();
+ toastAttention(S.company.betaNotice);
+ }
+ // Leaving company mode is what drops the open organization — not leaving its routes.
+ // A desk or ticket conversation renders at `/chat/:sessionId` with the company sidebar
+ // around it, and that sidebar lists this organization's channels and desks.
+ if (mode !== "company") get().setCurrentOrg(null);
+ // Server-side copy is best-effort: a lost write only costs the choice on another browser.
+ void api.putPrefs({ workMode: mode }).catch(() => undefined);
+ },
+
+ setPersonalEnabled: (enabled) => {
+ set({ personalEnabled: enabled });
+ // Hiding company mode hides its shell with it (see setWorkMode).
+ if (!enabled) get().setCurrentOrg(null);
+ void api.putPrefs({ companyMode: enabled }).catch(() => undefined);
+ },
+
+ setCurrentOrg: (key) => {
+ const prev = get();
+ if (key === prev.currentOrgKey) return;
+ // Leaving one organization for another drops its channels and their counters: both
+ // belong to the organization they were read for, and so does an open ticket.
+ set({
+ currentOrgKey: key,
+ channels: null,
+ channelsError: null,
+ channelReadAt: new Map(),
+ channelUnread: 0,
+ channelMentions: 0,
+ orgChart: null,
+ orgChartError: null,
+ ticketDialog: null,
+ ticketStack: [],
+ });
+ if (key === null || key === prev.lastOrgKey) return;
+ storeLastOrgKey(key);
+ set({ lastOrgKey: key });
+ void api.putPrefs({ lastOrgKey: key }).catch(() => undefined);
+ },
+
+ /**
+ * Re-reads the open organization's channels. A response for an organization the shell has
+ * since left is dropped, and a channel marked read after the request went out keeps its
+ * local zero: the server's read cursor may not have been written yet when the listing was
+ * computed, and a badge that comes back from the dead reads as a bug.
+ */
+ reloadChannels: async (projectId, orgId) => {
+ const key = orgKey(projectId, orgId);
+ const startedAt = Date.now();
+ try {
+ const res = await api.listOrgChannels(projectId, orgId);
+ const state = get();
+ if (state.currentOrgKey !== key) return;
+ const channels = res.channels.map((c) =>
+ (state.channelReadAt.get(c.channelId) ?? 0) >= startedAt
+ ? { ...c, unread: 0, mentionsMe: 0 }
+ : c,
+ );
+ set({ channels, channelsError: null, ...counters(channels) });
+ } catch (e) {
+ if (get().currentOrgKey === key) set({ channelsError: apiErrorText(e) });
+ }
+ },
+
+ /** The reader reached the end of a channel: its badge clears here before the server confirms. */
+ markChannelRead: (channelId) => {
+ const state = get();
+ const readAt = new Map(state.channelReadAt);
+ readAt.set(channelId, Date.now());
+ const channels =
+ state.channels === null
+ ? null
+ : state.channels.map((c) =>
+ c.channelId === channelId ? { ...c, unread: 0, mentionsMe: 0 } : c,
+ );
+ set({
+ channelReadAt: readAt,
+ channels,
+ ...(channels === null ? {} : counters(channels)),
+ });
+ },
+
+ reloadOrganizations: async (projectIds) => {
+ set({ orgsLoading: true });
+ try {
+ const lists = await Promise.all(
+ projectIds.map((projectId) =>
+ api
+ .listOrganizations(projectId)
+ .then((res) => res.organizations)
+ // One Project's failure (lost access, a transient error) must not hide the
+ // rest — but it is recorded, since the shortened list is not evidence that
+ // anything was deleted (forgetMissingOrganizations).
+ .catch(() => null),
+ ),
+ );
+ set({
+ organizations: lists.filter((list) => list !== null).flat(),
+ orgsLoaded: true,
+ orgsPartial: lists.some((list) => list === null),
+ });
+ } finally {
+ set({ orgsLoading: false });
+ }
+ },
+
+ /**
+ * Drops the open and the remembered organization when the settled list no longer holds
+ * them — a deletion, or access lost. Neither key is a cache the shell can afford to keep
+ * stale: `currentOrgKey` is what the channel listing and the roster are fetched for (a
+ * deleted organization answers 404 and the sidebar shows a load failure), and
+ * `lastOrgKey` is where `/org` lands, so a stale one sends every later visit at an
+ * organization that is gone. The remembered key is cleared in all three places it lives:
+ * the store, the localStorage mirror and the server preference — written as an empty
+ * string, which `parseOrgKey` reads as none (`UiPrefs.lastOrgKey` is a string).
+ *
+ * A partial list is not evidence: one Project's listing failing would otherwise forget an
+ * organization that is merely unreachable this minute.
+ */
+ forgetMissingOrganizations: () => {
+ const state = get();
+ if (!state.orgsLoaded || state.orgsPartial) return;
+ const known = (key: string | null): boolean => {
+ const parsed = parseOrgKey(key);
+ if (parsed === null) return false;
+ return state.organizations.some(
+ (o) => o.projectId === parsed.projectId && o.orgId === parsed.orgId,
+ );
+ };
+ if (state.currentOrgKey !== null && !known(state.currentOrgKey)) {
+ get().setCurrentOrg(null);
+ }
+ if (get().lastOrgKey !== null && !known(get().lastOrgKey)) {
+ clearLastOrgKey();
+ set({ lastOrgKey: null });
+ void api.putPrefs({ lastOrgKey: "" }).catch(() => undefined);
+ }
+ },
+
+ reloadOrgSessions: async (projectId) => {
+ const orgs = get().organizations.filter((o) => o.projectId === projectId);
+ const entries = await Promise.all(
+ orgs.map(async (o) => {
+ try {
+ return [
+ orgKey(o.projectId, o.orgId),
+ await api.getOrgSessions(o.projectId, o.orgId),
+ ] as const;
+ } catch {
+ return null;
+ }
+ }),
+ );
+ const next = new Map<string, OrgSessionsResponse>();
+ for (const entry of entries) if (entry !== null) next.set(entry[0], entry[1]);
+ set({ orgSessions: next });
+ },
+
+ /**
+ * Re-reads the open organization's chart (the 工位 group's roster). A response for an
+ * organization the shell has since left is dropped, and a failure leaves whatever the
+ * group already shows: the roster changes only when someone hires or offboards, so a
+ * stale list is a better answer than an empty one.
+ */
+ reloadOrgChart: async (projectId, orgId) => {
+ const key = orgKey(projectId, orgId);
+ try {
+ const chart = await api.getOrgChart(projectId, orgId);
+ if (get().currentOrgKey === key) set({ orgChart: chart, orgChartError: null });
+ } catch (e) {
+ if (get().currentOrgKey === key) set({ orgChartError: apiErrorText(e) });
+ }
+ },
+
+ /**
+ * Opens a ticket's detail dialog. Another ticket of the organization already on screen is
+ * pushed onto the back stack — that is a parent or a child followed from inside the dialog,
+ * and the reader has to be able to come back — while a ticket of another organization, or
+ * the first one opened, starts a fresh stack. Re-opening the ticket already shown does
+ * nothing, so a deep link the page has just written into its own query cannot stack a
+ * ticket on top of itself.
+ */
+ openTicket: (projectId, orgId, ticketId) => {
+ const open = get().ticketDialog;
+ const target = { projectId, orgId, ticketId };
+ if (open === null || open.projectId !== projectId || open.orgId !== orgId) {
+ set({ ticketDialog: target, ticketStack: [] });
+ return;
+ }
+ if (open.ticketId === ticketId) return;
+ set({ ticketDialog: target, ticketStack: [...get().ticketStack, open.ticketId] });
+ },
+
+ closeTicket: () => {
+ if (get().ticketDialog === null) return;
+ set({ ticketDialog: null, ticketStack: [] });
+ },
+
+ /** Back to the ticket this one was opened from; nothing to do with an empty stack. */
+ backTicket: () => {
+ const { ticketDialog, ticketStack } = get();
+ const previous = ticketStack[ticketStack.length - 1];
+ if (ticketDialog === null || previous === undefined) return;
+ set({
+ ticketDialog: { ...ticketDialog, ticketId: previous },
+ ticketStack: ticketStack.slice(0, -1),
+ });
+ },
+
+ /**
+ * A ticket was written from this browser (the dialog's saves, the board's moves). The
+ * writer's own request carries the change back to it alone, so the version the other
+ * surfaces watch is bumped here exactly as the scheduler's event would bump it — the board,
+ * the finance ledger and the organization summaries refetch off one signal instead of each
+ * writer reloading its neighbours by hand.
+ */
+ ticketsChanged: () => {
+ const versions = get().versions;
+ set({ versions: { ...versions, tickets: versions.tickets + 1, orgs: versions.orgs + 1 } });
+ },
+
+ applyCompanyEvent: (ev, userId) => {
+ const state = get();
+ const key = orgKey(ev.projectId, ev.orgId);
+ const versions = { ...state.versions };
+ if (ev.type === "org_run") {
+ versions.runs += 1;
+ versions.orgs += 1;
+ } else if (ev.type === "org_ticket") {
+ versions.tickets += 1;
+ versions.orgs += 1;
+ } else if (ev.type === "org_budget") {
+ versions.budget += 1;
+ versions.orgs += 1;
+ } else {
+ versions.messages += 1;
+ // The open organization's counters move with the channel the message landed in; a
+ // message the user sent themselves is read by definition, and a channel the user is
+ // not in is waiting for nobody. `mentionsMe` counts the user's own principal only —
+ // the same rule the server's listing applies, so the optimistic bump and the refresh
+ // that follows it agree.
+ const channels = state.channels;
+ if (
+ key === state.currentOrgKey &&
+ channels !== null &&
+ ev.message.sender !== `user:${userId ?? ""}`
+ ) {
+ const addressed = ev.message.mentions.includes(`user:${userId ?? ""}`);
+ const next = channels.map((c) =>
+ c.channelId === ev.channelId && c.isMember
+ ? {
+ ...c,
+ unread: c.unread + 1,
+ mentionsMe: c.mentionsMe + (addressed ? 1 : 0),
+ lastMessageAt: ev.message.time,
+ }
+ : c,
+ );
+ set({ channels: next, ...counters(next) });
+ }
+ }
+ set({ versions });
+ },
+ }));
+}
+
+export type CompanyStore = ReturnType<typeof createCompanyStore>;
+
+interface CompanyContextValue {
+ /** The server's master switch. */
+ serverEnabled: boolean;
+ /** The user's own switch. */
+ personalEnabled: boolean;
+ /** Both switches on: the mode switch renders and `/org` routes resolve. */
+ available: boolean;
+ /** The effective mode: the chosen one while company mode is available, development otherwise. */
+ workMode: WorkMode;
+ setWorkMode: (mode: WorkMode) => void;
+ setPersonalEnabled: (enabled: boolean) => void;
+ organizations: OrganizationSummary[];
+ orgsLoading: boolean;
+ orgsLoaded: boolean;
+ currentOrgKey: string | null;
+ /** The summary of the open organization (or, outside its routes, of the one last opened), when the list holds it. */
+ currentOrg: OrganizationSummary | null;
+ lastOrgKey: string | null;
+ setCurrentOrg: (key: string | null) => void;
+ /** The open organization's channels; null until the first listing arrives. */
+ channels: OrgChannelItem[] | null;
+ channelsError: string | null;
+ /** Unread and @me summed over the channels the user belongs to — the sidebar's and the rail's badges. */
+ channelUnread: number;
+ channelMentions: number;
+ reloadChannels: () => Promise<void>;
+ markChannelRead: (channelId: string) => void;
+ /** Desk and ticket Sessions of every organization of the current Project, keyed by org key. */
+ orgSessions: ReadonlyMap<string, OrgSessionsResponse>;
+ /** The open organization's employees, in chart order; null until the first read. */
+ orgChart: OrgChartResponse | null;
+ orgChartError: string | null;
+ reloadOrgChart: () => Promise<void>;
+ /** The ticket the detail dialog is showing; null when it is closed. */
+ ticketDialog: TicketDialogTarget | null;
+ /** How many tickets the dialog can go back through (the parents and children followed inside it). */
+ ticketBackDepth: number;
+ openTicket: (projectId: string, orgId: string, ticketId: string) => void;
+ closeTicket: () => void;
+ backTicket: () => void;
+ /** Say that a ticket was written here, so every surface that lists tickets refetches. */
+ ticketsChanged: () => void;
+ versions: CompanyVersions;
+ reloadOrganizations: () => Promise<void>;
+ reloadOrgSessions: () => Promise<void>;
+}
+
+const CompanyContext = createContext<CompanyContextValue | null>(null);
+
+export function CompanyProvider({ children }: { children: ReactNode }) {
+ const { user, companyMode: serverEnabled } = useAuth();
+ const { projects, currentProject } = useProject();
+ const [store] = useState(createCompanyStore);
+ const state = useStore(store);
+ const userId = user?.userId ?? null;
+ const currentProjectId = currentProject?.projectId ?? null;
+ const projectIdsKey = projects.map((p) => p.projectId).join(",");
+
+ // Preferences: the stored switch, mode and last organization win over the localStorage
+ // mirrors once they arrive. Read once per signed-in user.
+ useEffect(() => {
+ if (userId === null) return;
+ let cancelled = false;
+ void api
+ .getPrefs()
+ .then((res) => {
+ if (cancelled) return;
+ const prefs = res.prefs;
+ const patch: Partial<CompanyStoreState> = { prefsLoaded: true };
+ if (prefs.companyMode === false) patch.personalEnabled = false;
+ if (prefs.workMode === "company" || prefs.workMode === "dev") {
+ patch.workMode = prefs.workMode;
+ storeWorkMode(prefs.workMode);
+ }
+ if (typeof prefs.lastOrgKey === "string" && parseOrgKey(prefs.lastOrgKey) !== null) {
+ patch.lastOrgKey = prefs.lastOrgKey;
+ storeLastOrgKey(prefs.lastOrgKey);
+ }
+ store.setState(patch);
+ })
+ .catch(() => {
+ // Unreachable preferences leave the mirrors standing; nothing here is critical.
+ if (!cancelled) store.setState({ prefsLoaded: true });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [store, userId]);
+
+ // The organization list spans every Project the user can reach; it refreshes when the
+ // Project set changes and whenever an event says a summary moved.
+ const { orgs: orgsVersion, runs: runsVersion, tickets: ticketsVersion } = state.versions;
+ useEffect(() => {
+ if (!serverEnabled || projectIdsKey === "") {
+ store.setState({
+ organizations: [],
+ orgsLoaded: false,
+ orgsPartial: false,
+ orgSessions: new Map(),
+ });
+ return;
+ }
+ void store.getState().reloadOrganizations(projectIdsKey.split(","));
+ }, [store, serverEnabled, projectIdsKey, orgsVersion]);
+
+ const { orgsLoaded, orgsPartial } = state;
+ const orgListKey = state.organizations.map((o) => orgKey(o.projectId, o.orgId)).join(",");
+
+ // A deleted organization must not leave the shell aimed at it. The list is the only place
+ // that knows: once it has settled, the open key and the remembered one are checked against
+ // it, so the sidebar drops to its no-organization shape instead of failing to load the
+ // channels of something that is gone.
+ useEffect(() => {
+ store.getState().forgetMissingOrganizations();
+ }, [store, orgsLoaded, orgsPartial, orgListKey]);
+
+ // The current Project's desk and ticket Sessions: the company sidebar lists them, and the
+ // development sidebar folds them into an "organization" folder.
+ // Keyed on the list's identity as well: a newly created organization has no sessions entry
+ // until its first event otherwise.
+ useEffect(() => {
+ if (!serverEnabled || currentProjectId === null || !orgsLoaded) return;
+ void store.getState().reloadOrgSessions(currentProjectId);
+ }, [store, serverEnabled, currentProjectId, orgsLoaded, orgListKey, runsVersion, ticketsVersion]);
+
+ // The open organization's channels: the sidebar's list and every badge on it. Re-read when
+ // the organization changes and whenever a message event says one of its counters moved —
+ // the listing carries the server's read cursors, which no client-side bump can know.
+ const { currentOrgKey, versions } = state;
+ const messageVersion = versions.messages;
+ useEffect(() => {
+ const open = parseOrgKey(currentOrgKey);
+ if (!serverEnabled || open === null) return;
+ void store.getState().reloadChannels(open.projectId, open.orgId);
+ }, [store, serverEnabled, currentOrgKey, messageVersion]);
+
+ // The open organization's roster: the sidebar's 工位 group has a row per employee, desk or
+ // no desk. Re-read when the organization changes and when a run or a personnel change
+ // (both bump `orgs`) says the chart moved.
+ useEffect(() => {
+ const open = parseOrgKey(currentOrgKey);
+ if (!serverEnabled || open === null) return;
+ void store.getState().reloadOrgChart(open.projectId, open.orgId);
+ }, [store, serverEnabled, currentOrgKey, orgsVersion]);
+
+ // In company mode the shell always has a current organization: the one its sidebar names.
+ // The organization routes announce it, but a desk or ticket conversation lives at
+ // `/chat/:sessionId` — reload there and no route ever would, which used to leave the
+ // channel list on a skeleton and the 工位 group without its roster. The organization last
+ // opened is exactly what the sidebar is already showing, so the shell adopts it.
+ const { workMode, personalEnabled, lastOrgKey } = state;
+ useEffect(() => {
+ if (!serverEnabled || !personalEnabled || workMode !== "company") return;
+ if (currentOrgKey !== null || lastOrgKey === null) return;
+ store.getState().setCurrentOrg(lastOrgKey);
+ }, [store, serverEnabled, personalEnabled, workMode, currentOrgKey, lastOrgKey]);
+
+ useEffect(
+ () => subscribeCompanyEvents((ev) => store.getState().applyCompanyEvent(ev, userId)),
+ [store, userId],
+ );
+
+ const value = useMemo<CompanyContextValue>(() => {
+ const available = serverEnabled && state.personalEnabled;
+ const shownKey = state.currentOrgKey ?? state.lastOrgKey;
+ const shown = parseOrgKey(shownKey);
+ const currentOrg =
+ shown === null
+ ? null
+ : (state.organizations.find(
+ (o) => o.projectId === shown.projectId && o.orgId === shown.orgId,
+ ) ?? null);
+ return {
+ serverEnabled,
+ personalEnabled: state.personalEnabled,
+ available,
+ workMode: available ? state.workMode : "dev",
+ setWorkMode: state.setWorkMode,
+ setPersonalEnabled: state.setPersonalEnabled,
+ organizations: state.organizations,
+ orgsLoading: state.orgsLoading,
+ orgsLoaded: state.orgsLoaded,
+ currentOrgKey: state.currentOrgKey,
+ currentOrg,
+ lastOrgKey: state.lastOrgKey,
+ setCurrentOrg: state.setCurrentOrg,
+ channels: state.channels,
+ channelsError: state.channelsError,
+ channelUnread: state.channelUnread,
+ channelMentions: state.channelMentions,
+ reloadChannels: () => {
+ const open = parseOrgKey(state.currentOrgKey);
+ return open === null ? Promise.resolve() : state.reloadChannels(open.projectId, open.orgId);
+ },
+ markChannelRead: state.markChannelRead,
+ orgSessions: state.orgSessions,
+ orgChart: state.orgChart,
+ orgChartError: state.orgChartError,
+ reloadOrgChart: () => {
+ const open = parseOrgKey(state.currentOrgKey);
+ return open === null ? Promise.resolve() : state.reloadOrgChart(open.projectId, open.orgId);
+ },
+ ticketDialog: state.ticketDialog,
+ ticketBackDepth: state.ticketStack.length,
+ openTicket: state.openTicket,
+ closeTicket: state.closeTicket,
+ backTicket: state.backTicket,
+ ticketsChanged: state.ticketsChanged,
+ versions: state.versions,
+ reloadOrganizations: () =>
+ state.reloadOrganizations(projectIdsKey === "" ? [] : projectIdsKey.split(",")),
+ reloadOrgSessions: () =>
+ currentProjectId === null ? Promise.resolve() : state.reloadOrgSessions(currentProjectId),
+ };
+ }, [state, serverEnabled, projectIdsKey, currentProjectId]);
+
+ return <CompanyContext.Provider value={value}>{children}</CompanyContext.Provider>;
+}
+
+export function useCompany(): CompanyContextValue {
+ const ctx = useContext(CompanyContext);
+ if (!ctx) throw new Error("useCompany must be used within a CompanyProvider");
+ return ctx;
+}
diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsx
index 03e1164f..1e3f503e 100644
--- a/packages/web/src/state/sessions.tsx
+++ b/packages/web/src/state/sessions.tsx
@@ -37,6 +37,7 @@ import { useStore } from "zustand/react";
import { createStore } from "zustand/vanilla";
import * as api from "../api/endpoints";
import { openUserEvents } from "../api/sse";
+import { isCompanyEvent, publishCompanyEvent } from "./company";
import {
FOLDER_CATEGORIES,
SIDEBAR_PAGE_SIZE,
@@ -649,6 +650,19 @@ export function applyUserEvent(
void store.getState().reload();
return;
}
+ // Company-mode notifications fan out to the company store and any mounted organization page
+ // (state/company.tsx); a work run additionally opened a desk or ticket Session this list has
+ // not seen, so it refreshes like a schedule firing does.
+ if (isCompanyEvent(ev)) {
+ publishCompanyEvent(ev);
+ if (ev.type === "org_run" && ev.projectId === store.getState().projectId) {
+ void store.getState().reload();
+ }
+ return;
+ }
+ // A scheduled task firing may have created a new Session (new-session mode); reload the list
+ // so it appears immediately. schedule_queued doesn't change the list (the target Session
+ // already exists), so it is ignored, as is every other Session-scoped event.
// Either schedule event moves a task's state — nextFireAt, lastFiredAt, the queued flag, or a
// one-off going done — so the conversation's schedule list is stale from here. The store
// decides for itself whether the agent is the one on screen.
@@ -790,3 +804,17 @@ export function useSessions(): SessionsContextValue {
if (!ctx) throw new Error("useSessions must be used within a SessionsProvider");
return ctx;
}
+
+/**
+ * Every loaded Session's run status by id — the user event channel's view of it, which is the
+ * only one that reports a run ENDING. Surfaces built on a server-side snapshot (company mode's
+ * desk and ticket rows, the org chart's state dots, the overview's employee counts) read this
+ * first and keep their snapshot for the rows this list has not loaded: their snapshots are
+ * re-read on organization events, and no event announces that a run finished.
+ *
+ * Memoized on the rows, so a consumer re-shapes only when a status (or the list) actually moves.
+ */
+export function useLiveSessionStatuses(): ReadonlyMap<string, SessionStatus> {
+ const { sessions } = useSessions();
+ return useMemo(() => new Map(sessions.map((s) => [s.sessionId, s.status])), [sessions]);
+}
diff --git a/packages/web/src/styles.css b/packages/web/src/styles.css
index 0ccc53d1..7cbdbe6f 100644
--- a/packages/web/src/styles.css
+++ b/packages/web/src/styles.css
@@ -776,6 +776,56 @@ html.dark .shiki span {
@apply border border-gray-200 px-2 py-1 text-sm dark:border-gray-800;
}
+/* A channel message body (features/company/channel-view.tsx): the same Markdown typography, one
+ size tighter. A message is a line in a stream, not a document — its blocks sit closer, its
+ headings step down towards body size, and the first and last block give up their outer margins
+ so a one-paragraph message occupies exactly its row. Used together with .md-body, after it, so
+ these win at equal specificity. */
+.md-compact :is(p, ul, ol, pre, blockquote, table) {
+ margin: 0.25rem 0;
+}
+.md-compact li {
+ margin: 0.125rem 0;
+}
+.md-compact p {
+ line-height: 1.6;
+}
+.md-compact :is(h1, h2, h3, h4) {
+ margin: 0.5rem 0 0.25rem;
+}
+.md-compact h1 {
+ font-size: 1.0625rem;
+}
+.md-compact h2 {
+ font-size: 1rem;
+}
+.md-compact h3 {
+ font-size: 0.9375rem;
+}
+.md-compact h4 {
+ font-size: 0.875rem;
+}
+.md-compact > :first-child {
+ margin-top: 0;
+}
+.md-compact > :last-child {
+ margin-bottom: 0;
+}
+
+/* ---------- Channel message bubble (features/company/channel-view.tsx) ---------- */
+
+/* A bubble's own surface is the grey the shared Markdown rules give inline code and table
+ rules, so inside a bubble those marks are printed on their own colour and disappear. One
+ step deeper puts them back, and reads on both bubble tints in both themes. Fenced blocks
+ need nothing: `.md-body pre` carries a border and its own lighter/darker fill, and the code
+ inside it is transparent. The `:not(pre) >` shape is what keeps this off them. */
+.channel-bubble :not(pre) > code {
+ @apply bg-gray-200 dark:bg-gray-700;
+}
+.channel-bubble :is(th, td) {
+ @apply border-gray-300 dark:border-gray-700;
+}
+
/* ---------- KaTeX (math rendering; see lib/markdown-plugins.ts) ---------- */
/* KaTeX's own fonts carry no CJK glyphs, and it tags every CJK run `cjk_fallback` while leaving
diff --git a/packages/web/test/budget-input.test.ts b/packages/web/test/budget-input.test.ts
new file mode 100644
index 00000000..1bc3e13c
--- /dev/null
+++ b/packages/web/test/budget-input.test.ts
@@ -0,0 +1,90 @@
+/**
+ * budget-input.ts unit tests: a budget is a monthly cap stored in USD, and the box that sets
+ * it speaks whichever currency the reader picked — so what was typed has to reach the server
+ * as USD, and what the server holds has to come back into the box as the reader's currency.
+ */
+import { describe, expect, it } from "vitest";
+import {
+ fromStoredUsd,
+ isBudgetText,
+ toStoredUsd,
+ unitLabel,
+} from "../src/features/company/budget-input";
+import { zh } from "../src/lib/strings";
+import { en } from "../src/lib/strings-en";
+
+describe("toStoredUsd", () => {
+ it("keeps a USD box as it was typed", () => {
+ expect(toStoredUsd("100", "USD")).toBe(100);
+ expect(toStoredUsd(" 12.5 ", "USD")).toBe(12.5);
+ });
+
+ it("divides a CNY box by the fixed rate and rounds to cents", () => {
+ expect(toStoredUsd("700", "CNY")).toBe(100);
+ expect(toStoredUsd("100", "CNY")).toBe(14.29);
+ });
+
+ it("reads an empty box as unbounded", () => {
+ expect(toStoredUsd("", "USD")).toBeNull();
+ expect(toStoredUsd(" ", "CNY")).toBeNull();
+ });
+
+ it("keeps zero as a real budget rather than unbounded", () => {
+ expect(toStoredUsd("0", "USD")).toBe(0);
+ expect(toStoredUsd("0", "CNY")).toBe(0);
+ });
+
+ it("refuses what is not a non-negative number (the callers validate first)", () => {
+ expect(toStoredUsd("abc", "USD")).toBeNull();
+ expect(toStoredUsd("-5", "USD")).toBeNull();
+ });
+});
+
+describe("fromStoredUsd", () => {
+ it("starts the box empty when there is no budget", () => {
+ expect(fromStoredUsd(undefined, "USD")).toBe("");
+ expect(fromStoredUsd(null, "CNY")).toBe("");
+ });
+
+ it("fills a USD box with the stored amount and a CNY box with the converted one", () => {
+ expect(fromStoredUsd(100, "USD")).toBe("100");
+ expect(fromStoredUsd(100, "CNY")).toBe("700");
+ expect(fromStoredUsd(0, "USD")).toBe("0");
+ });
+
+ it("round-trips a USD box exactly", () => {
+ for (const text of ["0", "30", "100", "12.5"]) {
+ expect(fromStoredUsd(toStoredUsd(text, "USD"), "USD")).toBe(text);
+ }
+ });
+
+ it("shows a CNY box what the cent-rounded amount actually converts back to", () => {
+ // 100 CNY stores as $14.29, which is 100.03 CNY — the field says so under itself rather
+ // than pretending the fixed rate is lossless.
+ expect(fromStoredUsd(14.29, "CNY")).toBe("100.03");
+ });
+});
+
+describe("isBudgetText", () => {
+ it("accepts an empty box and any non-negative number", () => {
+ expect(isBudgetText("")).toBe(true);
+ expect(isBudgetText(" ")).toBe(true);
+ expect(isBudgetText("0")).toBe(true);
+ expect(isBudgetText("12.5")).toBe(true);
+ });
+
+ it("rejects a negative amount and anything that is not a number", () => {
+ expect(isBudgetText("-1")).toBe(false);
+ expect(isBudgetText("abc")).toBe(false);
+ expect(isBudgetText("1,000")).toBe(false);
+ });
+});
+
+describe("unitLabel", () => {
+ it("names the reader's currency and the period the cap covers", () => {
+ expect(unitLabel("USD", zh)).toBe("$ / 月");
+ expect(unitLabel("CNY", zh)).toBe("¥ / 月");
+ expect(unitLabel("USD", en)).toBe("$ / month");
+ expect(unitLabel("CNY", en)).toBe("¥ / month");
+ });
+});
diff --git a/packages/web/test/calendar-geom.test.ts b/packages/web/test/calendar-geom.test.ts
new file mode 100644
index 00000000..d6e42a75
--- /dev/null
+++ b/packages/web/test/calendar-geom.test.ts
@@ -0,0 +1,279 @@
+/**
+ * calendar-geom.ts unit tests: the month grid (as many Monday-based rows as the month
+ * needs), the week, the view ranges and stepping, period parsing, the expansion of an
+ * event's startAt / period / endAt into the instances of a range — including which past
+ * instance carries the recorded outcome — the cadence an event reads as, the lanes
+ * overlapping chips take, and how a legend entry draws under the employee filter. Dates are
+ * built with the local Date constructor, so the assertions hold in every timezone.
+ */
+import { describe, expect, it } from "vitest";
+import type { OrgCalendarItem } from "@prismshadow/penguin-server/api";
+import {
+ MAX_INSTANCES_PER_EVENT,
+ addDays,
+ cadenceOf,
+ chipLanes,
+ dayFraction,
+ dayKey,
+ expandEvents,
+ instancesByDay,
+ legendState,
+ monthGrid,
+ parsePeriodMs,
+ shiftAnchor,
+ startOfWeek,
+ timeLabel,
+ toLocalInput,
+ viewRange,
+ weekDays,
+} from "../src/features/company/calendar-geom";
+
+const local = (y: number, m0: number, d: number, h = 0, min = 0) =>
+ new Date(y, m0, d, h, min).getTime();
+
+function event(over: Partial<OrgCalendarItem> & { startAt: string }): OrgCalendarItem {
+ return {
+ agentId: "ceo",
+ name: "standup",
+ prompt: "check the board",
+ enabled: true,
+ status: "active",
+ paused: false,
+ ...over,
+ };
+}
+
+describe("day and week arithmetic", () => {
+ it("keys a day as yyyy-mm-dd and finds the Monday of its week", () => {
+ // 2026-09-02 is a Wednesday.
+ expect(dayKey(local(2026, 8, 2, 15))).toBe("2026-09-02");
+ expect(dayKey(startOfWeek(local(2026, 8, 2, 15)))).toBe("2026-08-31");
+ // A Sunday belongs to the week that started six days earlier.
+ expect(dayKey(startOfWeek(local(2026, 8, 6)))).toBe("2026-08-31");
+ expect(dayKey(addDays(local(2026, 8, 30), 1))).toBe("2026-10-01");
+ });
+
+ it("lays the month out as Monday-based rows, only as many as it needs, marking the days outside it", () => {
+ // September 2026: Tuesday the 1st to Wednesday the 30th spans five Monday-based weeks.
+ const grid = monthGrid(local(2026, 8, 15));
+ expect(grid).toHaveLength(5);
+ expect(grid.every((row) => row.length === 7)).toBe(true);
+ expect(grid[0]![0]!.key).toBe("2026-08-31");
+ expect(grid[0]![0]!.inMonth).toBe(false);
+ expect(grid[0]![1]!.key).toBe("2026-09-01");
+ expect(grid[0]![1]!.inMonth).toBe(true);
+ expect(grid[4]![6]!.key).toBe("2026-10-04");
+ expect(grid[4]![6]!.inMonth).toBe(false);
+ // August 2026 starts on a Saturday and ends on a Monday: six rows.
+ expect(monthGrid(local(2026, 7, 10))).toHaveLength(6);
+ // February 2027 starts on a Monday and has 28 days: exactly four.
+ expect(monthGrid(local(2027, 1, 10))).toHaveLength(4);
+ });
+
+ it("the week is Monday to Sunday around the anchor", () => {
+ expect(weekDays(local(2026, 8, 2)).map((d) => d.key)).toEqual([
+ "2026-08-31",
+ "2026-09-01",
+ "2026-09-02",
+ "2026-09-03",
+ "2026-09-04",
+ "2026-09-05",
+ "2026-09-06",
+ ]);
+ });
+
+ it("view ranges are half-open and cover exactly the view", () => {
+ const day = viewRange(local(2026, 8, 2, 10), "day");
+ expect([dayKey(day.startMs), dayKey(day.endMs)]).toEqual(["2026-09-02", "2026-09-03"]);
+ const week = viewRange(local(2026, 8, 2, 10), "week");
+ expect([dayKey(week.startMs), dayKey(week.endMs)]).toEqual(["2026-08-31", "2026-09-07"]);
+ const month = viewRange(local(2026, 8, 2, 10), "month");
+ expect([dayKey(month.startMs), dayKey(month.endMs)]).toEqual(["2026-08-31", "2026-10-05"]);
+ });
+
+ it("steps the anchor by a day, a week or a month — clamping the day of a shorter month", () => {
+ expect(dayKey(shiftAnchor(local(2026, 8, 2), "day", 1))).toBe("2026-09-03");
+ expect(dayKey(shiftAnchor(local(2026, 8, 2), "week", -1))).toBe("2026-08-26");
+ expect(dayKey(shiftAnchor(local(2026, 0, 31), "month", 1))).toBe("2026-02-28");
+ expect(dayKey(shiftAnchor(local(2026, 0, 15), "month", -1))).toBe("2025-12-15");
+ });
+
+ it("places an instant in its day and labels it", () => {
+ expect(dayFraction(local(2026, 8, 2, 12, 0))).toBe(0.5);
+ expect(dayFraction(local(2026, 8, 2, 0, 0))).toBe(0);
+ expect(timeLabel(local(2026, 8, 2, 9, 5))).toBe("09:05");
+ expect(toLocalInput(new Date(local(2026, 8, 2, 9, 5)).toISOString())).toBe("2026-09-02T09:05");
+ expect(toLocalInput(undefined)).toBe("");
+ expect(toLocalInput("nope")).toBe("");
+ });
+});
+
+describe("parsePeriodMs", () => {
+ it("accepts the server's m / h / d forms and nothing else", () => {
+ expect(parsePeriodMs("30m")).toBe(30 * 60_000);
+ expect(parsePeriodMs("12h")).toBe(12 * 3_600_000);
+ expect(parsePeriodMs("7d")).toBe(7 * 24 * 3_600_000);
+ for (const raw of ["", "0m", "1w", "5", "m", "-1h", undefined]) {
+ expect(parsePeriodMs(raw)).toBeNull();
+ }
+ });
+});
+
+describe("expandEvents", () => {
+ const rangeStart = local(2026, 8, 1);
+ const rangeEnd = local(2026, 8, 8);
+ const now = local(2026, 8, 3, 12);
+
+ it("expands a periodic event across the range, skipping the part before it and stopping at endAt", () => {
+ const daily = event({
+ startAt: new Date(local(2026, 7, 20, 9)).toISOString(),
+ period: "1d",
+ endAt: new Date(local(2026, 8, 5, 9)).toISOString(),
+ });
+ const out = expandEvents([daily], rangeStart, rangeEnd, now);
+ expect(out.map((i) => dayKey(i.atMs))).toEqual([
+ "2026-09-01",
+ "2026-09-02",
+ "2026-09-03",
+ "2026-09-04",
+ "2026-09-05",
+ ]);
+ expect(out.map((i) => i.past)).toEqual([true, true, true, false, false]);
+ expect(out[0]!.key).toBe(`ceo/standup@${local(2026, 8, 1, 9)}`);
+ });
+
+ it("a one-off yields at most its own instant, inside the range only", () => {
+ const inRange = event({
+ name: "kickoff",
+ startAt: new Date(local(2026, 8, 2, 14)).toISOString(),
+ });
+ const outside = event({
+ name: "later",
+ startAt: new Date(local(2026, 9, 2, 14)).toISOString(),
+ });
+ const out = expandEvents([inRange, outside], rangeStart, rangeEnd, now);
+ expect(out.map((i) => i.event.name)).toEqual(["kickoff"]);
+ });
+
+ it("pins the recorded outcome to the instance nearest lastFiredAt and leaves other past instances without a claim", () => {
+ const daily = event({
+ startAt: new Date(local(2026, 8, 1, 9)).toISOString(),
+ period: "1d",
+ // Fired twenty seconds after the 09:00 slot of the 3rd: well inside half a period.
+ lastFiredAt: new Date(new Date(2026, 8, 3, 9, 0, 20).getTime()).toISOString(),
+ lastOutcome: "fired",
+ });
+ const out = expandEvents([daily], rangeStart, rangeEnd, now);
+ expect(out.map((i) => i.outcome)).toEqual([null, null, "fired", null, null, null, null]);
+ });
+
+ it("drops events it cannot place and caps a runaway period", () => {
+ const bad = event({ startAt: "not a date" });
+ const badPeriod = event({
+ name: "p",
+ startAt: new Date(rangeStart).toISOString(),
+ period: "1w",
+ });
+ expect(expandEvents([bad, badPeriod], rangeStart, rangeEnd, now)).toEqual([]);
+ const tiny = event({ name: "t", startAt: new Date(rangeStart).toISOString(), period: "1m" });
+ expect(expandEvents([tiny], rangeStart, rangeEnd, now)).toHaveLength(MAX_INSTANCES_PER_EVENT);
+ });
+
+ it("buckets instances by day and orders employees by first appearance", () => {
+ const a = event({ agentId: "a", startAt: new Date(local(2026, 8, 2, 9)).toISOString() });
+ const b = event({
+ agentId: "b",
+ name: "x",
+ startAt: new Date(local(2026, 8, 2, 11)).toISOString(),
+ });
+ const byDay = instancesByDay(expandEvents([b, a], rangeStart, rangeEnd, now));
+ expect([...byDay.keys()]).toEqual(["2026-09-02"]);
+ expect(byDay.get("2026-09-02")!.map((i) => i.event.agentId)).toEqual(["a", "b"]);
+ });
+});
+
+describe("cadenceOf", () => {
+ const start = new Date(local(2026, 8, 2, 9, 30)).toISOString();
+
+ it("reads whole-day periods as day and week cadences with the time of day", () => {
+ expect(cadenceOf({ startAt: start, period: "1d" })).toEqual({
+ kind: "days",
+ n: 1,
+ time: "09:30",
+ });
+ expect(cadenceOf({ startAt: start, period: "3d" })).toEqual({
+ kind: "days",
+ n: 3,
+ time: "09:30",
+ });
+ expect(cadenceOf({ startAt: start, period: "7d" })).toEqual({
+ kind: "weeks",
+ n: 1,
+ time: "09:30",
+ });
+ expect(cadenceOf({ startAt: start, period: "14d" })).toEqual({
+ kind: "weeks",
+ n: 2,
+ time: "09:30",
+ });
+ });
+
+ it("keeps sub-day periods in their own unit, and no period is a one-off", () => {
+ expect(cadenceOf({ startAt: start, period: "12h" })).toEqual({ kind: "hours", n: 12 });
+ expect(cadenceOf({ startAt: start, period: "90m" })).toEqual({ kind: "minutes", n: 90 });
+ expect(cadenceOf({ startAt: start, period: "48h" })).toEqual({
+ kind: "days",
+ n: 2,
+ time: "09:30",
+ });
+ expect(cadenceOf({ startAt: start })).toEqual({ kind: "once", atMs: local(2026, 8, 2, 9, 30) });
+ });
+
+ it("is invalid for an unparseable start or period", () => {
+ expect(cadenceOf({ startAt: "nope", period: "1d" })).toEqual({ kind: "invalid" });
+ expect(cadenceOf({ startAt: start, period: "1w" })).toEqual({ kind: "invalid" });
+ });
+});
+
+describe("chipLanes", () => {
+ const slot = 30 * 60_000;
+ const at = (h: number, m: number, key: string) => ({ atMs: local(2026, 8, 2, h, m), key });
+
+ it("gives a lone chip the full width and packs overlapping chips side by side", () => {
+ const out = chipLanes([at(14, 0, "c"), at(9, 0, "a"), at(9, 10, "b")], slot);
+ expect(out.map((s) => [s.item.key, s.lane, s.lanes])).toEqual([
+ ["a", 0, 2],
+ ["b", 1, 2],
+ ["c", 0, 1],
+ ]);
+ });
+
+ it("chains overlaps into one cluster and reuses a lane once it is free", () => {
+ // a 09:00–09:30, b 09:20–09:50, c 09:40–10:10: b overlaps both, a and c can share lane 0.
+ const out = chipLanes([at(9, 0, "a"), at(9, 20, "b"), at(9, 40, "c")], slot);
+ expect(out.map((s) => [s.item.key, s.lane, s.lanes])).toEqual([
+ ["a", 0, 2],
+ ["b", 1, 2],
+ ["c", 0, 2],
+ ]);
+ });
+
+ it("touching slots do not overlap, and the same instant sorts by key", () => {
+ const out = chipLanes([at(9, 30, "b"), at(9, 0, "a"), at(9, 0, "c")], slot);
+ expect(out.map((s) => [s.item.key, s.lane, s.lanes])).toEqual([
+ ["a", 0, 2],
+ ["c", 1, 2],
+ ["b", 0, 1],
+ ]);
+ expect(chipLanes([], slot)).toEqual([]);
+ });
+});
+
+describe("legendState", () => {
+ it("strikes through everyone the filter switched off, and nobody while it is off", () => {
+ expect(legendState("", "a")).toBe("plain");
+ expect(legendState("", "b")).toBe("plain");
+ expect(legendState("a", "a")).toBe("pressed");
+ expect(legendState("a", "b")).toBe("struck");
+ });
+});
diff --git a/packages/web/test/canvas-view.test.ts b/packages/web/test/canvas-view.test.ts
new file mode 100644
index 00000000..33243361
--- /dev/null
+++ b/packages/web/test/canvas-view.test.ts
@@ -0,0 +1,165 @@
+/**
+ * canvas-view.ts unit tests: the zoom range, a wheel tick's factor, the anchored zoom that
+ * keeps the point under the cursor fixed, panning, the clamp that keeps the drawing reachable,
+ * and the fit a chart opens at.
+ */
+import { describe, expect, it } from "vitest";
+import {
+ IDENTITY_VIEW,
+ ZOOM_MAX,
+ ZOOM_MIN,
+ ZOOM_STEP,
+ clampView,
+ clampZoom,
+ fitView,
+ panBy,
+ viewTransform,
+ wheelZoomFactor,
+ zoomAt,
+} from "../src/features/company/canvas-view";
+import type { CanvasView } from "../src/features/company/canvas-view";
+
+/** Where a point of the drawing lands in the frame under a view — the inverse of what zoomAt has to preserve. */
+const project = (view: CanvasView, x: number, y: number) => ({
+ x: view.x + x * view.scale,
+ y: view.y + y * view.scale,
+});
+
+describe("clampZoom", () => {
+ it("keeps a scale inside the range and treats a non-number as 100%", () => {
+ expect(clampZoom(0.01)).toBe(ZOOM_MIN);
+ expect(clampZoom(50)).toBe(ZOOM_MAX);
+ expect(clampZoom(0.85)).toBe(0.85);
+ expect(clampZoom(Number.NaN)).toBe(1);
+ });
+});
+
+describe("wheelZoomFactor", () => {
+ it("zooms in scrolling up and out scrolling down, by a tenth per notch", () => {
+ expect(wheelZoomFactor(-100)).toBeCloseTo(1.1, 10);
+ expect(wheelZoomFactor(100)).toBeCloseTo(1 / 1.1, 10);
+ expect(wheelZoomFactor(0)).toBe(1);
+ expect(wheelZoomFactor(Number.NaN)).toBe(1);
+ });
+
+ it("is smooth for a trackpad's small deltas and never jumps for an outsized one", () => {
+ const small = wheelZoomFactor(-10);
+ expect(small).toBeGreaterThan(1);
+ expect(small).toBeLessThan(1.02);
+ // A page-mode wheel reports a whole page per notch; the tick is capped at one notch.
+ expect(wheelZoomFactor(-1000)).toBeCloseTo(wheelZoomFactor(-100), 10);
+ expect(wheelZoomFactor(-1, 2)).toBeCloseTo(wheelZoomFactor(-100), 10);
+ // Line mode (Firefox): three lines is a notch's worth, but less than a full one.
+ expect(wheelZoomFactor(-3, 1)).toBeGreaterThan(1);
+ expect(wheelZoomFactor(-3, 1)).toBeLessThan(wheelZoomFactor(-100));
+ });
+});
+
+describe("zoomAt", () => {
+ const view: CanvasView = { x: -120, y: 40, scale: 0.8 };
+
+ it("keeps the drawing point under the pointer under it, zooming in and out", () => {
+ for (const factor of [ZOOM_STEP, 1 / ZOOM_STEP, 1.37]) {
+ const pointer = { x: 300, y: 220 };
+ // The drawing point currently under the pointer, in drawing coordinates.
+ const dx = (pointer.x - view.x) / view.scale;
+ const dy = (pointer.y - view.y) / view.scale;
+ const next = zoomAt(view, pointer, factor);
+ expect(next.scale).toBeCloseTo(view.scale * factor, 10);
+ expect(project(next, dx, dy).x).toBeCloseTo(pointer.x, 8);
+ expect(project(next, dx, dy).y).toBeCloseTo(pointer.y, 8);
+ }
+ });
+
+ it("anchors at the frame's origin as readily as at a point inside it", () => {
+ const next = zoomAt(view, { x: 0, y: 0 }, 2);
+ expect(next).toEqual({ x: -240, y: 80, scale: 1.6 });
+ });
+
+ it("stops at the range's ends and translates by the factor the clamp allowed, not the asked one", () => {
+ const atMax = zoomAt({ x: 10, y: 10, scale: ZOOM_MAX }, { x: 100, y: 100 }, 4);
+ expect(atMax).toEqual({ x: 10, y: 10, scale: ZOOM_MAX });
+ const toMax = zoomAt({ x: 0, y: 0, scale: 1 }, { x: 100, y: 0 }, 10);
+ expect(toMax.scale).toBe(ZOOM_MAX);
+ // The point at drawing x = 100 stays at frame x = 100 even though the factor was cut.
+ expect(project(toMax, 100, 0).x).toBeCloseTo(100, 8);
+ const atMin = zoomAt({ x: 5, y: 5, scale: ZOOM_MIN }, { x: 0, y: 0 }, 0.5);
+ expect(atMin).toEqual({ x: 5, y: 5, scale: ZOOM_MIN });
+ });
+});
+
+describe("panBy", () => {
+ it("adds the pointer delta to the translation and leaves the scale alone", () => {
+ expect(panBy({ x: 10, y: -5, scale: 0.5 }, 30, -12)).toEqual({ x: 40, y: -17, scale: 0.5 });
+ });
+});
+
+describe("clampView", () => {
+ const frame = { width: 1000, height: 600 };
+ const drawing = { width: 2000, height: 1200 };
+
+ it("leaves a view that has the frame's centre on the drawing untouched", () => {
+ const view = { x: -400, y: -200, scale: 1 };
+ expect(clampView(view, frame, drawing)).toEqual(view);
+ });
+
+ it("stops a pan where the drawing's far edge reaches the frame's centre", () => {
+ // Dragged right until the drawing's left edge is at the centre, and no further.
+ expect(clampView({ x: 9000, y: 0, scale: 1 }, frame, drawing).x).toBe(frame.width / 2);
+ // ...and left until its right edge is there.
+ expect(clampView({ x: -9000, y: 0, scale: 1 }, frame, drawing).x).toBe(
+ frame.width / 2 - drawing.width,
+ );
+ // The reach follows the scale: a shrunk drawing may travel less far.
+ expect(clampView({ x: 0, y: -9000, scale: 0.5 }, frame, drawing).y).toBe(
+ frame.height / 2 - drawing.height * 0.5,
+ );
+ expect(clampView({ x: 0, y: 9000, scale: 0.5 }, frame, drawing).y).toBe(frame.height / 2);
+ });
+
+ it("lets a drawing larger than the frame still reach both of its own edges", () => {
+ // The right edge brought to the frame's right edge, which a centre-on-drawing rule allows.
+ const showRight = { x: frame.width - drawing.width, y: 0, scale: 1 };
+ expect(clampView(showRight, frame, drawing).x).toBe(showRight.x);
+ expect(clampView({ x: 0, y: 0, scale: 1 }, frame, drawing).x).toBe(0);
+ });
+
+ it("clamps the scale too, so a view can only ever be handed on valid", () => {
+ expect(clampView({ x: 0, y: 0, scale: 99 }, frame, drawing).scale).toBe(ZOOM_MAX);
+ });
+});
+
+describe("fitView", () => {
+ it("centres a drawing smaller than the frame without enlarging it", () => {
+ expect(fitView({ width: 1000, height: 600 }, { width: 400, height: 200 })).toEqual({
+ x: 300,
+ y: 200,
+ scale: 1,
+ });
+ });
+
+ it("shrinks by the tighter of the two axes and centres what is left over", () => {
+ // Width wants 0.5, height wants 0.25: the height decides, and the width is centred.
+ const view = fitView({ width: 1000, height: 300 }, { width: 2000, height: 1200 });
+ expect(view.scale).toBe(0.25);
+ expect(view.x).toBe((1000 - 2000 * 0.25) / 2);
+ expect(view.y).toBe(0);
+ });
+
+ it("never shrinks past the zoom range's floor", () => {
+ expect(fitView({ width: 100, height: 100 }, { width: 10_000, height: 10_000 }).scale).toBe(
+ ZOOM_MIN,
+ );
+ });
+
+ it("is the identity view while the frame is unmeasured or the drawing empty", () => {
+ expect(fitView({ width: 0, height: 0 }, { width: 400, height: 200 })).toBe(IDENTITY_VIEW);
+ expect(fitView({ width: 1000, height: 600 }, { width: 0, height: 0 })).toBe(IDENTITY_VIEW);
+ });
+});
+
+describe("viewTransform", () => {
+ it("translates before it scales, which is the order the arithmetic assumes", () => {
+ expect(viewTransform({ x: 12, y: -4, scale: 0.75 })).toBe("translate(12px, -4px) scale(0.75)");
+ });
+});
diff --git a/packages/web/test/channel-list.test.ts b/packages/web/test/channel-list.test.ts
new file mode 100644
index 00000000..533cd51c
--- /dev/null
+++ b/packages/web/test/channel-list.test.ts
@@ -0,0 +1,162 @@
+/**
+ * channel-list.ts unit tests: the all-hands channel's reserved id and its localized label,
+ * the four runs of the sidebar's list and the order inside them, the id a new channel may
+ * take, the two numbers the sidebar and rail badges sum, and who is left to invite.
+ */
+import { describe, expect, it } from "vitest";
+import type { OrgChannelItem } from "@prismshadow/penguin-server/api";
+import {
+ CHANNEL_ID_PATTERN,
+ DEFAULT_CHANNEL_ID,
+ channelBadgeCounts,
+ channelIdProblem,
+ channelLabel,
+ groupChannels,
+ inviteCandidates,
+ isAllHands,
+} from "../src/features/company/channel-list";
+
+const channel = (over: Partial<OrgChannelItem> & { channelId: string }): OrgChannelItem => ({
+ name: over.channelId,
+ purpose: "",
+ everyone: false,
+ archived: false,
+ createdBy: "user:alice",
+ createdAt: "2026-09-03T00:00:00Z",
+ memberCount: 1,
+ isMember: true,
+ unread: 0,
+ mentionsMe: 0,
+ lastMessageAt: null,
+ ...over,
+});
+
+describe("the all-hands channel", () => {
+ it("is `default_channel`, and renders under its localized label rather than its stored name", () => {
+ expect(DEFAULT_CHANNEL_ID).toBe("default_channel");
+ expect(isAllHands(DEFAULT_CHANNEL_ID)).toBe(true);
+ expect(isAllHands("site")).toBe(false);
+ expect(channelLabel({ channelId: DEFAULT_CHANNEL_ID, name: "General" }, "全员频道")).toBe(
+ "全员频道",
+ );
+ expect(channelLabel({ channelId: "site", name: "Site launch" }, "全员频道")).toBe(
+ "Site launch",
+ );
+ });
+});
+
+describe("channelIdProblem", () => {
+ it("accepts the semantic-id grammar the server enforces", () => {
+ expect(CHANNEL_ID_PATTERN.test("site")).toBe(true);
+ for (const id of ["site", "site_2", "a1", "marketing_q4"]) {
+ expect(channelIdProblem(id)).toBeNull();
+ }
+ });
+
+ it("names why an id is refused, before the request goes out", () => {
+ expect(channelIdProblem("")).toBe("required");
+ expect(channelIdProblem(" ")).toBe("required");
+ // A single character, a leading digit, an uppercase letter, a hyphen, and 65 characters.
+ expect(channelIdProblem("a")).toBe("invalid");
+ expect(channelIdProblem("1site")).toBe("invalid");
+ expect(channelIdProblem("Site")).toBe("invalid");
+ expect(channelIdProblem("site-launch")).toBe("invalid");
+ expect(channelIdProblem(`a${"b".repeat(64)}`)).toBe("invalid");
+ // The all-hands channel owns its id.
+ expect(channelIdProblem(DEFAULT_CHANNEL_ID)).toBe("reserved");
+ expect(channelIdProblem("site", ["site", "marketing"])).toBe("taken");
+ expect(channelIdProblem(" site ", ["site"])).toBe("taken");
+ expect(channelIdProblem("design", ["site"])).toBeNull();
+ });
+});
+
+describe("groupChannels", () => {
+ const channels = [
+ channel({ channelId: "site", name: "Site launch" }),
+ channel({ channelId: DEFAULT_CHANNEL_ID, name: "General", everyone: true, memberCount: 4 }),
+ channel({ channelId: "old_launch", name: "Launch 2025", archived: true }),
+ channel({ channelId: "marketing", name: "Marketing", isMember: false }),
+ channel({ channelId: "design", name: "Design" }),
+ channel({ channelId: "gone", name: "Gone", isMember: false, archived: true }),
+ ];
+
+ it("pins the all-hands channel, then splits by membership, with archived winning over both", () => {
+ const groups = groupChannels(channels, "All hands");
+ expect(groups.allHands?.channelId).toBe(DEFAULT_CHANNEL_ID);
+ expect(groups.mine.map((c) => c.channelId)).toEqual(["design", "site"]);
+ expect(groups.others.map((c) => c.channelId)).toEqual(["marketing"]);
+ // Archived channels fold away whether or not the caller is a member of them.
+ expect(groups.archived.map((c) => c.channelId)).toEqual(["gone", "old_launch"]);
+ });
+
+ it("orders each run by display name, then by id for two channels of one name", () => {
+ const same = [
+ channel({ channelId: "b_room", name: "Room" }),
+ channel({ channelId: "a_room", name: "Room" }),
+ channel({ channelId: "zebra", name: "Alpha" }),
+ ];
+ expect(groupChannels(same, "All hands").mine.map((c) => c.channelId)).toEqual([
+ "zebra",
+ "a_room",
+ "b_room",
+ ]);
+ });
+
+ it("survives an organization whose all-hands channel is missing", () => {
+ const groups = groupChannels([channel({ channelId: "site" })], "All hands");
+ expect(groups.allHands).toBeNull();
+ expect(groups.mine).toHaveLength(1);
+ });
+});
+
+describe("channelBadgeCounts", () => {
+ it("sums the channels the caller belongs to and skips the rest", () => {
+ expect(
+ channelBadgeCounts([
+ channel({ channelId: DEFAULT_CHANNEL_ID, unread: 3, mentionsMe: 1 }),
+ channel({ channelId: "site", unread: 2, mentionsMe: 2 }),
+ // Readable but not joined: it is waiting for nobody.
+ channel({ channelId: "marketing", isMember: false, unread: 9, mentionsMe: 4 }),
+ // Archived: folded away in the list, so it must not sit in the total either.
+ channel({ channelId: "old_launch", archived: true, unread: 7, mentionsMe: 5 }),
+ ]),
+ ).toEqual({ unread: 5, mentions: 3 });
+ expect(channelBadgeCounts([])).toEqual({ unread: 0, mentions: 0 });
+ });
+});
+
+describe("inviteCandidates", () => {
+ const employees = [
+ { agentId: "ceo", name: "Alice CEO", title: "CEO" },
+ { agentId: "dev", name: "Dev Lead", title: " " },
+ ];
+
+ it("offers employees then Project members, minus who is already in the channel", () => {
+ const list = inviteCandidates(
+ employees,
+ ["alice", "bob"],
+ [
+ { principal: "agent:ceo", name: "Alice CEO", kind: "agent" as const },
+ { principal: "user:alice", name: "alice", kind: "user" as const },
+ ],
+ );
+ expect(list.map((c) => c.principal)).toEqual(["agent:dev", "user:bob"]);
+ // A blank title is not a detail line.
+ expect("detail" in list[0]!).toBe(false);
+ });
+
+ it("carries an employee's title and ranks a prefix above a substring", () => {
+ const list = inviteCandidates(employees, ["alice"], []);
+ expect(list[0]?.detail).toBe("CEO");
+ expect(inviteCandidates(employees, ["alice"], [], "de").map((c) => c.principal)).toEqual([
+ "agent:dev",
+ ]);
+ // "lice" is inside both the employee's name and the member's id; the member's id starts
+ // with neither, so list order breaks the tie between two equal scores.
+ expect(inviteCandidates(employees, ["alice"], [], "lice").map((c) => c.principal)).toEqual([
+ "agent:ceo",
+ "user:alice",
+ ]);
+ expect(inviteCandidates(employees, ["alice"], [], "zzz")).toEqual([]);
+ });
+});
diff --git a/packages/web/test/channel-markdown.test.ts b/packages/web/test/channel-markdown.test.ts
new file mode 100644
index 00000000..3c832d3d
--- /dev/null
+++ b/packages/web/test/channel-markdown.test.ts
@@ -0,0 +1,98 @@
+/**
+ * A channel message body, via react-dom/server static markup (node env, no DOM): Markdown
+ * renders — headings, lists, tables, fenced code — while the `@mentions` around it stay chips
+ * that resolve an employee's name and mark the ones addressing the reader; a mention inside
+ * code stays literal; and a single typed newline stays a line break rather than folding into a
+ * space, which is what the composer's Shift+Enter promises.
+ */
+import { describe, expect, it } from "vitest";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import {
+ ChannelMessageBody,
+ ChannelReaderProvider,
+} from "../src/features/company/channel-markdown";
+import { zh } from "../src/lib/strings";
+
+const reader = {
+ names: new Map([["ceo", "Ada CEO"]]),
+ me: "alice",
+ employeeIds: new Set(["ceo"]),
+};
+
+const render = (text: string) =>
+ renderToStaticMarkup(
+ createElement(ChannelReaderProvider, {
+ reader,
+ children: createElement(ChannelMessageBody, { text }),
+ }),
+ );
+
+describe("channel message Markdown", () => {
+ it("renders headings, lists and tables instead of their markers", () => {
+ const html = render("## Plan\n\n- one\n- two\n\n| a | b |\n| - | - |\n| 1 | 2 |");
+ expect(html).toContain("<h2>Plan</h2>");
+ expect(html).toContain("<li>one</li>");
+ expect(html).toContain("<table>");
+ expect(html).not.toContain("## Plan");
+ });
+
+ it("keeps a fenced block's content literal, mention included", () => {
+ const html = render("```\n@ceo ls\n```");
+ expect(html).toContain("@ceo ls");
+ expect(html).not.toContain("Ada CEO");
+ });
+
+ it("keeps a mention inside inline code literal", () => {
+ const html = render("write `@ceo` to reach it");
+ expect(html).toContain("<code>@ceo</code>");
+ expect(html).not.toContain("Ada CEO");
+ });
+
+ it("links open in a new tab", () => {
+ const html = render("see [docs](https://example.com)");
+ expect(html).toContain('target="_blank"');
+ expect(html).toContain('rel="noreferrer"');
+ });
+});
+
+describe("mentions inside a message body", () => {
+ it("resolves an employee's name and keeps the raw token in the tooltip", () => {
+ const html = render("@ceo 先看一下");
+ expect(html).toContain('title="@ceo"');
+ expect(html).toContain("@Ada CEO");
+ expect(html).not.toContain(zh.company.channels.mentionsYou);
+ });
+
+ it("marks a mention that addresses the reader", () => {
+ const html = render("@user:alice 这条是给你的");
+ expect(html).toContain('title="@user:alice"');
+ expect(html).toContain(zh.company.channels.mentionsYou);
+ });
+
+ it("survives inside a list item and a heading", () => {
+ const html = render("# @ceo\n\n- ping @ceo");
+ expect(html).toContain("<h1>");
+ expect(html).toContain("<li>");
+ expect((html.match(/@Ada CEO/g) ?? []).length).toBe(2);
+ });
+
+ it("leaves a message with no mention as one paragraph", () => {
+ const html = render("just a note");
+ expect(html).toBe("<p>just a note</p>");
+ });
+});
+
+describe("typed line breaks", () => {
+ it("keeps a single newline as a break rather than a space", () => {
+ const html = render("first line\nsecond line");
+ expect(html).toContain("<br/>");
+ expect(html).toContain("first line");
+ expect(html).toContain("second line");
+ });
+
+ it("still separates paragraphs on a blank line", () => {
+ const html = render("one\n\ntwo");
+ expect(html).toBe("<p>one</p>\n<p>two</p>");
+ });
+});
diff --git a/packages/web/test/channel-mentions.test.ts b/packages/web/test/channel-mentions.test.ts
new file mode 100644
index 00000000..9040f1b9
--- /dev/null
+++ b/packages/web/test/channel-mentions.test.ts
@@ -0,0 +1,202 @@
+/**
+ * channel-mentions.ts unit tests: the candidate list, its narrowing to a channel's own
+ * membership, its filter and its ranking, what a pick types, the @-token at the caret,
+ * splicing a pick into the draft, splitting a stored message into plain and mention runs by
+ * the server's own token grammar, and what a mention run displays and whom it addresses.
+ */
+import { describe, expect, it } from "vitest";
+import {
+ channelMentionCandidates,
+ insertMention,
+ mentionCandidates,
+ mentionInsertId,
+ mentionIsMe,
+ mentionLabel,
+ mentionQueryAt,
+ mentionRuns,
+ rankMentionCandidates,
+} from "../src/features/company/channel-mentions";
+
+const candidates = mentionCandidates(
+ [
+ { agentId: "ceo", name: "Alice" },
+ { agentId: "pm", name: "Product" },
+ ],
+ ["bob"],
+ "Everyone",
+);
+
+describe("mentionCandidates", () => {
+ it("lists employees, then members, then all, with their principals", () => {
+ expect(candidates.map((c) => c.principal)).toEqual([
+ "agent:ceo",
+ "agent:pm",
+ "user:bob",
+ "all",
+ ]);
+ expect(candidates[3]).toEqual({ principal: "all", label: "Everyone", id: "all", kind: "all" });
+ });
+});
+
+describe("mentionQueryAt", () => {
+ it("finds the token the caret ends and reports what was typed after the @", () => {
+ expect(mentionQueryAt("hi @ce", 6)).toEqual({ start: 3, query: "ce" });
+ expect(mentionQueryAt("@", 1)).toEqual({ start: 0, query: "" });
+ expect(mentionQueryAt("@agent:c", 8)).toEqual({ start: 0, query: "agent:c" });
+ });
+
+ it("is null when the @ is glued to a word, when a space breaks the token, or when there is none", () => {
+ expect(mentionQueryAt("mail@ex", 7)).toBeNull();
+ expect(mentionQueryAt("@ceo please", 11)).toBeNull();
+ expect(mentionQueryAt("plain", 5)).toBeNull();
+ });
+});
+
+describe("insertMention", () => {
+ it("replaces the typed token with the principal and a trailing space, moving the caret after it", () => {
+ expect(insertMention("hi @ce there", 3, 6, "agent:ceo")).toEqual({
+ text: "hi @agent:ceo there",
+ caret: 14,
+ });
+ });
+});
+
+describe("mentionRuns", () => {
+ it("splits plain text and mentions in order, keeping the server's trailing-punctuation rule", () => {
+ expect(mentionRuns("@ceo, ping @user:bob. cc @all")).toEqual([
+ { text: "@ceo", mention: "ceo" },
+ { text: ", ping ", mention: null },
+ { text: "@user:bob", mention: "user:bob" },
+ { text: ". cc ", mention: null },
+ { text: "@all", mention: "all" },
+ ]);
+ });
+
+ it("leaves an email address alone and returns one plain run for text without mentions", () => {
+ expect(mentionRuns("write to [email protected]")).toEqual([
+ { text: "write to [email protected]", mention: null },
+ ]);
+ expect(mentionRuns("")).toEqual([]);
+ });
+});
+
+describe("mentionCandidates with titles", () => {
+ it("carries an employee's title as the detail and leaves a blank one out", () => {
+ const list = mentionCandidates(
+ [
+ { agentId: "ceo", name: "Alice", title: "CEO" },
+ { agentId: "pm", name: "Product", title: " " },
+ ],
+ [],
+ "Everyone",
+ );
+ expect(list[0]?.detail).toBe("CEO");
+ expect("detail" in list[1]!).toBe(false);
+ });
+});
+
+describe("rankMentionCandidates", () => {
+ const list = mentionCandidates(
+ [
+ { agentId: "studio_ceo", name: "Penguin CEO" },
+ { agentId: "studio_cto", name: "Tech Lead" },
+ { agentId: "ops", name: "Studio Ops" },
+ ],
+ ["stu", "bob"],
+ "Everyone",
+ );
+
+ it("keeps the list's own order for an empty query", () => {
+ expect(rankMentionCandidates(list, "").map((c) => c.id)).toEqual([
+ "studio_ceo",
+ "studio_cto",
+ "ops",
+ "stu",
+ "bob",
+ "all",
+ ]);
+ });
+
+ it("puts id and name prefixes above substring matches, ties in list order", () => {
+ // "stu": prefixes on studio_ceo / studio_cto / Studio Ops (name) / stu; nothing else.
+ expect(rankMentionCandidates(list, "stu").map((c) => c.id)).toEqual([
+ "studio_ceo",
+ "studio_cto",
+ "ops",
+ "stu",
+ ]);
+ // "lead": a substring of the name only.
+ expect(rankMentionCandidates(list, "LEAD").map((c) => c.id)).toEqual(["studio_cto"]);
+ // "cto" is a prefix of nothing but is contained in studio_cto.
+ expect(rankMentionCandidates(list, "cto").map((c) => c.id)).toEqual(["studio_cto"]);
+ // A principal prefix reaches the members.
+ expect(rankMentionCandidates(list, "user:").map((c) => c.id)).toEqual(["stu", "bob"]);
+ expect(rankMentionCandidates(list, "zzz")).toEqual([]);
+ });
+});
+
+describe("mentionInsertId", () => {
+ it("types a bare id, and disambiguates a member who shares an employee's id", () => {
+ const list = mentionCandidates([{ agentId: "alice", name: "Alice" }], ["alice", "bob"], "All");
+ expect(mentionInsertId(list[0]!, list)).toBe("alice");
+ expect(mentionInsertId(list[1]!, list)).toBe("user:alice");
+ expect(mentionInsertId(list[2]!, list)).toBe("bob");
+ expect(mentionInsertId(list[3]!, list)).toBe("all");
+ });
+});
+
+describe("mentionLabel and mentionIsMe", () => {
+ const names = new Map([["ceo", "Alice"]]);
+ const employees = new Set(["ceo", "bob"]);
+
+ it("resolves an agent id to its name, a member to its id, all to the everyone label", () => {
+ expect(mentionLabel("agent:ceo", names, "Everyone")).toBe("Alice");
+ expect(mentionLabel("ceo", names, "Everyone")).toBe("Alice");
+ expect(mentionLabel("user:bob", names, "Everyone")).toBe("bob");
+ expect(mentionLabel("unknown", names, "Everyone")).toBe("unknown");
+ expect(mentionLabel("all", names, "Everyone")).toBe("Everyone");
+ });
+
+ it("addresses the reader by principal, by all, or by bare id when no employee claims it", () => {
+ expect(mentionIsMe("user:bob", "bob", employees)).toBe(true);
+ expect(mentionIsMe("all", "bob", employees)).toBe(true);
+ // The server gives a bare "bob" to the employee of that id, not the member.
+ expect(mentionIsMe("bob", "bob", employees)).toBe(false);
+ expect(mentionIsMe("carol", "carol", employees)).toBe(true);
+ expect(mentionIsMe("all", "", employees)).toBe(false);
+ });
+});
+
+describe("channelMentionCandidates", () => {
+ const list = mentionCandidates(
+ [
+ { agentId: "ceo", name: "Alice" },
+ { agentId: "pm", name: "Product" },
+ ],
+ ["bob", "carol"],
+ "Everyone",
+ );
+
+ it("keeps only the channel's members, and `all` — which means that membership", () => {
+ const members = new Set(["agent:pm", "user:carol"]);
+ expect(channelMentionCandidates(list, members).map((c) => c.principal)).toEqual([
+ "agent:pm",
+ "user:carol",
+ "all",
+ ]);
+ });
+
+ it("offers everyone when the membership is not known yet, rather than an empty panel", () => {
+ expect(channelMentionCandidates(list, null).map((c) => c.principal)).toEqual([
+ "agent:ceo",
+ "agent:pm",
+ "user:bob",
+ "user:carol",
+ "all",
+ ]);
+ });
+
+ it("is `all` alone in a channel whose only member is the reader's own employee-free self", () => {
+ expect(channelMentionCandidates(list, new Set()).map((c) => c.principal)).toEqual(["all"]);
+ });
+});
diff --git a/packages/web/test/channel-notices.test.ts b/packages/web/test/channel-notices.test.ts
new file mode 100644
index 00000000..5343e71d
--- /dev/null
+++ b/packages/web/test/channel-notices.test.ts
@@ -0,0 +1,80 @@
+/**
+ * channel-notices.ts unit tests: every kind the contract declares has a sentence in both
+ * dictionaries, the sentence names employees instead of spelling them `agent:<id>`, a member
+ * reads as its user id, an unknown employee falls back to its id, and a kind this build does
+ * not know renders nothing so the view can fall back to the server's English text.
+ */
+import { describe, expect, it } from "vitest";
+import type { OrgChannelNotice } from "@prismshadow/penguin-server/api";
+import { NOTICE_KINDS, noticeText } from "../src/features/company/channel-notices";
+import { zh } from "../src/lib/strings";
+import { en } from "../src/lib/strings-en";
+
+const names = new Map([
+ ["ceo", "Ada CEO"],
+ ["dev", "Dana Dev"],
+]);
+
+const notice = (kind: string, params: Record<string, string>): OrgChannelNotice =>
+ ({ kind, params }) as OrgChannelNotice;
+
+describe("the notice dictionaries", () => {
+ for (const [locale, dict] of Object.entries({ zh, en })) {
+ it(`${locale} carries one sentence per kind, and no key the contract does not declare`, () => {
+ const notices: Record<string, unknown> = dict.company.channels.notices;
+ expect(Object.keys(notices).sort()).toEqual([...NOTICE_KINDS].sort());
+ for (const kind of NOTICE_KINDS) expect(typeof notices[kind], kind).toBe("function");
+ });
+ }
+
+ it("has wording for every kind, even for a notice missing its parameters", () => {
+ for (const kind of NOTICE_KINDS) {
+ expect(noticeText(notice(kind, {}), names, zh.company.channels.notices), kind).toBeTruthy();
+ expect(noticeText(notice(kind, {}), names, en.company.channels.notices), kind).toBeTruthy();
+ }
+ });
+});
+
+describe("noticeText", () => {
+ const zhText = (n: OrgChannelNotice) => noticeText(n, names, zh.company.channels.notices);
+ const enText = (n: OrgChannelNotice) => noticeText(n, names, en.company.channels.notices);
+
+ it("names the employees of a hire and keeps the job title verbatim", () => {
+ const hire = notice("employee_joined", {
+ agent: "agent:dev",
+ title: "研究",
+ reportsTo: "agent:ceo",
+ });
+ expect(enText(hire)).toBe("Dana Dev joined as 研究, reporting to Ada CEO.");
+ expect(zhText(hire)).toBe("Dana Dev 以「研究」身份加入,汇报给 Ada CEO。");
+ });
+
+ it("renders a member as its user id and an unknown employee as its id", () => {
+ const invited = notice("channel_invited", { by: "user:alice", principal: "agent:ghost" });
+ expect(enText(invited)).toBe("alice invited ghost to the channel.");
+ });
+
+ it("carries a budget event's period, share and amounts", () => {
+ const warned = notice("budget_warned", {
+ agent: "agent:ceo",
+ period: "2026-09",
+ percent: "82",
+ cost: "41.00",
+ budget: "50.00",
+ });
+ expect(enText(warned)).toBe(
+ "Budget warning: Ada CEO has used 82% of its 2026-09 budget (41.00 / 50.00 USD).",
+ );
+ expect(zhText(warned)).toContain("2026-09 预算的 82%");
+ });
+
+ it("carries a ticket's id and title", () => {
+ const done = notice("ticket_done", { ticket: "T-3", title: "Build the site" });
+ expect(enText(done)).toBe("Ticket T-3 (Build the site) is done.");
+ expect(zhText(done)).toBe("工单 T-3(Build the site)已完成。");
+ });
+
+ it("renders nothing for a kind this build does not know", () => {
+ expect(zhText(notice("teleported", { agent: "agent:ceo" }))).toBeNull();
+ });
+});
diff --git a/packages/web/test/channel-stream.test.ts b/packages/web/test/channel-stream.test.ts
new file mode 100644
index 00000000..255568e7
--- /dev/null
+++ b/packages/web/test/channel-stream.test.ts
@@ -0,0 +1,261 @@
+/**
+ * channel-stream.ts unit tests: day separators and sender runs, the unread divider at the read
+ * cursor, which hop counts are worth a chip, which side of the stream a run stands on and
+ * where each of its bubbles falls, day arithmetic for the separators and both paging
+ * decisions — how far the opening load walks back and which day "earlier" fetches — when a
+ * join made elsewhere has to be re-read, and the immutable live append.
+ */
+import { describe, expect, it } from "vitest";
+import type { OrgChannelMessage } from "@prismshadow/penguin-server/api";
+import {
+ INITIAL_DAYS_MAX,
+ INITIAL_MESSAGES,
+ appendMessage,
+ bubbleShape,
+ buildStream,
+ dayKind,
+ earlierDay,
+ hopChipShown,
+ initialDaysToLoad,
+ isOwnRun,
+ joinedElsewhere,
+ lastMessageId,
+ messageCount,
+ shiftDate,
+} from "../src/features/company/channel-stream";
+
+let seq = 0;
+const msg = (sender: string, time: string, hop = 0): OrgChannelMessage => ({
+ id: `msg-${time.slice(0, 19).replace(/[T:]/g, "-")}-${String(++seq).padStart(8, "0")}`,
+ time,
+ sender,
+ hop,
+ text: `${sender} at ${time}`,
+ mentions: [],
+});
+
+describe("buildStream", () => {
+ it("starts each day with a separator, folds one sender's close messages into a run, and keeps system lines apart", () => {
+ const a1 = msg("user:alice", "2026-09-02T10:00:00Z");
+ const a2 = msg("user:alice", "2026-09-02T10:03:00Z");
+ const sys = msg("system", "2026-09-02T10:04:00Z");
+ const a3 = msg("user:alice", "2026-09-02T10:05:00Z");
+ const b1 = msg("agent:ceo", "2026-09-02T10:06:00Z", 1);
+ const items = buildStream([
+ { date: "2026-09-01", messages: [] },
+ { date: "2026-09-02", messages: [a1, a2, sys, a3, b1] },
+ ]);
+ expect(items.map((i) => i.kind)).toEqual(["day", "day", "run", "system", "run", "run"]);
+ expect(items[2]).toMatchObject({ sender: "user:alice", hop: 0, messages: [a1, a2] });
+ expect(items[4]).toMatchObject({ sender: "user:alice", messages: [a3] });
+ expect(items[5]).toMatchObject({ sender: "agent:ceo", hop: 1 });
+ });
+
+ it("breaks a run after the gap, and on a hop change", () => {
+ const a1 = msg("user:alice", "2026-09-02T10:00:00Z");
+ const a2 = msg("user:alice", "2026-09-02T10:06:00Z");
+ const c1 = msg("agent:ceo", "2026-09-02T10:07:00Z", 1);
+ const c2 = msg("agent:ceo", "2026-09-02T10:07:30Z", 2);
+ const items = buildStream([{ date: "2026-09-02", messages: [a1, a2, c1, c2] }]);
+ expect(items.map((i) => (i.kind === "run" ? i.messages.length : i.kind))).toEqual([
+ "day",
+ 1,
+ 1,
+ 1,
+ 1,
+ ]);
+ // A wider gap joins them again.
+ expect(
+ buildStream([{ date: "2026-09-02", messages: [a1, a2] }], { gapMs: 10 * 60_000 }).length,
+ ).toBe(2);
+ });
+
+ it("draws the unread divider before the first message after the cursor, splitting a run", () => {
+ const a1 = msg("user:alice", "2026-09-02T10:00:00Z");
+ const a2 = msg("user:alice", "2026-09-02T10:01:00Z");
+ const a3 = msg("user:alice", "2026-09-02T10:02:00Z");
+ const items = buildStream([{ date: "2026-09-02", messages: [a1, a2, a3] }], {
+ unreadAfterId: a2.id,
+ });
+ expect(items.map((i) => i.kind)).toEqual(["day", "run", "unread", "run"]);
+ expect(items[1]).toMatchObject({ messages: [a1, a2] });
+ expect(items[3]).toMatchObject({ messages: [a3] });
+ });
+
+ it("draws no divider without a cursor, or when everything is read", () => {
+ const a1 = msg("user:alice", "2026-09-02T10:00:00Z");
+ const days = [{ date: "2026-09-02", messages: [a1] }];
+ expect(buildStream(days).some((i) => i.kind === "unread")).toBe(false);
+ expect(buildStream(days, { unreadAfterId: a1.id }).some((i) => i.kind === "unread")).toBe(
+ false,
+ );
+ });
+});
+
+describe("shiftDate and dayKind", () => {
+ it("moves whole days across month and year ends and names today and yesterday", () => {
+ expect(shiftDate("2026-09-01", -1)).toBe("2026-08-31");
+ expect(shiftDate("2026-01-01", -1)).toBe("2025-12-31");
+ expect(shiftDate("2026-12-31", 1)).toBe("2027-01-01");
+ expect(shiftDate("nope", 1)).toBeNull();
+ expect(dayKind("2026-09-02", "2026-09-02")).toBe("today");
+ expect(dayKind("2026-09-01", "2026-09-02")).toBe("yesterday");
+ expect(dayKind("2026-08-20", "2026-09-02")).toBe("other");
+ });
+});
+
+describe("earlierDay", () => {
+ it("picks the newest day older than the earliest loaded, from a newest-first list", () => {
+ const days = ["2026-09-02", "2026-09-01", "2026-08-28"];
+ expect(earlierDay(days, "2026-09-02")).toBe("2026-09-01");
+ expect(earlierDay(days, "2026-09-01")).toBe("2026-08-28");
+ expect(earlierDay(days, "2026-08-28")).toBeNull();
+ // Today has no file yet: the list starts below it.
+ expect(earlierDay(["2026-09-01"], "2026-09-02")).toBe("2026-09-01");
+ });
+});
+
+describe("initialDaysToLoad", () => {
+ const pad = (n: number) => (n < 10 ? `0${n}` : `${n}`);
+ /** A day file of `n` messages, all on that date. */
+ const day = (date: string, n: number) => ({
+ date,
+ messages: Array.from({ length: n }, (_, i) => msg("user:alice", `${date}T10:${pad(i)}:00Z`)),
+ });
+ const days = ["2026-09-02", "2026-09-01", "2026-08-31", "2026-08-28"];
+
+ it("steps back day by day while the opening load is short of messages", () => {
+ expect(initialDaysToLoad(days, "2026-09-02", [day("2026-09-02", 2)], 5)).toBe("2026-09-01");
+ expect(
+ initialDaysToLoad(days, "2026-09-02", [day("2026-09-01", 2), day("2026-09-02", 2)], 5),
+ ).toBe("2026-08-31");
+ });
+
+ it("stops as soon as the load holds what it wanted", () => {
+ expect(initialDaysToLoad(days, "2026-09-02", [day("2026-09-02", 5)], 5)).toBeNull();
+ expect(initialDaysToLoad(days, "2026-09-02", [day("2026-09-02", 9)], 5)).toBeNull();
+ });
+
+ it("walks past today's empty file rather than opening a quiet channel on a blank day", () => {
+ // The whole point: today has no messages, so the first screen comes from earlier days.
+ expect(initialDaysToLoad(days, "2026-09-02", [day("2026-09-02", 0)], 5)).toBe("2026-09-01");
+ });
+
+ it("stops at the start of history", () => {
+ const loaded = [day("2026-08-28", 1), day("2026-09-02", 0)];
+ expect(initialDaysToLoad(days, "2026-09-02", loaded, 30)).toBeNull();
+ // A channel with no day file at all: nothing to walk back to.
+ expect(initialDaysToLoad([], "2026-09-02", [day("2026-09-02", 0)], 30)).toBeNull();
+ });
+
+ it("spends at most its day budget, however little each day held", () => {
+ const loaded = Array.from({ length: INITIAL_DAYS_MAX }, (_, i) =>
+ day(`2026-09-${pad(i + 1)}`, 1),
+ );
+ const wide = [...loaded.map((d) => d.date)].reverse().concat("2026-08-28");
+ expect(initialDaysToLoad(wide, "2026-09-07", loaded, INITIAL_MESSAGES)).toBeNull();
+ // One day file short of the budget it still steps back.
+ expect(initialDaysToLoad(wide, "2026-09-07", loaded.slice(0, -1), INITIAL_MESSAGES)).toBe(
+ "2026-08-28",
+ );
+ });
+
+ it("wants a full screen of messages by default", () => {
+ expect(initialDaysToLoad(days, "2026-09-02", [day("2026-09-02", INITIAL_MESSAGES)])).toBeNull();
+ expect(initialDaysToLoad(days, "2026-09-02", [day("2026-09-02", INITIAL_MESSAGES - 1)])).toBe(
+ "2026-09-01",
+ );
+ });
+});
+
+describe("joinedElsewhere", () => {
+ it("re-reads the detail the moment the listing says the reader joined", () => {
+ expect(joinedElsewhere(false, true, false)).toBe(true);
+ });
+
+ it("stays quiet while the two sources have always disagreed", () => {
+ // The server's own answer, not a join that just happened: re-reading it on every render
+ // would be a refetch loop.
+ expect(joinedElsewhere(true, true, false)).toBe(false);
+ // Nothing is known about the previous listing yet (a channel just opened).
+ expect(joinedElsewhere(null, true, false)).toBe(false);
+ });
+
+ it("stays quiet once the detail agrees, and when membership went the other way", () => {
+ expect(joinedElsewhere(false, true, true)).toBe(false);
+ expect(joinedElsewhere(true, false, true)).toBe(false);
+ expect(joinedElsewhere(false, null, false)).toBe(false);
+ });
+});
+
+describe("appendMessage, lastMessageId and messageCount", () => {
+ it("appends to the day, creates a missing day at the end, and returns the same array for a repeat", () => {
+ const a1 = msg("user:alice", "2026-09-02T10:00:00Z");
+ const a2 = msg("user:alice", "2026-09-02T10:01:00Z");
+ const days = [{ date: "2026-09-02", messages: [a1] }];
+ const next = appendMessage(days, "2026-09-02", a2);
+ expect(next).not.toBe(days);
+ expect(next[0]?.messages).toEqual([a1, a2]);
+ expect(appendMessage(next, "2026-09-02", a2)).toBe(next);
+ const b1 = msg("agent:ceo", "2026-09-03T00:00:10Z");
+ const rolled = appendMessage(next, "2026-09-03", b1);
+ expect(rolled.map((d) => d.date)).toEqual(["2026-09-02", "2026-09-03"]);
+ expect(lastMessageId(rolled)).toBe(b1.id);
+ expect(messageCount(rolled)).toBe(3);
+ expect(lastMessageId([{ date: "2026-09-02", messages: [] }])).toBeNull();
+ });
+});
+
+describe("hopChipShown", () => {
+ it("says nothing about the first hop and marks every chain from the second", () => {
+ // Hop 0 is a person writing, hop 1 an employee answering a trigger: both ordinary.
+ expect(hopChipShown(0)).toBe(false);
+ expect(hopChipShown(1)).toBe(false);
+ expect(hopChipShown(2)).toBe(true);
+ expect(hopChipShown(5)).toBe(true);
+ });
+});
+
+describe("isOwnRun", () => {
+ it("claims the reader's own messages and nobody else's", () => {
+ expect(isOwnRun("user:alice", "alice")).toBe(true);
+ expect(isOwnRun("user:bob", "alice")).toBe(false);
+ // An employee writes as an agent, never as the reader — even when the ids collide.
+ expect(isOwnRun("agent:alice", "alice")).toBe(false);
+ expect(isOwnRun("system", "alice")).toBe(false);
+ expect(isOwnRun("all", "alice")).toBe(false);
+ });
+
+ it("owns nothing while the reader is unknown", () => {
+ // "" is the id before the session has loaded: a malformed `user:` principal must not
+ // start reading as the reader's own message.
+ expect(isOwnRun("user:", "")).toBe(false);
+ expect(isOwnRun("user:alice", "")).toBe(false);
+ });
+});
+
+describe("bubbleShape", () => {
+ const run = (sender: string, n: number) => ({
+ sender,
+ messages: Array.from({ length: n }, (_, i) => msg(sender, `2026-09-02T10:0${i}:00Z`)),
+ });
+
+ it("marks the first and the last bubble of a run, on the side that wrote it", () => {
+ const others = run("agent:ceo", 3);
+ expect(bubbleShape(others, 0, "alice")).toEqual({ own: false, first: true, last: false });
+ expect(bubbleShape(others, 1, "alice")).toEqual({ own: false, first: false, last: false });
+ expect(bubbleShape(others, 2, "alice")).toEqual({ own: false, first: false, last: true });
+ const mine = run("user:alice", 2);
+ expect(bubbleShape(mine, 0, "alice")).toEqual({ own: true, first: true, last: false });
+ expect(bubbleShape(mine, 1, "alice")).toEqual({ own: true, first: false, last: true });
+ });
+
+ it("makes a run of one both its first and its last bubble", () => {
+ // The lone bubble carries the name, the avatar and the squared corner all at once.
+ expect(bubbleShape(run("user:bob", 1), 0, "alice")).toEqual({
+ own: false,
+ first: true,
+ last: true,
+ });
+ });
+});
diff --git a/packages/web/test/chart-view.test.ts b/packages/web/test/chart-view.test.ts
new file mode 100644
index 00000000..a0284134
--- /dev/null
+++ b/packages/web/test/chart-view.test.ts
@@ -0,0 +1,14 @@
+/**
+ * chart-view.ts unit tests: the tone an employee's live state takes. The canvas's pan and
+ * zoom arithmetic is covered by canvas-view.test.ts.
+ */
+import { describe, expect, it } from "vitest";
+import { employeeStateTone } from "../src/features/company/chart-view";
+
+describe("employeeStateTone", () => {
+ it("picks busy for running, attention for a budget pause, success on the desk", () => {
+ expect(employeeStateTone("running")).toBe("busy");
+ expect(employeeStateTone("paused")).toBe("attention");
+ expect(employeeStateTone("idle")).toBe("success");
+ });
+});
diff --git a/packages/web/test/company-beta.test.ts b/packages/web/test/company-beta.test.ts
new file mode 100644
index 00000000..87a4850f
--- /dev/null
+++ b/packages/web/test/company-beta.test.ts
@@ -0,0 +1,119 @@
+/**
+ * Company mode's two beta marks (features/company/beta-badge.tsx).
+ *
+ * The tag, on 「公司」 in the work-mode switch: it has to be legible, it has to reach a screen
+ * reader through the option's name, and it must not move the switch around — which is the whole
+ * reason it is positioned out of flow rather than laid out beside the word.
+ *
+ * The notice, the once-only sentence behind it: the first switch into the mode in a browser
+ * raises it, every later one does not, and a storage that is absent or refuses to answer raises
+ * nothing rather than raising it forever.
+ */
+import { describe, expect, it } from "vitest";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import {
+ BETA_NOTICE_KEY,
+ BetaBadge,
+ markBetaNoticeShown,
+ shouldShowBetaNotice,
+} from "../src/features/company/beta-badge";
+import { Segmented } from "../src/components/ui/segmented";
+import { zh } from "../src/lib/strings";
+
+/** The in-memory stand-in for localStorage (this package's vitest runs in Node, which has none). */
+function memoryStorage(initial: Record<string, string> = {}) {
+ const map = new Map(Object.entries(initial));
+ return {
+ getItem: (key: string): string | null => map.get(key) ?? null,
+ setItem: (key: string, value: string): void => {
+ map.set(key, value);
+ },
+ read: (key: string): string | null => map.get(key) ?? null,
+ };
+}
+
+/** A browser with site data blocked: every access throws rather than returning null. */
+const throwingStorage = {
+ getItem(): string | null {
+ throw new Error("access denied");
+ },
+ setItem(): void {
+ throw new Error("access denied");
+ },
+};
+
+describe("shouldShowBetaNotice", () => {
+ it("is owed on a browser that has never seen it, and not after it is marked", () => {
+ const storage = memoryStorage();
+ expect(shouldShowBetaNotice(storage)).toBe(true);
+ markBetaNoticeShown(storage);
+ expect(storage.read(BETA_NOTICE_KEY)).toBe("1");
+ expect(shouldShowBetaNotice(storage)).toBe(false);
+ });
+
+ it("stays owed while the flag holds anything but the mark", () => {
+ expect(shouldShowBetaNotice(memoryStorage({ [BETA_NOTICE_KEY]: "" }))).toBe(true);
+ expect(shouldShowBetaNotice(memoryStorage({ [BETA_NOTICE_KEY]: "true" }))).toBe(true);
+ expect(shouldShowBetaNotice(memoryStorage({ [BETA_NOTICE_KEY]: "0" }))).toBe(true);
+ });
+
+ it("answers no when storage throws, so the notice cannot repeat on every switch", () => {
+ expect(shouldShowBetaNotice(throwingStorage)).toBe(false);
+ expect(() => markBetaNoticeShown(throwingStorage)).not.toThrow();
+ });
+
+ it("answers no when there is no storage at all (Node, no localStorage)", () => {
+ expect(shouldShowBetaNotice()).toBe(false);
+ expect(() => markBetaNoticeShown()).not.toThrow();
+ });
+});
+
+/** The work-mode switch as the sidebar builds it, with and without the tag on 「公司」. */
+function workModeSwitch(withBadge: boolean): string {
+ return renderToStaticMarkup(
+ createElement(Segmented<"dev" | "company">, {
+ options: [
+ { value: "dev", label: zh.company.modeDev },
+ {
+ value: "company",
+ label: zh.company.modeCompany,
+ ...(withBadge
+ ? { badge: { node: createElement(BetaBadge), name: zh.company.beta } }
+ : {}),
+ },
+ ],
+ value: "dev",
+ onChange: () => {},
+ cols: 2,
+ }),
+ );
+}
+
+describe("the beta tag on the work-mode switch", () => {
+ it("names itself in the option's accessible name, and only that option's", () => {
+ const markup = workModeSwitch(true);
+ expect(markup).toContain(`aria-label="${zh.company.modeCompany} · ${zh.company.beta}"`);
+ // The other option keeps the label's own text as its name: an aria-label is only spent
+ // where there is something the visible text does not already say.
+ expect(markup).not.toContain(`aria-label="${zh.company.modeDev}"`);
+ });
+
+ it("is a superscript, so the option's height and the control's size do not move", () => {
+ const markup = workModeSwitch(true);
+ expect(markup).toContain("absolute");
+ // Out of flow means out of the name too, so the tag's text is hidden rather than announced
+ // twice beside the suffix above.
+ expect(markup).toContain('aria-hidden="true"');
+ expect(markup).toContain(zh.company.beta);
+ // The tooltip is the one thing the tag still says on its own.
+ expect(markup).toContain(`title="${zh.company.betaTitle}"`);
+ });
+
+ it("costs an option without one nothing", () => {
+ const markup = workModeSwitch(false);
+ expect(markup).not.toContain("aria-label");
+ expect(markup).not.toContain("absolute");
+ expect(markup).not.toContain(zh.company.beta);
+ });
+});
diff --git a/packages/web/test/company-click-targets.test.ts b/packages/web/test/company-click-targets.test.ts
new file mode 100644
index 00000000..098cf2fe
--- /dev/null
+++ b/packages/web/test/company-click-targets.test.ts
@@ -0,0 +1,158 @@
+/**
+ * The company pages carry no whole-area click targets.
+ *
+ * A card, a row, a heading or a panel is never itself the link — but a row's or a card's *title*
+ * is: the title renders as a text button that opens what it names, and the surface around it
+ * stays inert (on the ticket board it stays the drag handle). A row with no title of its own
+ * carries a small named icon button instead. What the rule rules out is the silently clickable
+ * surface, which swallows the controls living inside it and leaves a reader guessing what a
+ * click will do. It came out of the company pages, where a whole card, a whole row and a bare
+ * heading had each grown a click of its own.
+ *
+ * The three shapes that smell of it and are mechanically visible: an `onClick` on a host element
+ * that is not a control, a `role="button"` / `role="link"` on a container, and a `cursor-pointer`
+ * on a surface that is not itself a control. A drift back into any of them is invisible in review
+ * — the attribute is just one more line in a long element — so it is parsed rather than
+ * remembered, with the TypeScript parser, since whether the handler sits on the `<div>` or on the
+ * `<button>` inside it is a question a regex over the file cannot answer.
+ *
+ * A `<button>` around a title is a control host and passes, which is the point — the check is
+ * about where the handler sits, not about whether a surface navigates at all. Out of its reach,
+ * and still on the rule: a `<button>` that wraps a whole row (nothing in the syntax says how much
+ * of the row it covers), and a click handler passed down as a prop. Those are on the reviewer.
+ */
+import { describe, expect, it } from "vitest";
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import ts from "typescript";
+
+const SRC = fileURLToPath(new URL("../src", import.meta.url));
+
+/**
+ * The company modules swept for the rule, relative to `src`. Every page whose surfaces have been
+ * gone through belongs here; add one as it is swept, so the list says what has been checked rather
+ * than implying the whole feature has.
+ */
+const MODULES = [
+ "features/company/calendar-page.tsx",
+ "features/company/chart-card.tsx",
+ "features/company/channel-view.tsx",
+ "features/company/finance-page.tsx",
+ "features/company/handbook-explorer.tsx",
+ "features/company/handbook-page.tsx",
+ "features/company/org-chart-page.tsx",
+ "features/company/org-layout.tsx",
+ "features/company/overview-page.tsx",
+ "features/company/shared.tsx",
+ "features/company/ticket-dialog.tsx",
+ "features/company/tickets-page.tsx",
+];
+
+/** Host elements that are controls already: a click on one of these is what the element is for. */
+const CONTROLS = new Set([
+ "a",
+ "button",
+ "input",
+ "label",
+ "option",
+ "select",
+ "summary",
+ "textarea",
+]);
+
+/**
+ * Declared exceptions: an `onClick` on a container that delegates for the interactive elements
+ * *inside* it rather than being a target of its own — the handbook's rendered Markdown catches
+ * clicks on the anchors it drew, so a relative link opens in the pane instead of a new tab. Keyed
+ * by module and by the handler's own text, both of which survive the line moving.
+ */
+const DELEGATES = new Map<string, ReadonlySet<string>>([
+ ["features/company/handbook-page.tsx", new Set(["onBodyClick"])],
+]);
+
+function openingElement(node: ts.Node): ts.JsxOpeningLikeElement | null {
+ if (ts.isJsxSelfClosingElement(node) || ts.isJsxOpeningElement(node)) return node;
+ return null;
+}
+
+/** A host element is a lowercase tag; `<OrgSection>` is a component and owns its own markup. */
+const isHostElement = (el: ts.JsxOpeningLikeElement): boolean =>
+ /^[a-z]/.test(el.tagName.getText());
+
+function attribute(el: ts.JsxOpeningLikeElement, name: string): ts.JsxAttribute | undefined {
+ return el.attributes.properties.find(
+ (attr): attr is ts.JsxAttribute => ts.isJsxAttribute(attr) && attr.name.getText() === name,
+ );
+}
+
+/**
+ * Every literal chunk of a `className`. A template literal's interpolations are skipped: a class
+ * reached through a shared constant is that constant's business, and the constants themselves are
+ * in these same modules.
+ */
+function literalChunks(node: ts.Node, out: string[] = []): string[] {
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) out.push(node.text);
+ else if (ts.isTemplateExpression(node)) {
+ out.push(node.head.text);
+ for (const span of node.templateSpans) out.push(span.literal.text);
+ } else {
+ // The callback must return nothing: forEachChild stops at the first truthy result.
+ ts.forEachChild(node, (child) => {
+ literalChunks(child, out);
+ });
+ }
+ return out;
+}
+
+/** Whole-area click targets, as "relative/path:line <tag> — what it is". */
+function findWholeAreaTargets(): string[] {
+ const found: string[] = [];
+ for (const rel of MODULES) {
+ const path = `${SRC}/${rel}`;
+ const source = ts.createSourceFile(
+ path,
+ readFileSync(path, "utf8"),
+ ts.ScriptTarget.Latest,
+ /* setParentNodes */ true,
+ ts.ScriptKind.TSX,
+ );
+ const delegates = DELEGATES.get(rel) ?? new Set<string>();
+ const report = (el: ts.JsxOpeningLikeElement, why: string) => {
+ const line = source.getLineAndCharacterOfPosition(el.getStart(source)).line + 1;
+ found.push(`${rel}:${line} <${el.tagName.getText()}> — ${why}`);
+ };
+ const visit = (node: ts.Node): void => {
+ const el = openingElement(node);
+ if (el !== null && isHostElement(el)) {
+ const tag = el.tagName.getText();
+ const onClick = attribute(el, "onClick");
+ if (onClick !== undefined && !CONTROLS.has(tag)) {
+ const handler = onClick.initializer?.getText() ?? "";
+ const named = handler.replaceAll(/[{}]/g, "").trim();
+ if (!delegates.has(named)) report(el, "onClick on a surface that is not a control");
+ }
+ const role = attribute(el, "role")?.initializer?.getText();
+ if ((role === '"button"' || role === '"link"') && !CONTROLS.has(tag)) {
+ report(el, `${role} on a container`);
+ }
+ const className = attribute(el, "className");
+ if (
+ className?.initializer !== undefined &&
+ !CONTROLS.has(tag) &&
+ literalChunks(className.initializer).some((chunk) => /\bcursor-pointer\b/.test(chunk))
+ ) {
+ report(el, "cursor-pointer on a surface that is not a control");
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ }
+ return found.sort();
+}
+
+describe("company pages", () => {
+ it("navigate through named controls, never through a whole card, row or panel", () => {
+ expect(findWholeAreaTargets()).toEqual([]);
+ });
+});
diff --git a/packages/web/test/company-mode-write.test.ts b/packages/web/test/company-mode-write.test.ts
new file mode 100644
index 00000000..fe87418a
--- /dev/null
+++ b/packages/web/test/company-mode-write.test.ts
@@ -0,0 +1,87 @@
+/**
+ * company-mode-write.ts unit tests: the master switch in System settings › Server applies on the
+ * flip, so the write is the whole save path and there is no Save button to retry with. Both
+ * outcomes are pinned here — the request a flip sends and the value it settles on, and the
+ * revert-with-a-reason that a rejected write has to produce, since a switch left showing a state
+ * the server does not hold is the failure mode this replaced.
+ *
+ * vitest runs node-only in this package (`environment: "node"`, no jsdom), which is why the
+ * sequence lives in its own module and the component is the thin caller.
+ */
+import { describe, expect, it } from "vitest";
+import type {
+ ServerSettings,
+ ServerSettingsResponse,
+ ServerSettingsUpdateRequest,
+} from "@prismshadow/penguin-server/api";
+import { writeCompanyMode } from "../src/features/settings/company-mode-write";
+
+const settings = (companyMode: boolean): ServerSettings => ({
+ proxyForApp: true,
+ proxyForAgent: true,
+ proxyUrl: null,
+ attachmentMaxMb: 100,
+ attachmentTotalMb: 500,
+ companyMode,
+});
+
+/** Records what the switch sent and answers with the server's stored settings. */
+const recorder = (answer: boolean) => {
+ const sent: ServerSettingsUpdateRequest[] = [];
+ return {
+ sent,
+ put: (body: ServerSettingsUpdateRequest): Promise<ServerSettingsResponse> => {
+ sent.push(body);
+ return Promise.resolve({ settings: settings(answer) });
+ },
+ };
+};
+
+const describeError = (error: unknown) => `described: ${String(error)}`;
+
+describe("writeCompanyMode", () => {
+ it("sends the flipped value alone and settles on what the server answers", async () => {
+ const api = recorder(true);
+ const result = await writeCompanyMode(true, false, { put: api.put, describeError });
+ // Only the one field: every other server setting keeps its stored value.
+ expect(api.sent).toEqual([{ companyMode: true }]);
+ expect(result).toEqual({ status: "applied", companyMode: true });
+ });
+
+ it("turning it off is the same single write", async () => {
+ const api = recorder(false);
+ const result = await writeCompanyMode(false, true, { put: api.put, describeError });
+ expect(api.sent).toEqual([{ companyMode: false }]);
+ expect(result).toEqual({ status: "applied", companyMode: false });
+ });
+
+ it("adopts the server's answer rather than the value that was asked for", async () => {
+ // A server that stored something else is what the switch must show; assuming the request
+ // won would leave the knob lying about the server's state until the next reload.
+ const api = recorder(false);
+ const result = await writeCompanyMode(true, false, { put: api.put, describeError });
+ expect(result).toEqual({ status: "applied", companyMode: false });
+ });
+
+ it("reverts to the stored value and carries the described reason when the write fails", async () => {
+ const result = await writeCompanyMode(true, false, {
+ put: () => Promise.reject(new Error("403")),
+ describeError,
+ });
+ expect(result).toEqual({
+ status: "failed",
+ revertTo: false,
+ error: "described: Error: 403",
+ });
+ });
+
+ it("reverts to on, not to off, when turning it off fails", async () => {
+ // The revert target is the stored value, never a default: a failed turn-off on an enabled
+ // server has to leave the switch on.
+ const result = await writeCompanyMode(false, true, {
+ put: () => Promise.reject(new Error("boom")),
+ describeError,
+ });
+ expect(result).toMatchObject({ status: "failed", revertTo: true });
+ });
+});
diff --git a/packages/web/test/company-nav.test.ts b/packages/web/test/company-nav.test.ts
new file mode 100644
index 00000000..cb25dd8a
--- /dev/null
+++ b/packages/web/test/company-nav.test.ts
@@ -0,0 +1,254 @@
+/**
+ * company-nav.ts and work-mode.ts unit tests: the company-mode nav manifest (the six pages
+ * in rendered order, each with a zh label, an en label and a glyph — the sidebar, the rail
+ * and the router all derive their rows from it), the `<projectId>/<orgId>` key, the
+ * `/org/:projectId/:orgId/<page>` and `…/channels/:channelId` grammars, where `/org` lands
+ * without an organization, where a freshly created one opens and which key the shell becomes
+ * current at when it does, the switcher's grouping by
+ * Project, and the localStorage mirrors of the mode and the last organization (injectable
+ * storage, forgettable, degrading to the defaults on anything unexpected).
+ */
+import { describe, expect, it } from "vitest";
+import {
+ COMPANY_NAV_KEYS,
+ groupOrganizationsByProject,
+ isOrgRoute,
+ orgChannelPath,
+ orgCreatedPath,
+ orgCreatedTarget,
+ orgKey,
+ orgPagePath,
+ parseOrgKey,
+ resolveOrgLanding,
+} from "../src/features/company/company-nav";
+import { DEFAULT_CHANNEL_ID } from "../src/features/company/channel-list";
+import { COMPANY_NAV_ICONS } from "../src/features/company/company-nav-icons";
+import {
+ LAST_ORG_KEY,
+ WORK_MODE_KEY,
+ clearLastOrgKey,
+ initialLastOrgKey,
+ initialWorkMode,
+ storeLastOrgKey,
+ storeWorkMode,
+} from "../src/lib/work-mode";
+import type { WorkModeStorage } from "../src/lib/work-mode";
+import { zh } from "../src/lib/strings";
+import { en } from "../src/lib/strings-en";
+
+function memStorage(): WorkModeStorage & { map: Map<string, string> } {
+ const map = new Map<string, string>();
+ return {
+ map,
+ getItem: (k) => map.get(k) ?? null,
+ setItem: (k, v) => void map.set(k, v),
+ removeItem: (k) => void map.delete(k),
+ };
+}
+
+describe("COMPANY_NAV_KEYS", () => {
+ it("lists the six organization pages in the spec's order, channels not among them", () => {
+ expect([...COMPANY_NAV_KEYS]).toEqual([
+ "overview",
+ "chart",
+ "calendar",
+ "tickets",
+ "finance",
+ "handbook",
+ ]);
+ // Channels are the sidebar's own list, the way conversations are in development mode.
+ expect(COMPANY_NAV_KEYS).not.toContain("chat");
+ expect(COMPANY_NAV_KEYS).not.toContain("channels");
+ });
+
+ it("every entry has the spec's zh and en names and a glyph", () => {
+ // The bilingual table of the prototype spec, verbatim.
+ const expected = {
+ overview: ["概览", "Overview"],
+ chart: ["组织图", "Org Chart"],
+ calendar: ["日历", "Calendar"],
+ tickets: ["工单", "Tickets"],
+ finance: ["财务", "Finance"],
+ handbook: ["手册", "Handbook"],
+ } as const;
+ for (const key of COMPANY_NAV_KEYS) {
+ expect(zh.nav.org[key]).toBe(expected[key][0]);
+ expect(en.nav.org[key]).toBe(expected[key][1]);
+ expect(COMPANY_NAV_ICONS[key]).toBeTruthy();
+ }
+ });
+
+ it("the mode switch's two options exist in both languages and differ", () => {
+ for (const dict of [zh, en]) {
+ expect(dict.company.modeDev).toBeTruthy();
+ expect(dict.company.modeCompany).toBeTruthy();
+ expect(dict.company.modeDev).not.toBe(dict.company.modeCompany);
+ }
+ });
+});
+
+describe("org keys and paths", () => {
+ it("round-trips a key through parseOrgKey", () => {
+ expect(orgKey("p1", "acme")).toBe("p1/acme");
+ expect(parseOrgKey("p1/acme")).toEqual({ projectId: "p1", orgId: "acme" });
+ });
+
+ it("rejects anything that is not exactly two non-empty segments", () => {
+ for (const raw of [null, undefined, "", "p1", "/acme", "p1/", "p1/acme/extra"]) {
+ expect(parseOrgKey(raw)).toBeNull();
+ }
+ });
+
+ it("builds page paths under the /org prefix, encoding the ids", () => {
+ expect(orgPagePath("p1", "acme", "tickets")).toBe("/org/p1/acme/tickets");
+ expect(orgPagePath("alice-proj", "a b", "overview")).toBe("/org/alice-proj/a%20b/overview");
+ expect(orgPagePath("p1", "acme", "handbook")).toBe("/org/p1/acme/handbook");
+ });
+
+ it("builds a channel path with the channel as its own segment", () => {
+ expect(orgChannelPath("p1", "acme", DEFAULT_CHANNEL_ID)).toBe(
+ "/org/p1/acme/channels/default_channel",
+ );
+ expect(orgChannelPath("p1", "acme", "site")).toBe("/org/p1/acme/channels/site");
+ expect(orgChannelPath("alice-proj", "a b", "site")).toBe("/org/alice-proj/a%20b/channels/site");
+ });
+
+ // An organization opens on its overview, not on a channel: the switcher's pick, `/org`'s
+ // redirect and the router's index route all land there, and a channel is reached from the
+ // sidebar's own list.
+ it("makes the overview the first page of the six, which is where an organization opens", () => {
+ expect(COMPANY_NAV_KEYS[0]).toBe("overview");
+ expect(orgPagePath("p1", "acme", "overview")).toBe("/org/p1/acme/overview");
+ });
+
+ it("lands a newly created organization in the CEO's desk, else on its overview", () => {
+ expect(orgCreatedPath({ projectId: "p1", orgId: "acme", ceoDeskSessionId: "s-1" })).toBe(
+ "/chat/s-1",
+ );
+ expect(orgCreatedPath({ projectId: "p1", orgId: "acme" })).toBe("/org/p1/acme/overview");
+ });
+
+ // The desk session is NOT one of the organization's own routes, so nothing on the way there
+ // would tell the shell which organization it is now inside: the key travels with the path.
+ it("names the organization the shell becomes current at beside the path it opens", () => {
+ expect(orgCreatedTarget({ projectId: "p1", orgId: "acme", ceoDeskSessionId: "s-1" })).toEqual({
+ key: "p1/acme",
+ path: "/chat/s-1",
+ });
+ expect(orgCreatedTarget({ projectId: "p1", orgId: "acme" })).toEqual({
+ key: "p1/acme",
+ path: "/org/p1/acme/overview",
+ });
+ });
+
+ // The key is the shell's own grammar, not the path's: a Project or an organization whose id
+ // needs escaping in a URL is still keyed by its plain ids, which is what parseOrgKey reads
+ // back and what the organization list is searched by.
+ it("keys the created organization by its plain ids while the path escapes them", () => {
+ const target = orgCreatedTarget({ projectId: "alice proj", orgId: "acme" });
+ expect(target.key).toBe("alice proj/acme");
+ expect(parseOrgKey(target.key)).toEqual({ projectId: "alice proj", orgId: "acme" });
+ expect(target.path).toBe("/org/alice%20proj/acme/overview");
+ });
+
+ it("tells organization routes from the shared chat route", () => {
+ expect(isOrgRoute("/org")).toBe(true);
+ expect(isOrgRoute("/org/p1/acme/overview")).toBe(true);
+ expect(isOrgRoute("/org/p1/acme/channels/site")).toBe(true);
+ expect(isOrgRoute("/organizations")).toBe(false);
+ expect(isOrgRoute("/chat/abc")).toBe(false);
+ });
+});
+
+describe("resolveOrgLanding", () => {
+ const orgs = [
+ { projectId: "p1", orgId: "a" },
+ { projectId: "p2", orgId: "b" },
+ { projectId: "p2", orgId: "c" },
+ ];
+
+ it("returns the organization last opened when it still exists", () => {
+ expect(resolveOrgLanding("p2/c", orgs, "p1")).toEqual({ projectId: "p2", orgId: "c" });
+ });
+
+ it("falls back to the current Project's first organization, then to the first anywhere", () => {
+ expect(resolveOrgLanding("p9/gone", orgs, "p2")).toEqual({ projectId: "p2", orgId: "b" });
+ expect(resolveOrgLanding(null, orgs, "p3")).toEqual({ projectId: "p1", orgId: "a" });
+ expect(resolveOrgLanding(null, orgs, null)).toEqual({ projectId: "p1", orgId: "a" });
+ });
+
+ it("is null with no organization at all — the empty landing's cue", () => {
+ expect(resolveOrgLanding("p1/a", [], "p1")).toBeNull();
+ });
+});
+
+describe("groupOrganizationsByProject", () => {
+ it("groups in the Project list's order and drops Projects with no organization", () => {
+ const orgs = [
+ { projectId: "p2", orgId: "b" },
+ { projectId: "p1", orgId: "a" },
+ { projectId: "p2", orgId: "c" },
+ { projectId: "stale", orgId: "z" },
+ ];
+ expect(groupOrganizationsByProject(orgs, ["p1", "p2", "p3"])).toEqual([
+ { projectId: "p1", organizations: [{ projectId: "p1", orgId: "a" }] },
+ {
+ projectId: "p2",
+ organizations: [
+ { projectId: "p2", orgId: "b" },
+ { projectId: "p2", orgId: "c" },
+ ],
+ },
+ ]);
+ });
+});
+
+describe("work-mode storage mirrors", () => {
+ it("defaults to development with nothing stored, and only an explicit company switches", () => {
+ const s = memStorage();
+ expect(initialWorkMode(s)).toBe("dev");
+ storeWorkMode("company", s);
+ expect(s.map.get(WORK_MODE_KEY)).toBe("company");
+ expect(initialWorkMode(s)).toBe("company");
+ s.map.set(WORK_MODE_KEY, "COMPANY");
+ expect(initialWorkMode(s)).toBe("dev");
+ });
+
+ it("keeps only a well-formed last organization key", () => {
+ const s = memStorage();
+ expect(initialLastOrgKey(s)).toBeNull();
+ storeLastOrgKey("p1/acme", s);
+ expect(s.map.get(LAST_ORG_KEY)).toBe("p1/acme");
+ expect(initialLastOrgKey(s)).toBe("p1/acme");
+ s.map.set(LAST_ORG_KEY, "garbage");
+ expect(initialLastOrgKey(s)).toBeNull();
+ });
+
+ // The organization it named was deleted: the mirror is dropped, not overwritten, so the
+ // next reload starts with no remembered organization at all.
+ it("forgets the last organization key outright", () => {
+ const s = memStorage();
+ storeLastOrgKey("p1/acme", s);
+ clearLastOrgKey(s);
+ expect(s.map.has(LAST_ORG_KEY)).toBe(false);
+ expect(initialLastOrgKey(s)).toBeNull();
+ });
+
+ it("throwing storage degrades to the defaults instead of escaping", () => {
+ const broken: WorkModeStorage = {
+ getItem: () => {
+ throw new Error("denied");
+ },
+ setItem: () => {
+ throw new Error("denied");
+ },
+ removeItem: () => {
+ throw new Error("denied");
+ },
+ };
+ expect(() => storeWorkMode("company", broken)).not.toThrow();
+ expect(() => clearLastOrgKey(broken)).not.toThrow();
+ expect(initialWorkMode(broken)).toBe("dev");
+ expect(initialLastOrgKey(broken)).toBeNull();
+ });
+});
diff --git a/packages/web/test/company-store.test.ts b/packages/web/test/company-store.test.ts
new file mode 100644
index 00000000..eb1ee0d0
--- /dev/null
+++ b/packages/web/test/company-store.test.ts
@@ -0,0 +1,378 @@
+/**
+ * state/company.tsx unit tests: the company store's routing of the scheduler's events (the
+ * per-channel counters of the open organization and the totals the sidebar badges read, the
+ * version bump each family causes, and what a local read mark clears), the open ticket every
+ * company surface shares (the back stack a parent or a child pushes, and what closes it), what
+ * it forgets when the organization list comes back without the organization it is aimed at,
+ * and the
+ * user-channel forwarding in state/sessions.tsx's applyUserEvent — a company event reaches
+ * every subscriber, and a work run refreshes the session list of the Project it belongs to.
+ */
+import { describe, expect, it, vi } from "vitest";
+import type {
+ CompanyServerEvent,
+ OrgChannelItem,
+ OrgChannelMessage,
+ OrganizationSummary,
+} from "@prismshadow/penguin-server/api";
+import { createCompanyStore, isCompanyEvent, subscribeCompanyEvents } from "../src/state/company";
+import { applyUserEvent, createSessionsStore } from "../src/state/sessions";
+
+const message = (over: Partial<OrgChannelMessage> = {}): OrgChannelMessage => ({
+ id: "m-1",
+ time: "2026-09-02T00:00:00Z",
+ sender: "agent:ceo",
+ hop: 0,
+ text: "hello",
+ mentions: [],
+ ...over,
+});
+
+const posted = (
+ over: Partial<OrgChannelMessage> = {},
+ channelId = "default_channel",
+): CompanyServerEvent => ({
+ type: "org_channel",
+ projectId: "p1",
+ orgId: "acme",
+ channelId,
+ message: message(over),
+});
+
+const channel = (over: Partial<OrgChannelItem> = {}): OrgChannelItem => ({
+ channelId: "default_channel",
+ name: "All hands",
+ purpose: "",
+ everyone: true,
+ archived: false,
+ createdBy: "system",
+ createdAt: "2026-09-02T00:00:00Z",
+ memberCount: 2,
+ isMember: true,
+ unread: 0,
+ mentionsMe: 0,
+ lastMessageAt: null,
+ ...over,
+});
+
+describe("isCompanyEvent", () => {
+ it("recognizes the four organization families and nothing else", () => {
+ expect(
+ isCompanyEvent({
+ type: "org_run",
+ projectId: "p",
+ orgId: "o",
+ agentId: "a",
+ sessionId: "s",
+ kind: "event",
+ }),
+ ).toBe(true);
+ expect(isCompanyEvent(posted())).toBe(true);
+ expect(
+ isCompanyEvent({
+ type: "org_ticket",
+ projectId: "p",
+ orgId: "o",
+ ticketId: "t",
+ change: "moved",
+ }),
+ ).toBe(true);
+ expect(
+ isCompanyEvent({
+ type: "org_budget",
+ projectId: "p",
+ orgId: "o",
+ agentId: "a",
+ state: "warned",
+ ratio: 0.8,
+ }),
+ ).toBe(true);
+ expect(isCompanyEvent({ type: "hello" })).toBe(false);
+ expect(isCompanyEvent({ type: "web_updated", rev: "1" })).toBe(false);
+ });
+});
+
+describe("company store event routing", () => {
+ it("counts unread and @me per channel of the open organization only, never the user's own", () => {
+ const store = createCompanyStore();
+ store.getState().applyCompanyEvent(posted(), "alice");
+ // Nothing is open yet: no counter moves, the message version does.
+ expect(store.getState().channelUnread).toBe(0);
+ expect(store.getState().versions.messages).toBe(1);
+
+ store.setState({
+ currentOrgKey: "p1/acme",
+ channels: [channel(), channel({ channelId: "site", name: "Site", everyone: false })],
+ channelUnread: 0,
+ channelMentions: 0,
+ });
+ store.getState().applyCompanyEvent(posted({ id: "m-2" }), "alice");
+ store.getState().applyCompanyEvent(posted({ id: "m-3", mentions: ["user:alice"] }), "alice");
+ // `all` is not a personal mention: the server's listing counts only `user:<id>`, and the
+ // optimistic bump has to agree with it or the badge jumps on the next refresh.
+ store.getState().applyCompanyEvent(posted({ id: "m-4", mentions: ["all"] }), "alice");
+ store
+ .getState()
+ .applyCompanyEvent(posted({ id: "m-5", sender: "user:alice", mentions: ["all"] }), "alice");
+ store.getState().applyCompanyEvent(posted({ id: "m-6" }, "site"), "alice");
+ expect(store.getState().channels?.map((c) => c.unread)).toEqual([3, 1]);
+ expect(store.getState().channelUnread).toBe(4);
+ expect(store.getState().channelMentions).toBe(1);
+
+ // Another organization's message moves the version, not this organization's counters.
+ store.getState().applyCompanyEvent({ ...posted({ id: "m-7" }), orgId: "other" }, "alice");
+ expect(store.getState().channelUnread).toBe(4);
+ expect(store.getState().versions.messages).toBe(7);
+
+ // Reading one channel clears that channel alone.
+ store.getState().markChannelRead("default_channel");
+ expect(store.getState().channelUnread).toBe(1);
+ expect(store.getState().channelMentions).toBe(0);
+ });
+
+ it("leaves a channel the user is not in — and one it does not know — out of the badge", () => {
+ const store = createCompanyStore();
+ store.setState({
+ currentOrgKey: "p1/acme",
+ channels: [channel({ channelId: "site", name: "Site", everyone: false, isMember: false })],
+ });
+ store.getState().applyCompanyEvent(posted({ id: "m-2" }, "site"), "alice");
+ store.getState().applyCompanyEvent(posted({ id: "m-3" }, "unknown_channel"), "alice");
+ expect(store.getState().channels?.[0]?.unread).toBe(0);
+ expect(store.getState().channelUnread).toBe(0);
+ // Both messages still moved the version, which is what re-reads the listing.
+ expect(store.getState().versions.messages).toBe(2);
+ });
+
+ it("drops the open organization's channels and roster when another one is opened", () => {
+ const store = createCompanyStore();
+ store.setState({
+ currentOrgKey: "p1/acme",
+ channels: [channel({ unread: 3 })],
+ channelUnread: 3,
+ orgChart: { ceoAgentId: "ceo", employees: [] },
+ orgChartError: "boom",
+ });
+ store.getState().setCurrentOrg("p1/other");
+ expect(store.getState().channels).toBeNull();
+ expect(store.getState().channelUnread).toBe(0);
+ // The 工位 group's roster belongs to the organization it was read for.
+ expect(store.getState().orgChart).toBeNull();
+ expect(store.getState().orgChartError).toBeNull();
+ });
+
+ it("bumps the version of each family, and the organization list for the ones that change a summary", () => {
+ const store = createCompanyStore();
+ store.getState().applyCompanyEvent(
+ {
+ type: "org_run",
+ projectId: "p",
+ orgId: "o",
+ agentId: "a",
+ sessionId: "s",
+ kind: "event",
+ },
+ null,
+ );
+ store
+ .getState()
+ .applyCompanyEvent(
+ { type: "org_ticket", projectId: "p", orgId: "o", ticketId: "t", change: "moved" },
+ null,
+ );
+ store
+ .getState()
+ .applyCompanyEvent(
+ { type: "org_budget", projectId: "p", orgId: "o", agentId: "a", state: "paused", ratio: 1 },
+ null,
+ );
+ expect(store.getState().versions).toEqual({
+ orgs: 3,
+ messages: 0,
+ tickets: 1,
+ runs: 1,
+ budget: 1,
+ });
+ });
+});
+
+/** One organization as the list carries it; only the two ids matter to the checks below. */
+const summary = (projectId: string, orgId: string): OrganizationSummary => ({
+ projectId,
+ orgId,
+ name: orgId,
+ mission: "",
+ status: "active",
+ employeeCount: 0,
+ runningCount: 0,
+ pausedCount: 0,
+ openTickets: 0,
+ blockedTickets: 0,
+ createdBy: "user:alice",
+ spend: { period: "2026-09", cost: 0 },
+});
+
+describe("forgetting an organization the list no longer holds", () => {
+ it("drops the open organization and the remembered one, and the channels read for it", () => {
+ const store = createCompanyStore();
+ store.setState({
+ organizations: [summary("p1", "other")],
+ orgsLoaded: true,
+ orgsPartial: false,
+ currentOrgKey: "p1/acme",
+ lastOrgKey: "p1/acme",
+ channels: [channel({ unread: 3 })],
+ channelUnread: 3,
+ });
+ store.getState().forgetMissingOrganizations();
+ expect(store.getState().currentOrgKey).toBeNull();
+ expect(store.getState().lastOrgKey).toBeNull();
+ // The listing belonged to the organization that is gone: a retry would only 404.
+ expect(store.getState().channels).toBeNull();
+ expect(store.getState().channelUnread).toBe(0);
+ });
+
+ it("keeps both when the organization is still listed", () => {
+ const store = createCompanyStore();
+ store.setState({
+ organizations: [summary("p1", "acme"), summary("p2", "other")],
+ orgsLoaded: true,
+ orgsPartial: false,
+ currentOrgKey: "p1/acme",
+ lastOrgKey: "p1/acme",
+ channels: [channel()],
+ });
+ store.getState().forgetMissingOrganizations();
+ expect(store.getState().currentOrgKey).toBe("p1/acme");
+ expect(store.getState().lastOrgKey).toBe("p1/acme");
+ expect(store.getState().channels).not.toBeNull();
+ });
+
+ it("forgets the remembered organization on its own, with none open", () => {
+ const store = createCompanyStore();
+ store.setState({
+ organizations: [],
+ orgsLoaded: true,
+ orgsPartial: false,
+ currentOrgKey: null,
+ lastOrgKey: "p1/acme",
+ });
+ store.getState().forgetMissingOrganizations();
+ expect(store.getState().lastOrgKey).toBeNull();
+ });
+
+ it("waits for a settled and complete list — neither a first load nor a failed Project is a deletion", () => {
+ for (const settling of [
+ { orgsLoaded: false, orgsPartial: false },
+ { orgsLoaded: true, orgsPartial: true },
+ ]) {
+ const store = createCompanyStore();
+ store.setState({
+ organizations: [],
+ ...settling,
+ currentOrgKey: "p1/acme",
+ lastOrgKey: "p1/acme",
+ });
+ store.getState().forgetMissingOrganizations();
+ expect(store.getState().currentOrgKey).toBe("p1/acme");
+ expect(store.getState().lastOrgKey).toBe("p1/acme");
+ }
+ });
+});
+
+describe("the ticket dialog the whole shell shares", () => {
+ const open = (store: ReturnType<typeof createCompanyStore>) => store.getState().ticketDialog;
+
+ it("opens a ticket, stacks the ones followed from it, and walks back through them", () => {
+ const store = createCompanyStore();
+ store.getState().openTicket("p1", "acme", "t-1");
+ expect(open(store)).toEqual({ projectId: "p1", orgId: "acme", ticketId: "t-1" });
+ expect(store.getState().ticketStack).toEqual([]);
+
+ // A child followed from inside the dialog leaves its parent on the stack.
+ store.getState().openTicket("p1", "acme", "t-2");
+ store.getState().openTicket("p1", "acme", "t-3");
+ expect(open(store)?.ticketId).toBe("t-3");
+ expect(store.getState().ticketStack).toEqual(["t-1", "t-2"]);
+
+ store.getState().backTicket();
+ expect(open(store)?.ticketId).toBe("t-2");
+ expect(store.getState().ticketStack).toEqual(["t-1"]);
+ store.getState().backTicket();
+ expect(open(store)?.ticketId).toBe("t-1");
+ expect(store.getState().ticketStack).toEqual([]);
+ // Nothing left to go back to: the dialog stays on the ticket it is showing.
+ store.getState().backTicket();
+ expect(open(store)?.ticketId).toBe("t-1");
+ });
+
+ it("re-opening the ticket already shown changes nothing", () => {
+ const store = createCompanyStore();
+ store.getState().openTicket("p1", "acme", "t-1");
+ store.getState().openTicket("p1", "acme", "t-2");
+ // What the board does when it writes the open ticket back into its own query.
+ store.getState().openTicket("p1", "acme", "t-2");
+ expect(store.getState().ticketStack).toEqual(["t-1"]);
+ });
+
+ it("starts a fresh stack in another organization, and closing drops both", () => {
+ const store = createCompanyStore();
+ store.getState().openTicket("p1", "acme", "t-1");
+ store.getState().openTicket("p1", "acme", "t-2");
+ store.getState().openTicket("p1", "other", "t-9");
+ expect(open(store)).toEqual({ projectId: "p1", orgId: "other", ticketId: "t-9" });
+ expect(store.getState().ticketStack).toEqual([]);
+
+ store.getState().closeTicket();
+ expect(open(store)).toBeNull();
+ expect(store.getState().ticketStack).toEqual([]);
+ });
+
+ it("closes with the organization the reader leaves", () => {
+ const store = createCompanyStore();
+ store.setState({ currentOrgKey: "p1/acme" });
+ store.getState().openTicket("p1", "acme", "t-1");
+ store.getState().openTicket("p1", "acme", "t-2");
+ store.getState().setCurrentOrg("p1/other");
+ expect(open(store)).toBeNull();
+ expect(store.getState().ticketStack).toEqual([]);
+ });
+
+ it("a local ticket write bumps the versions the surfaces listing tickets watch", () => {
+ const store = createCompanyStore();
+ const before = store.getState().versions;
+ store.getState().ticketsChanged();
+ const after = store.getState().versions;
+ expect(after.tickets).toBe(before.tickets + 1);
+ expect(after.orgs).toBe(before.orgs + 1);
+ expect(after.messages).toBe(before.messages);
+ });
+});
+
+describe("applyUserEvent forwarding", () => {
+ it("publishes a company event to every subscriber and refreshes the list on a work run of the current Project", () => {
+ const sessions = createSessionsStore();
+ const reload = vi.fn(() => Promise.resolve());
+ sessions.setState({ projectId: "p1", reload });
+ const seen: CompanyServerEvent[] = [];
+ const stop = subscribeCompanyEvents((ev) => seen.push(ev));
+ try {
+ const run: CompanyServerEvent = {
+ type: "org_run",
+ projectId: "p1",
+ orgId: "acme",
+ agentId: "ceo",
+ sessionId: "s",
+ kind: "init",
+ };
+ applyUserEvent(sessions, run, () => undefined);
+ applyUserEvent(sessions, { ...run, projectId: "p2" }, () => undefined);
+ applyUserEvent(sessions, posted(), () => undefined);
+ expect(seen.map((e) => e.type)).toEqual(["org_run", "org_run", "org_channel"]);
+ // Only the run of the current Project refreshes; a channel message changes no session row.
+ expect(reload).toHaveBeenCalledTimes(1);
+ } finally {
+ stop();
+ }
+ });
+});
diff --git a/packages/web/test/desk-renew.test.ts b/packages/web/test/desk-renew.test.ts
new file mode 100644
index 00000000..977ed60f
--- /dev/null
+++ b/packages/web/test/desk-renew.test.ts
@@ -0,0 +1,28 @@
+/**
+ * desk-renew.ts unit tests: what a desk-renewal confirm sends — a renewal alone when the
+ * prefilled workspace is untouched, the workspace write first when it changed, and a refusal
+ * when the required field was emptied.
+ */
+import { describe, expect, it } from "vitest";
+import { deskRenewPlan } from "../src/features/company/desk-renew";
+
+describe("deskRenewPlan", () => {
+ it("sends no workspace write when the prefilled spec is left alone", () => {
+ expect(deskRenewPlan("hr", "hr")).toEqual({ valid: true, workspace: null });
+ // Padding is not a change: the field is prefilled, and a stray space must not rewrite the chart.
+ expect(deskRenewPlan("hr", " hr ")).toEqual({ valid: true, workspace: null });
+ expect(deskRenewPlan(".", ".")).toEqual({ valid: true, workspace: null });
+ });
+
+ it("sends the trimmed spec when it changed", () => {
+ expect(deskRenewPlan("hr", "hr/2026")).toEqual({ valid: true, workspace: "hr/2026" });
+ expect(deskRenewPlan(".", " /srv/shared ")).toEqual({ valid: true, workspace: "/srv/shared" });
+ // Case matters: a directory name is the file system's, not ours to fold.
+ expect(deskRenewPlan("hr", "HR")).toEqual({ valid: true, workspace: "HR" });
+ });
+
+ it("refuses an emptied field instead of falling back to the shared workspace", () => {
+ expect(deskRenewPlan("hr", "")).toEqual({ valid: false, workspace: null });
+ expect(deskRenewPlan("hr", " ")).toEqual({ valid: false, workspace: null });
+ });
+});
diff --git a/packages/web/test/finance-tree.test.ts b/packages/web/test/finance-tree.test.ts
new file mode 100644
index 00000000..e69bfa62
--- /dev/null
+++ b/packages/web/test/finance-tree.test.ts
@@ -0,0 +1,315 @@
+/**
+ * finance-tree.ts unit tests: the spend tree along the reporting line, the ticket ledger
+ * along parent tickets and the rows its fold leaves visible, period arithmetic, the budget
+ * tone thresholds, the marks the state column carries, the trend series and its axis breaks,
+ * the KPI row's numbers, the alert grouping, and the two row tooltips that carry what the
+ * tables dropped a column for.
+ */
+import { describe, expect, it } from "vitest";
+import type { OrgFinanceEmployee, OrgFinanceTicket } from "@prismshadow/penguin-server/api";
+import {
+ budgetTone,
+ dailyBreaks,
+ financeKpis,
+ financeSeries,
+ groupAlerts,
+ shiftPeriod,
+ spendRowTooltip,
+ spendStateMarks,
+ spendTreeRows,
+ ticketRowTooltip,
+ ticketTreeRows,
+ visibleLedgerRows,
+} from "../src/features/company/finance-tree";
+
+const employee = (agentId: string, reportsTo: string | null): OrgFinanceEmployee => ({
+ agentId,
+ name: agentId,
+ title: "",
+ reportsTo,
+ own: 1,
+ cumulative: 1,
+ warned: false,
+ paused: false,
+});
+
+const ticket = (ticketId: string, parent?: string): OrgFinanceTicket => ({
+ ticketId,
+ title: ticketId,
+ status: "done",
+ ...(parent !== undefined ? { parent } : {}),
+ cost: 1,
+ rolledUp: 1,
+});
+
+describe("spendTreeRows", () => {
+ it("walks the reporting line depth-first with depths, an unknown manager starting a tree of its own", () => {
+ const rows = spendTreeRows([
+ employee("dev", "cto"),
+ employee("ceo", null),
+ employee("cto", "ceo"),
+ employee("lost", "gone"),
+ ]);
+ expect(rows.map((r) => [r.employee.agentId, r.depth])).toEqual([
+ ["ceo", 0],
+ ["cto", 1],
+ ["dev", 2],
+ ["lost", 0],
+ ]);
+ });
+});
+
+describe("ticketTreeRows", () => {
+ it("nests children under their parent and starts at the top for an unknown parent", () => {
+ const rows = ticketTreeRows([ticket("b", "a"), ticket("a"), ticket("c", "zzz")]);
+ expect(rows.map((r) => [r.ticket.ticketId, r.depth])).toEqual([
+ ["a", 0],
+ ["b", 1],
+ ["c", 0],
+ ]);
+ });
+});
+
+describe("visibleLedgerRows", () => {
+ /** a > b > c, a > d, and the root e with nothing under it. */
+ const tree = () =>
+ ticketTreeRows([
+ ticket("a"),
+ ticket("b", "a"),
+ ticket("c", "b"),
+ ticket("d", "a"),
+ ticket("e"),
+ ]);
+
+ it("shows the roots alone when nothing is expanded, each counting only its direct children", () => {
+ expect(
+ visibleLedgerRows(tree(), new Set()).map((r) => [r.ticket.ticketId, r.children]),
+ ).toEqual([
+ ["a", 2],
+ ["e", 0],
+ ]);
+ });
+
+ it("opens one level per expanded parent", () => {
+ expect(visibleLedgerRows(tree(), new Set(["a"])).map((r) => r.ticket.ticketId)).toEqual([
+ "a",
+ "b",
+ "d",
+ "e",
+ ]);
+ expect(
+ visibleLedgerRows(tree(), new Set(["a", "b"])).map((r) => [r.ticket.ticketId, r.depth]),
+ ).toEqual([
+ ["a", 0],
+ ["b", 1],
+ ["c", 2],
+ ["d", 1],
+ ["e", 0],
+ ]);
+ });
+
+ it("keeps a subtree hidden while an ancestor above the expanded parent is folded", () => {
+ expect(visibleLedgerRows(tree(), new Set(["b"])).map((r) => r.ticket.ticketId)).toEqual([
+ "a",
+ "e",
+ ]);
+ });
+
+ it("leaves a childless row with no children to count and nothing to fold", () => {
+ const rows = visibleLedgerRows(ticketTreeRows([ticket("only")]), new Set());
+ expect(rows).toEqual([{ ticket: ticket("only"), depth: 0, children: 0 }]);
+ });
+});
+
+describe("shiftPeriod", () => {
+ it("moves whole months across year boundaries and rejects other shapes", () => {
+ expect(shiftPeriod("2026-09", -1)).toBe("2026-08");
+ expect(shiftPeriod("2026-01", -1)).toBe("2025-12");
+ expect(shiftPeriod("2026-12", 1)).toBe("2027-01");
+ expect(shiftPeriod("2026-13", 1)).toBeNull();
+ expect(shiftPeriod("nope", 1)).toBeNull();
+ });
+});
+
+describe("budgetTone", () => {
+ it("is success under 80%, attention from 80%, danger from 100%, muted without a budget", () => {
+ expect(budgetTone(0.5)).toBe("success");
+ expect(budgetTone(0.8)).toBe("attention");
+ expect(budgetTone(1)).toBe("danger");
+ expect(budgetTone(undefined)).toBe("muted");
+ expect(budgetTone(Number.NaN)).toBe("muted");
+ });
+});
+
+describe("financeSeries", () => {
+ it("shapes daily costs as the trend chart's points", () => {
+ expect(financeSeries([{ date: "2026-09-01", cost: 2.5 }])).toEqual([
+ {
+ bucket: "2026-09-01",
+ cacheRead: 0,
+ cacheWrite: 0,
+ output: 0,
+ total: 0,
+ cost: 2.5,
+ requests: 0,
+ completed: 0,
+ denominator: 0,
+ },
+ ]);
+ });
+});
+
+describe("dailyBreaks", () => {
+ it("marks the point after which a calendar day was skipped, across a month boundary too", () => {
+ const daily = [
+ { date: "2026-08-30" },
+ { date: "2026-08-31" },
+ { date: "2026-09-01" },
+ { date: "2026-09-03" },
+ { date: "2026-09-10" },
+ ];
+ expect(dailyBreaks(daily)).toEqual([2, 3]);
+ expect(dailyBreaks([{ date: "2026-09-02" }])).toEqual([]);
+ expect(dailyBreaks([])).toEqual([]);
+ });
+
+ it("ignores an unparsable date rather than breaking around it", () => {
+ expect(dailyBreaks([{ date: "2026-09-01" }, { date: "nope" }, { date: "2026-09-05" }])).toEqual(
+ [],
+ );
+ });
+});
+
+describe("financeKpis", () => {
+ const withBudget = (
+ agentId: string,
+ reportsTo: string | null,
+ extra: Partial<OrgFinanceEmployee>,
+ ): OrgFinanceEmployee => ({ ...employee(agentId, reportsTo), ...extra });
+
+ it("measures the total against the root's budget and counts budgets, warnings and pauses", () => {
+ const kpis = financeKpis({
+ total: 21,
+ employees: [
+ withBudget("cto", "ceo", { budget: 4, warned: true, paused: true }),
+ withBudget("ceo", null, { budget: 10, warned: true }),
+ withBudget("dev", "cto", {}),
+ withBudget("growth", "ceo", { budget: 3, warned: true }),
+ ],
+ });
+ expect(kpis).toEqual({
+ total: 21,
+ budget: 10,
+ ratio: 2.1,
+ employees: 4,
+ budgeted: 3,
+ warned: 2,
+ paused: 1,
+ });
+ });
+
+ it("leaves budget and ratio out when the root has no budget", () => {
+ const kpis = financeKpis({ total: 5, employees: [employee("ceo", null)] });
+ expect(kpis).toEqual({ total: 5, employees: 1, budgeted: 0, warned: 0, paused: 0 });
+ expect("budget" in kpis).toBe(false);
+ });
+});
+
+describe("groupAlerts", () => {
+ it("lists a paused alert under paused only, newest first in each group", () => {
+ const groups = groupAlerts([
+ { agentId: "a", period: "2026-09", warnedAt: "2026-09-01T00:00:00Z" },
+ {
+ agentId: "b",
+ period: "2026-09",
+ warnedAt: "2026-09-01T00:00:00Z",
+ pausedAt: "2026-09-02T00:00:00Z",
+ },
+ { agentId: "c", period: "2026-09", warnedAt: "2026-09-03T00:00:00Z" },
+ { agentId: "d", period: "2026-09", pausedAt: "2026-09-04T00:00:00Z" },
+ { agentId: "e", period: "2026-09" },
+ ]);
+ expect(groups.paused.map((a) => a.agentId)).toEqual(["d", "b"]);
+ expect(groups.warned.map((a) => a.agentId)).toEqual(["c", "a"]);
+ });
+});
+
+describe("spendRowTooltip", () => {
+ const labels = {
+ own: "Own spend",
+ cumulative: "Cumulative",
+ budget: "Budget",
+ noBudget: "Unbounded",
+ };
+ const money = (value: number) => `$${value.toFixed(2)}`;
+
+ it("names all three figures, the budget among them", () => {
+ expect(spendRowTooltip({ own: 12, cumulative: 41, budget: 100 }, labels, money)).toBe(
+ "Own spend $12.00 · Cumulative $41.00 · Budget $100.00",
+ );
+ });
+
+ it("says a missing budget is unbounded rather than dropping the field", () => {
+ expect(spendRowTooltip({ own: 12, cumulative: 41 }, labels, money)).toBe(
+ "Own spend $12.00 · Cumulative $41.00 · Budget Unbounded",
+ );
+ });
+});
+
+describe("ticketRowTooltip", () => {
+ const labels = {
+ owner: "Owner",
+ noOwner: "Unassigned",
+ cost: "Cost",
+ rolledUp: "Rolled-up cost",
+ };
+ const money = (value: number) => `$${value.toFixed(2)}`;
+
+ it("leads with the id and carries the owner and both costs", () => {
+ expect(
+ ticketRowTooltip({ ticketId: "TCK-1", cost: 3.2, rolledUp: 8.7 }, "Ada", labels, money),
+ ).toBe("TCK-1 · Owner Ada · Cost $3.20 · Rolled-up cost $8.70");
+ });
+
+ it("keeps the owner field with a stand-in when nobody owns the ticket", () => {
+ expect(
+ ticketRowTooltip({ ticketId: "TCK-2", cost: 0, rolledUp: 0 }, undefined, labels, money),
+ ).toBe("TCK-2 · Owner Unassigned · Cost $0.00 · Rolled-up cost $0.00");
+ });
+});
+
+describe("spendStateMarks", () => {
+ const calm = { warned: false, paused: false };
+
+ it("leads with the live state and adds what the budget did", () => {
+ expect(spendStateMarks(calm, "running")).toEqual([{ tone: "busy", key: "running" }]);
+ expect(spendStateMarks(calm, "idle")).toEqual([{ tone: "success", key: "idle" }]);
+ expect(spendStateMarks({ warned: true, paused: false }, "running")).toEqual([
+ { tone: "busy", key: "running" },
+ { tone: "attention", key: "warned" },
+ ]);
+ });
+
+ it("says paused once, however the two sources spell it", () => {
+ // A budget pause is the reason the live state reads `paused`: one mark, not two.
+ const paused = [{ tone: "danger", key: "paused" }];
+ expect(spendStateMarks({ warned: true, paused: true }, "paused")).toEqual(paused);
+ expect(spendStateMarks({ warned: false, paused: true }, "idle")).toEqual([
+ { tone: "success", key: "idle" },
+ { tone: "danger", key: "paused" },
+ ]);
+ // The chart knows before the period's figures do, and the row still says why.
+ expect(spendStateMarks(calm, "paused")).toEqual(paused);
+ });
+
+ it("stands on the budget alone while the live state is unknown", () => {
+ // The chart is a best-effort join: a row must still read without it.
+ expect(spendStateMarks(calm, undefined)).toEqual([]);
+ expect(spendStateMarks({ warned: true, paused: false }, undefined)).toEqual([
+ { tone: "attention", key: "warned" },
+ ]);
+ expect(spendStateMarks({ warned: false, paused: true }, undefined)).toEqual([
+ { tone: "danger", key: "paused" },
+ ]);
+ });
+});
diff --git a/packages/web/test/handbook-explorer.test.ts b/packages/web/test/handbook-explorer.test.ts
new file mode 100644
index 00000000..e2b771e6
--- /dev/null
+++ b/packages/web/test/handbook-explorer.test.ts
@@ -0,0 +1,103 @@
+/**
+ * The handbook explorer's rows, via react-dom/server static markup (node env, no DOM). The
+ * explorer is the app's shared `FileTree`, so what is tested here is the handbook's own half:
+ * that the rows really are the shared tree's (each one a `treeitem` carrying `data-tree-path`),
+ * that the index leads them, and what a row shows on screen against what it only tells the
+ * pointer and the screen reader. The pinned index is the case that matters — why `README.md`
+ * is pinned is a tooltip and an accessible name, never a second visible line under the file
+ * name — while an ordinary document or folder row keeps its visible name as its whole
+ * accessible name and carries its own meta after it.
+ */
+import { describe, expect, it } from "vitest";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import type { OrgHandbookFile } from "@prismshadow/penguin-server/api";
+import { HandbookExplorer } from "../src/features/company/handbook-explorer";
+import {
+ HANDBOOK_INDEX,
+ buildHandbookTree,
+ handbookTreeRows,
+} from "../src/features/company/handbook-tree";
+import { formatBytes, formatDateTime, formatRelativeShort } from "../src/lib/format";
+import { zh } from "../src/lib/strings";
+
+const UPDATED = "2026-09-02T10:00:00.000Z";
+const file = (path: string, size: number): OrgHandbookFile => ({ path, size, updatedAt: UPDATED });
+
+const FILES = [
+ file(HANDBOOK_INDEX, 512),
+ file("conventions.md", 40),
+ file("roles/hr.md", 30),
+ file("roles/eng.md", 30),
+];
+
+/** How a document row's tooltip spells "written then, this big". */
+const updatedAt = (size: number): string =>
+ zh.company.handbook.updatedAt(formatDateTime(UPDATED), formatBytes(size));
+
+/**
+ * The tree with `roles` open, as one chunk of markup per row in reading order. A row is a
+ * `treeitem` element holding no other row — the shared tree nests subtrees in sibling groups —
+ * so a row ends at the first close tag after it.
+ */
+function rows(): string[] {
+ const tree = buildHandbookTree(FILES);
+ const html = renderToStaticMarkup(
+ createElement(HandbookExplorer, {
+ rows: handbookTreeRows(tree, new Set(["roles"])),
+ selected: HANDBOOK_INDEX,
+ locale: "zh",
+ toggled: null,
+ onSelect: () => undefined,
+ onToggle: () => undefined,
+ }),
+ );
+ return [...html.matchAll(/<div [^>]*data-tree-path="[^"]*"[^>]*>.*?<\/div>/g)].map((m) => m[0]);
+}
+
+/** One attribute of a row, or null when the row does not carry it. */
+const attr = (row: string, name: string): string | null =>
+ new RegExp(`${name}="([^"]*)"`).exec(row)?.[1] ?? null;
+
+/** What a row puts on screen: its markup with every tag — and so every attribute — removed. */
+const visible = (row: string): string => row.replaceAll(/<[^>]*>/g, "");
+
+describe("HandbookExplorer rows", () => {
+ it("draws the shared file tree's rows, the index leading them", () => {
+ expect(rows().map((r) => attr(r, "data-tree-path"))).toEqual([
+ HANDBOOK_INDEX,
+ "roles",
+ "roles/eng.md",
+ "roles/hr.md",
+ "conventions.md",
+ ]);
+ expect(rows().every((r) => attr(r, "role") === "treeitem")).toBe(true);
+ });
+
+ it("keeps the index's reason for being pinned out of the row and in its tooltip and name", () => {
+ const [index] = rows();
+ const expected = `${HANDBOOK_INDEX} · ${zh.company.handbook.indexLabel} · ${updatedAt(512)}`;
+ expect(attr(index!, "title")).toBe(expected);
+ expect(attr(index!, "aria-label")).toBe(expected);
+ expect(visible(index!)).toContain(HANDBOOK_INDEX);
+ expect(visible(index!)).not.toContain(zh.company.handbook.indexLabel);
+ });
+
+ it("leaves the index label out of every visible row", () => {
+ expect(rows().map(visible).join("")).not.toContain(zh.company.handbook.indexLabel);
+ });
+
+ it("gives a document row its path and write time, and no accessible name of its own", () => {
+ const row = rows().find((r) => attr(r, "data-tree-path") === "conventions.md");
+ expect(attr(row!, "title")).toBe(`conventions.md · ${updatedAt(40)}`);
+ expect(attr(row!, "aria-label")).toBeNull();
+ expect(visible(row!)).toBe(`conventions.md${formatRelativeShort(UPDATED, "zh")}`);
+ });
+
+ it("gives a folder row its path and how many documents it holds", () => {
+ const row = rows().find((r) => attr(r, "aria-expanded") !== null);
+ expect(attr(row!, "title")).toBe(`roles · ${zh.company.handbook.documentsInFolder(2)}`);
+ expect(attr(row!, "aria-label")).toBeNull();
+ expect(visible(row!)).toBe("roles2");
+ });
+});
diff --git a/packages/web/test/handbook-tree.test.ts b/packages/web/test/handbook-tree.test.ts
new file mode 100644
index 00000000..8b6d83c7
--- /dev/null
+++ b/packages/web/test/handbook-tree.test.ts
@@ -0,0 +1,300 @@
+/**
+ * handbook-tree.ts unit tests: the listing shaped into the pinned index and a nested explorer
+ * tree (folders before files at every level, each group ordered case-insensitively, the index
+ * apart); the walking the tree view does — the folders above a document, the shared file-tree
+ * rows an expanded set makes visible, how many documents a subtree holds; the path rule
+ * mirrored from the server; what the new-document dialog sends for what was typed; the body a
+ * new document starts with; and how a relative link inside a document resolves to another.
+ */
+import { describe, expect, it } from "vitest";
+import type { OrgHandbookFile } from "@prismshadow/penguin-server/api";
+import {
+ HANDBOOK_INDEX,
+ ancestorFolders,
+ buildHandbookTree,
+ completeHandbookPath,
+ countDocuments,
+ fileName,
+ handbookTreeRows,
+ isHandbookPath,
+ isMarkdownPath,
+ newDocumentBody,
+ resolveHandbookLink,
+} from "../src/features/company/handbook-tree";
+import type { HandbookNode } from "../src/features/company/handbook-tree";
+
+const file = (path: string, size = 10): OrgHandbookFile => ({
+ path,
+ size,
+ updatedAt: "2026-09-02T10:00:00.000Z",
+});
+
+/** A node's path prefixed by its kind, so an assertion reads as the tree's shape. */
+const shape = (nodes: readonly HandbookNode[]): string[] =>
+ nodes.flatMap((n) =>
+ n.kind === "folder" ? [`dir ${n.path}`, ...shape(n.children)] : [`doc ${n.path}`],
+ );
+
+const MIXED = [
+ file("README.md"),
+ file("decisions/2026/09/plan.md"),
+ file("decisions/2026-09-02-hire-plan.md"),
+ file("conventions.md"),
+ file("decisions/2026-09-01-mission.md"),
+ file("roles/hr.md"),
+ file("Brand.md"),
+];
+
+describe("buildHandbookTree", () => {
+ it("nests every path, folders before files at each level, with the index apart", () => {
+ const tree = buildHandbookTree(MIXED);
+ expect(tree.index?.path).toBe(HANDBOOK_INDEX);
+ expect(shape(tree.nodes)).toEqual([
+ "dir decisions",
+ "dir decisions/2026",
+ "dir decisions/2026/09",
+ "doc decisions/2026/09/plan.md",
+ "doc decisions/2026-09-01-mission.md",
+ "doc decisions/2026-09-02-hire-plan.md",
+ "dir roles",
+ "doc roles/hr.md",
+ "doc Brand.md",
+ "doc conventions.md",
+ ]);
+ // A row carries its own name for display and the whole path for selection.
+ const decisions = tree.nodes[0]!;
+ expect(decisions.kind === "folder" && decisions.name).toBe("decisions");
+ const brand = tree.nodes[2]!;
+ expect(brand.kind === "file" && brand.name).toBe("Brand.md");
+ expect(brand.kind === "file" && brand.file.size).toBe(10);
+ });
+
+ it("orders each level case-insensitively, case deciding only a tie", () => {
+ const tree = buildHandbookTree([file("beta.md"), file("Alpha.md"), file("alpha.md")]);
+ expect(shape(tree.nodes)).toEqual(["doc Alpha.md", "doc alpha.md", "doc beta.md"]);
+ });
+
+ it("ignores the order the listing came in, and copes with a missing index", () => {
+ const tree = buildHandbookTree([file("z.md"), file("a.md"), file("m/x.md"), file("b/y.md")]);
+ expect(tree.index).toBeNull();
+ expect(shape(tree.nodes)).toEqual([
+ "dir b",
+ "doc b/y.md",
+ "dir m",
+ "doc m/x.md",
+ "doc a.md",
+ "doc z.md",
+ ]);
+ });
+
+ it("is empty but for the index when the handbook holds nothing else", () => {
+ const tree = buildHandbookTree([file("README.md")]);
+ expect(tree.index).not.toBeNull();
+ expect(tree.nodes).toEqual([]);
+ });
+});
+
+describe("ancestorFolders", () => {
+ it("names the folders above a document, root first", () => {
+ expect(ancestorFolders("decisions/2026/09/plan.md")).toEqual([
+ "decisions",
+ "decisions/2026",
+ "decisions/2026/09",
+ ]);
+ expect(ancestorFolders("conventions.md")).toEqual([]);
+ expect(ancestorFolders(HANDBOOK_INDEX)).toEqual([]);
+ });
+});
+
+describe("handbookTreeRows", () => {
+ const tree = buildHandbookTree(MIXED);
+
+ it("leads with the index and shows only the top level while everything is collapsed", () => {
+ const rows = handbookTreeRows(tree, new Set());
+ expect(rows.map((r) => r.path)).toEqual([
+ HANDBOOK_INDEX,
+ "decisions",
+ "roles",
+ "Brand.md",
+ "conventions.md",
+ ]);
+ expect(rows.every((r) => r.depth === 0)).toBe(true);
+ // The index shares the top level, so it counts in that level\'s set.
+ expect(rows.map((r) => `${r.posInSet}/${r.setSize}`)).toEqual([
+ "1/5",
+ "2/5",
+ "3/5",
+ "4/5",
+ "5/5",
+ ]);
+ expect(rows.filter((r) => r.isIndex).map((r) => r.path)).toEqual([HANDBOOK_INDEX]);
+ });
+
+ it("walks an expanded folder\'s children in place, one level deeper", () => {
+ const rows = handbookTreeRows(tree, new Set(["decisions", "decisions/2026"]));
+ expect(rows.map((r) => `${r.depth} ${r.path}`)).toEqual([
+ `0 ${HANDBOOK_INDEX}`,
+ "0 decisions",
+ "1 decisions/2026",
+ "2 decisions/2026/09",
+ "1 decisions/2026-09-01-mission.md",
+ "1 decisions/2026-09-02-hire-plan.md",
+ "0 roles",
+ "0 Brand.md",
+ "0 conventions.md",
+ ]);
+ // A nested level states its own size, and only the expanded folders report themselves open.
+ const nested = rows.find((r) => r.path === "decisions/2026")!;
+ expect(`${nested.posInSet}/${nested.setSize}`).toBe("1/3");
+ expect(rows.filter((r) => r.expanded).map((r) => r.path)).toEqual([
+ "decisions",
+ "decisions/2026",
+ ]);
+ });
+
+ it("keeps a folder\'s children hidden while the folder above it is closed", () => {
+ const rows = handbookTreeRows(tree, new Set(["decisions/2026"]));
+ expect(rows.map((r) => r.path)).toEqual([
+ HANDBOOK_INDEX,
+ "decisions",
+ "roles",
+ "Brand.md",
+ "conventions.md",
+ ]);
+ });
+
+ it("tells a folder row from a document row, and hands each what it shows beside its name", () => {
+ const rows = handbookTreeRows(tree, new Set(["decisions"]));
+ const decisions = rows.find((r) => r.path === "decisions")!;
+ expect(decisions.kind).toBe("dir");
+ expect(decisions.docs).toBe(3);
+ expect(decisions.file).toBeNull();
+ const doc = rows.find((r) => r.path === "conventions.md")!;
+ expect(doc.kind).toBe("file");
+ expect(doc.docs).toBe(0);
+ expect(doc.file?.path).toBe("conventions.md");
+ // The whole listing arrived in one response: no folder is ever still loading, and one
+ // built out of the paths of documents is never empty.
+ expect(rows.every((r) => r.loaded && !r.empty)).toBe(true);
+ });
+
+ it("draws no index row for a handbook whose index is gone", () => {
+ const rows = handbookTreeRows(buildHandbookTree([file("conventions.md")]), new Set());
+ expect(rows.map((r) => r.path)).toEqual(["conventions.md"]);
+ expect(rows[0]!.setSize).toBe(1);
+ expect(rows.some((r) => r.isIndex)).toBe(false);
+ });
+});
+
+describe("countDocuments", () => {
+ it("counts the documents of a subtree however deep, folders themselves counting for none", () => {
+ const tree = buildHandbookTree(MIXED);
+ expect(countDocuments(tree.nodes)).toBe(6);
+ const decisions = tree.nodes[0]!;
+ expect(decisions.kind === "folder" ? countDocuments(decisions.children) : -1).toBe(3);
+ expect(countDocuments([])).toBe(0);
+ });
+});
+
+describe("isHandbookPath", () => {
+ it("accepts plain segments joined by slashes", () => {
+ for (const rel of [
+ "README.md",
+ "conventions.md",
+ "decisions/2026-09-02-hire-plan.md",
+ "a/b/c/d/e/f/g/h.md",
+ "notes.v2",
+ "2026",
+ ]) {
+ expect(isHandbookPath(rel), rel).toBe(true);
+ }
+ });
+
+ it("refuses hidden files, traversal, empty segments, other characters and a ninth level", () => {
+ for (const rel of [
+ "",
+ ".hidden.md",
+ "decisions/.draft.md",
+ "../org_config.toml",
+ "a/../b.md",
+ "/abs.md",
+ "a//b.md",
+ "a/",
+ "hire plan.md",
+ "notes:1.md",
+ "a/b/c/d/e/f/g/h/i.md",
+ ]) {
+ expect(isHandbookPath(rel), rel).toBe(false);
+ }
+ });
+});
+
+describe("completeHandbookPath", () => {
+ it("trims, drops a leading ./ or / and a trailing /, and adds .md when the name has no extension", () => {
+ expect(completeHandbookPath(" decisions/hire-plan ")).toBe("decisions/hire-plan.md");
+ expect(completeHandbookPath("./conventions.md")).toBe("conventions.md");
+ expect(completeHandbookPath("/roles/hr")).toBe("roles/hr.md");
+ expect(completeHandbookPath("roles/")).toBe("roles.md");
+ });
+
+ it("leaves a name with an extension alone, and an empty input empty", () => {
+ expect(completeHandbookPath("notes.txt")).toBe("notes.txt");
+ expect(completeHandbookPath("notes.v2")).toBe("notes.v2");
+ expect(completeHandbookPath(" ")).toBe("");
+ });
+});
+
+describe("file names and bodies", () => {
+ it("names a file by its last segment and renders Markdown by extension", () => {
+ expect(fileName("decisions/2026-09-02-hire-plan.md")).toBe("2026-09-02-hire-plan.md");
+ expect(fileName("README.md")).toBe("README.md");
+ expect(isMarkdownPath("README.md")).toBe(true);
+ expect(isMarkdownPath("notes.MARKDOWN")).toBe(true);
+ expect(isMarkdownPath("notes.txt")).toBe(false);
+ expect(isMarkdownPath("2026")).toBe(false);
+ });
+
+ it("starts a new document with a title made of its file name", () => {
+ expect(newDocumentBody("decisions/2026-09-02-hire-plan.md")).toBe("# 2026-09-02-hire-plan\n");
+ expect(newDocumentBody("notes.v2")).toBe("# notes\n");
+ });
+});
+
+describe("resolveHandbookLink", () => {
+ it("resolves a relative link against the linking document's folder", () => {
+ expect(resolveHandbookLink("README.md", "decisions/hire-plan.md")).toBe(
+ "decisions/hire-plan.md",
+ );
+ expect(resolveHandbookLink("README.md", "./conventions.md")).toBe("conventions.md");
+ expect(resolveHandbookLink("decisions/hire-plan.md", "../conventions.md")).toBe(
+ "conventions.md",
+ );
+ expect(resolveHandbookLink("decisions/hire-plan.md", "mission.md")).toBe(
+ "decisions/mission.md",
+ );
+ expect(resolveHandbookLink("decisions/hire-plan.md", "/roles/hr.md")).toBe("roles/hr.md");
+ });
+
+ it("drops a fragment or query, and decodes the path", () => {
+ expect(resolveHandbookLink("README.md", "conventions.md#naming")).toBe("conventions.md");
+ expect(resolveHandbookLink("README.md", "conventions.md?x=1")).toBe("conventions.md");
+ expect(resolveHandbookLink("README.md", "hire%2Dplan.md")).toBe("hire-plan.md");
+ });
+
+ it("is null for anything that is not a document of the handbook", () => {
+ for (const href of [
+ "",
+ "#top",
+ "https://example.com/README.md",
+ "mailto:[email protected]",
+ "//example.com/x.md",
+ "../org_config.toml",
+ "../../etc/passwd",
+ ".hidden.md",
+ "%E0%A4%A",
+ ]) {
+ expect(resolveHandbookLink("README.md", href), href).toBeNull();
+ }
+ expect(resolveHandbookLink("decisions/plan.md", "../../out.md")).toBeNull();
+ });
+});
diff --git a/packages/web/test/id-suggest-notice.test.ts b/packages/web/test/id-suggest-notice.test.ts
new file mode 100644
index 00000000..d53581f6
--- /dev/null
+++ b/packages/web/test/id-suggest-notice.test.ts
@@ -0,0 +1,82 @@
+/**
+ * id-suggest-notice.ts unit tests: a model-made id says nothing, a transliteration gets the
+ * quiet note, a placeholder gets the attention-toned one with the server's reason spelled out
+ * in the reader's language, and a reason this build does not know still produces a sentence
+ * rather than dropping the note that tells the user the box holds a placeholder.
+ */
+import { describe, expect, it } from "vitest";
+import type {
+ SemanticIdSuggestReason,
+ SemanticIdSuggestResponse,
+} from "@prismshadow/penguin-server/api";
+import { idSuggestNotice } from "../src/features/company/id-suggest-notice";
+import { zh } from "../src/lib/strings";
+import { en } from "../src/lib/strings-en";
+
+const REASONS = Object.keys({
+ no_default_model: true,
+ model_failed: true,
+ unusable_answer: true,
+ no_ascii: true,
+} satisfies Record<SemanticIdSuggestReason, true>) as SemanticIdSuggestReason[];
+
+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());
+ });
+ }
+});
+
+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();
+ });
+
+ 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({
+ tone: "muted",
+ text: "按名称转写生成",
+ });
+ expect(idSuggestNotice(res, en.company.idSuggest)?.tone).toBe("muted");
+ });
+
+ it("asks for a real name when the id is a placeholder, and names the reason", () => {
+ for (const reason of REASONS) {
+ const res: SemanticIdSuggestResponse = {
+ id: "co_org_20260909",
+ source: "placeholder",
+ reason,
+ };
+ const note = idSuggestNotice(res, zh.company.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],
+ );
+ }
+ });
+
+ it("still tells the user it is a placeholder when the reason is one this build cannot read", () => {
+ const newer = {
+ id: "co_org_20260909",
+ source: "placeholder",
+ reason: "quota_exhausted",
+ } as unknown as SemanticIdSuggestResponse;
+ for (const dict of [zh, en]) {
+ const note = idSuggestNotice(newer, dict.company.idSuggest);
+ expect(note?.tone).toBe("attention");
+ expect(note?.text).toContain(dict.company.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,
+ );
+ });
+});
diff --git a/packages/web/test/org-chart-tree.test.ts b/packages/web/test/org-chart-tree.test.ts
new file mode 100644
index 00000000..62b5eae5
--- /dev/null
+++ b/packages/web/test/org-chart-tree.test.ts
@@ -0,0 +1,282 @@
+/**
+ * org-chart-tree.ts unit tests: the reporting line as a DFS tree from the CEO with the
+ * detached set apart, the subtree an employee may not be moved under, and the top-down
+ * layout — the root at the top centre, one row per depth, siblings a gap apart, a parent
+ * centred over its children, a deep subtree widening its parent's band, the detached row
+ * beneath, and the connectors from a parent's bottom centre to a child's top centre.
+ */
+import { describe, expect, it } from "vitest";
+import {
+ CHART_DETACHED_LABEL_H,
+ CHART_EDGE_RADIUS,
+ CHART_GAP_X,
+ CHART_GAP_Y,
+ CHART_NODE_H,
+ CHART_NODE_W,
+ CHART_PAD,
+ buildChartTree,
+ connectorPath,
+ layoutOrgTree,
+ managerCandidates,
+ subtreeIds,
+ workspaceTail,
+} from "../src/features/company/org-chart-tree";
+import type { OrgTreeLayout, OrgTreeNode } from "../src/features/company/org-chart-tree";
+
+const employees = [
+ { agentId: "ceo", reportsTo: null },
+ { agentId: "cto", reportsTo: "ceo" },
+ { agentId: "dev1", reportsTo: "cto" },
+ { agentId: "dev2", reportsTo: "cto" },
+ { agentId: "cfo", reportsTo: "ceo" },
+];
+
+const W = CHART_NODE_W;
+const H = CHART_NODE_H;
+const GX = CHART_GAP_X;
+const GY = CHART_GAP_Y;
+const PAD = CHART_PAD;
+
+const at = (layout: OrgTreeLayout, id: string): OrgTreeNode =>
+ layout.nodes.find((n) => n.id === id)!;
+const centre = (n: OrgTreeNode): number => n.x + W / 2;
+const row = (depth: number): number => PAD + depth * (H + GY);
+
+describe("buildChartTree", () => {
+ it("walks the tree in DFS preorder from the CEO with depths", () => {
+ const { nodes, detached } = buildChartTree(employees, "ceo");
+ expect(nodes.map((n) => [n.id, n.depth])).toEqual([
+ ["ceo", 0],
+ ["cto", 1],
+ ["dev1", 2],
+ ["dev2", 2],
+ ["cfo", 1],
+ ]);
+ expect(detached).toEqual([]);
+ });
+
+ it("lists employees whose chain never reaches the CEO as detached, cycles included", () => {
+ const { nodes, detached } = buildChartTree(
+ [...employees, { agentId: "x", reportsTo: "y" }, { agentId: "y", reportsTo: "x" }],
+ "ceo",
+ );
+ expect(nodes.map((n) => n.id)).toEqual(["ceo", "cto", "dev1", "dev2", "cfo"]);
+ expect(detached).toEqual(["x", "y"]);
+ });
+
+ it("a missing CEO leaves everyone detached rather than inventing a root", () => {
+ expect(buildChartTree(employees.slice(1), "ceo")).toEqual({
+ nodes: [],
+ detached: ["cto", "dev1", "dev2", "cfo"],
+ });
+ });
+});
+
+describe("subtreeIds and managerCandidates", () => {
+ it("collects an employee and every descendant, which are exactly who it may not report to", () => {
+ expect([...subtreeIds(employees, "cto")].sort()).toEqual(["cto", "dev1", "dev2"]);
+ expect(managerCandidates(employees, "cto").map((e) => e.agentId)).toEqual(["ceo", "cfo"]);
+ expect(managerCandidates(employees, "dev1").map((e) => e.agentId)).toEqual([
+ "ceo",
+ "cto",
+ "dev2",
+ "cfo",
+ ]);
+ });
+});
+
+describe("layoutOrgTree", () => {
+ it("puts a lone root at the top with the padding around it and no edges", () => {
+ const layout = layoutOrgTree([{ agentId: "ceo", reportsTo: null }], "ceo");
+ expect(at(layout, "ceo")).toMatchObject({ x: PAD, y: PAD, depth: 0, detached: false });
+ expect(layout.width).toBe(W + 2 * PAD);
+ expect(layout.height).toBe(H + 2 * PAD);
+ expect(layout.edges).toEqual([]);
+ expect(layout.detached).toEqual([]);
+ expect(layout.detachedTop).toBeNull();
+ });
+
+ it("two levels: siblings sit one gap apart on the second row and the root is centred over them", () => {
+ const layout = layoutOrgTree(
+ [
+ { agentId: "ceo", reportsTo: null },
+ { agentId: "a", reportsTo: "ceo" },
+ { agentId: "b", reportsTo: "ceo" },
+ { agentId: "c", reportsTo: "ceo" },
+ ],
+ "ceo",
+ );
+ expect(at(layout, "a")).toMatchObject({ x: PAD, y: row(1) });
+ expect(at(layout, "b")).toMatchObject({ x: PAD + W + GX, y: row(1) });
+ expect(at(layout, "c")).toMatchObject({ x: PAD + 2 * (W + GX), y: row(1) });
+ // The root's centre is the midpoint of its first and last child's centres — here, b's.
+ expect(at(layout, "ceo")).toMatchObject({ x: at(layout, "b").x, y: row(0) });
+ expect(centre(at(layout, "ceo"))).toBe((centre(at(layout, "a")) + centre(at(layout, "c"))) / 2);
+ expect(layout.width).toBe(3 * W + 2 * GX + 2 * PAD);
+ expect(layout.height).toBe(2 * H + GY + 2 * PAD);
+ });
+
+ it("three levels: a deeper subtree widens its parent's band and pushes the parent's siblings outward", () => {
+ const layout = layoutOrgTree(employees, "ceo");
+ const [ceo, cto, dev1, dev2, cfo] = ["ceo", "cto", "dev1", "dev2", "cfo"].map((id) =>
+ at(layout, id),
+ ) as [OrgTreeNode, OrgTreeNode, OrgTreeNode, OrgTreeNode, OrgTreeNode];
+ expect([ceo.y, cto.y, dev1.y, dev2.y, cfo.y]).toEqual([row(0), row(1), row(2), row(2), row(1)]);
+ // cto's band is two cards wide; cto is centred over dev1 and dev2.
+ expect(dev1.x).toBe(PAD);
+ expect(dev2.x).toBe(PAD + W + GX);
+ expect(centre(cto)).toBe((centre(dev1) + centre(dev2)) / 2);
+ // cfo starts after cto's whole band, not after cto's own card.
+ expect(cfo.x).toBe(dev2.x + W + GX);
+ expect(cfo.x - cto.x).toBeGreaterThan(W + GX);
+ // The root is centred between its first and last child.
+ expect(centre(ceo)).toBe((centre(cto) + centre(cfo)) / 2);
+ expect(layout.width).toBe(3 * W + 2 * GX + 2 * PAD);
+ expect(layout.height).toBe(3 * H + 2 * GY + 2 * PAD);
+ });
+
+ it("an uneven fan keeps every parent over the midpoint of its children and no row overlapping", () => {
+ const layout = layoutOrgTree(
+ [
+ { agentId: "ceo", reportsTo: null },
+ { agentId: "m1", reportsTo: "ceo" },
+ { agentId: "l1", reportsTo: "m1" },
+ { agentId: "l2", reportsTo: "m1" },
+ { agentId: "l3", reportsTo: "m1" },
+ { agentId: "m2", reportsTo: "ceo" },
+ { agentId: "l4", reportsTo: "m2" },
+ { agentId: "m3", reportsTo: "ceo" },
+ ],
+ "ceo",
+ );
+ const parents = [
+ ["ceo", ["m1", "m2", "m3"]],
+ ["m1", ["l1", "l2", "l3"]],
+ ["m2", ["l4"]],
+ ] as const;
+ for (const [parent, kids] of parents) {
+ const first = at(layout, kids[0]);
+ const last = at(layout, kids[kids.length - 1]!);
+ // Within half a pixel: x is rounded to whole pixels so cards render crisp.
+ expect(
+ Math.abs(centre(at(layout, parent)) - (centre(first) + centre(last)) / 2),
+ ).toBeLessThanOrEqual(0.5);
+ }
+ const byRow = new Map<number, OrgTreeNode[]>();
+ for (const n of layout.nodes) byRow.set(n.y, [...(byRow.get(n.y) ?? []), n]);
+ for (const nodes of byRow.values()) {
+ const xs = nodes.map((n) => n.x).sort((a, b) => a - b);
+ for (let i = 1; i < xs.length; i++)
+ expect(xs[i]! - xs[i - 1]!).toBeGreaterThanOrEqual(W + GX);
+ }
+ for (const n of layout.nodes) {
+ expect(Number.isInteger(n.x)).toBe(true);
+ expect(n.x).toBeGreaterThanOrEqual(PAD);
+ expect(n.x + W).toBeLessThanOrEqual(layout.width - PAD);
+ }
+ });
+
+ it("puts an employee whose manager is missing in a detached row under the tree, with no edge", () => {
+ const layout = layoutOrgTree(
+ [
+ { agentId: "ceo", reportsTo: null },
+ { agentId: "a", reportsTo: "ceo" },
+ { agentId: "x", reportsTo: "ghost" },
+ { agentId: "y", reportsTo: "x" },
+ ],
+ "ceo",
+ );
+ expect(layout.detached).toEqual(["x", "y"]);
+ const treeH = 2 * H + GY;
+ const detachedTop = PAD + treeH + GY + CHART_DETACHED_LABEL_H;
+ expect(layout.detachedTop).toBe(detachedTop);
+ expect(at(layout, "x")).toMatchObject({
+ x: PAD,
+ y: detachedTop,
+ detached: true,
+ parentId: null,
+ });
+ expect(at(layout, "y")).toMatchObject({ x: PAD + W + GX, y: detachedTop, detached: true });
+ expect(layout.edges.map((e) => e.toId)).toEqual(["a"]);
+ // The row is the wider block, so the one-card-wide tree is centred on it.
+ expect(layout.width).toBe(2 * W + GX + 2 * PAD);
+ expect(centre(at(layout, "ceo"))).toBe(layout.width / 2);
+ expect(at(layout, "a").x).toBe(at(layout, "ceo").x);
+ expect(layout.height).toBe(detachedTop + H + PAD);
+ });
+
+ it("a missing CEO gives a detached row alone, with room for its label and no tree above", () => {
+ const layout = layoutOrgTree(employees.slice(1), "ceo");
+ expect(layout.nodes.every((n) => n.detached)).toBe(true);
+ expect(layout.detachedTop).toBe(PAD + CHART_DETACHED_LABEL_H);
+ expect(layout.edges).toEqual([]);
+ expect(layout.width).toBe(4 * W + 3 * GX + 2 * PAD);
+ expect(layout.height).toBe(PAD + CHART_DETACHED_LABEL_H + H + PAD);
+ });
+
+ it("nobody at all is an empty drawing", () => {
+ expect(layoutOrgTree([], "ceo")).toMatchObject({
+ width: 2 * PAD,
+ height: PAD,
+ nodes: [],
+ edges: [],
+ detached: [],
+ detachedTop: null,
+ });
+ });
+
+ it("draws every connector from the parent's bottom centre through the rail to the child's top centre", () => {
+ const layout = layoutOrgTree(employees, "ceo");
+ expect(layout.edges.map((e) => `${e.fromId}>${e.toId}`).sort()).toEqual([
+ "ceo>cfo",
+ "ceo>cto",
+ "cto>dev1",
+ "cto>dev2",
+ ]);
+ for (const edge of layout.edges) {
+ const from = at(layout, edge.fromId);
+ const to = at(layout, edge.toId);
+ const railY = from.y + H + GY / 2;
+ expect(edge.path.startsWith(`M ${centre(from)} ${from.y + H} V `)).toBe(true);
+ expect(edge.path.endsWith(` V ${to.y}`)).toBe(true);
+ expect(edge.path.includes(` ${railY} `)).toBe(true);
+ // The horizontal run stops a corner short of the child's centre on the child's side.
+ const dir = centre(to) > centre(from) ? 1 : -1;
+ expect(edge.path.includes(` H ${centre(to) - dir * CHART_EDGE_RADIUS} `)).toBe(true);
+ }
+ });
+
+ it("is deterministic", () => {
+ expect(layoutOrgTree(employees, "ceo")).toEqual(layoutOrgTree(employees, "ceo"));
+ });
+});
+
+describe("connectorPath", () => {
+ it("is a straight drop when the two centres line up", () => {
+ expect(connectorPath(100, 50, 100, 150, 100)).toBe("M 100 50 V 150");
+ });
+
+ it("turns twice with rounded corners otherwise, in either direction", () => {
+ const r = CHART_EDGE_RADIUS;
+ expect(connectorPath(100, 50, 300, 150, 100)).toBe(
+ `M 100 50 V ${100 - r} Q 100 100 ${100 + r} 100 H ${300 - r} Q 300 100 300 ${100 + r} V 150`,
+ );
+ expect(connectorPath(300, 50, 100, 150, 100)).toBe(
+ `M 300 50 V ${100 - r} Q 300 100 ${300 - r} 100 H ${100 + r} Q 100 100 100 ${100 + r} V 150`,
+ );
+ });
+
+ it("shrinks the corners when the horizontal run is shorter than two radii", () => {
+ expect(connectorPath(0, 0, 6, 100, 50)).toBe("M 0 0 V 47 Q 0 50 3 50 H 3 Q 6 50 6 53 V 100");
+ });
+});
+
+describe("workspaceTail", () => {
+ it("keeps `.` and returns the last segment of a path", () => {
+ expect(workspaceTail(".")).toBe(".");
+ expect(workspaceTail("")).toBe(".");
+ expect(workspaceTail("docs/site")).toBe("site");
+ expect(workspaceTail("/home/u/proj/")).toBe("proj");
+ expect(workspaceTail("C:\\work\\repo")).toBe("repo");
+ });
+});
diff --git a/packages/web/test/org-draft.test.ts b/packages/web/test/org-draft.test.ts
new file mode 100644
index 00000000..274d5e31
--- /dev/null
+++ b/packages/web/test/org-draft.test.ts
@@ -0,0 +1,131 @@
+/**
+ * org-draft.ts unit tests: the key's user and Project scope, the defensive parse of whatever
+ * is in storage, what counts as a draft worth keeping, and the round trip through an injected
+ * storage — including a storage that throws, which must cost the dialog nothing.
+ */
+import { describe, expect, it } from "vitest";
+import type { DraftStorage, OrgCreateDraft } from "../src/features/company/org-draft";
+import {
+ EMPTY_ORG_DRAFT,
+ clearOrgDraft,
+ hasContent,
+ loadOrgDraft,
+ orgDraftKey,
+ parseOrgDraft,
+ saveOrgDraft,
+ serializeOrgDraft,
+} from "../src/features/company/org-draft";
+
+const draft = (over: Partial<OrgCreateDraft> = {}): OrgCreateDraft => ({
+ ...EMPTY_ORG_DRAFT,
+ mission: "Ship the marketplace",
+ ...over,
+});
+
+function memoryStorage(initial: Record<string, string> = {}): DraftStorage & {
+ map: Map<string, string>;
+} {
+ const map = new Map(Object.entries(initial));
+ return {
+ map,
+ getItem: (k) => map.get(k) ?? null,
+ setItem: (k, v) => void map.set(k, v),
+ removeItem: (k) => void map.delete(k),
+ };
+}
+
+const throwingStorage: DraftStorage = {
+ getItem: () => {
+ throw new Error("private mode");
+ },
+ setItem: () => {
+ throw new Error("quota");
+ },
+ removeItem: () => {
+ throw new Error("quota");
+ },
+};
+
+describe("orgDraftKey", () => {
+ it("separates users and Projects, and gives a signed-out browser its own bucket", () => {
+ expect(orgDraftKey("alice", "p1")).toBe("penguin.orgCreateDraft.alice.p1");
+ expect(orgDraftKey("alice", "p1")).not.toBe(orgDraftKey("bob", "p1"));
+ expect(orgDraftKey("alice", "p1")).not.toBe(orgDraftKey("alice", "p2"));
+ expect(orgDraftKey(null, "p1")).toBe("penguin.orgCreateDraft..p1");
+ });
+});
+
+describe("hasContent", () => {
+ it("ignores the prefilled budget and reads every field the user types", () => {
+ expect(hasContent(EMPTY_ORG_DRAFT)).toBe(false);
+ expect(hasContent({ ...EMPTY_ORG_DRAFT, ceoBudget: "100" })).toBe(false);
+ expect(hasContent({ ...EMPTY_ORG_DRAFT, mission: " " })).toBe(false);
+ expect(hasContent({ ...EMPTY_ORG_DRAFT, mission: "x" })).toBe(true);
+ expect(hasContent({ ...EMPTY_ORG_DRAFT, orgId: "acme" })).toBe(true);
+ expect(hasContent({ ...EMPTY_ORG_DRAFT, workspace: "/w" })).toBe(true);
+ expect(hasContent({ ...EMPTY_ORG_DRAFT, model: { provider: "anthropic", modelId: "m" } })).toBe(
+ true,
+ );
+ });
+});
+
+describe("parseOrgDraft", () => {
+ it("round-trips a full draft", () => {
+ const d = draft({
+ orgId: "acme",
+ name: "Acme",
+ workspace: "/w",
+ model: { provider: "anthropic", modelId: "claude" },
+ ceoBudget: "250",
+ });
+ expect(parseOrgDraft(serializeOrgDraft(d))).toEqual(d);
+ });
+
+ it("answers nothing for absent, unparsable or empty stored values", () => {
+ expect(parseOrgDraft(null)).toBeNull();
+ expect(parseOrgDraft("")).toBeNull();
+ expect(parseOrgDraft("{oops")).toBeNull();
+ expect(parseOrgDraft("[]")).toBeNull();
+ expect(parseOrgDraft("null")).toBeNull();
+ expect(parseOrgDraft(serializeOrgDraft(EMPTY_ORG_DRAFT))).toBeNull();
+ });
+
+ it("keeps the fields it can read when others are the wrong shape", () => {
+ // The mission is the expensive field: a mangled model reference must not cost it.
+ expect(parseOrgDraft(JSON.stringify({ mission: "Ship it", model: 7, name: 3 }))).toEqual({
+ ...EMPTY_ORG_DRAFT,
+ mission: "Ship it",
+ });
+ expect(
+ parseOrgDraft(JSON.stringify({ orgId: "acme", model: { provider: "anthropic" } })),
+ ).toEqual({ ...EMPTY_ORG_DRAFT, orgId: "acme" });
+ });
+});
+
+describe("loadOrgDraft / saveOrgDraft / clearOrgDraft", () => {
+ it("stores a draft with content and removes the entry once it is empty again", () => {
+ const storage = memoryStorage();
+ const key = orgDraftKey("alice", "p1");
+ saveOrgDraft(key, draft(), storage);
+ expect(loadOrgDraft(key, storage)).toEqual(draft());
+ saveOrgDraft(key, EMPTY_ORG_DRAFT, storage);
+ expect(storage.map.has(key)).toBe(false);
+ expect(loadOrgDraft(key, storage)).toBeNull();
+ });
+
+ it("clears one key and leaves another user's draft alone", () => {
+ const storage = memoryStorage();
+ saveOrgDraft(orgDraftKey("alice", "p1"), draft(), storage);
+ saveOrgDraft(orgDraftKey("bob", "p1"), draft({ mission: "Bob's" }), storage);
+ clearOrgDraft(orgDraftKey("alice", "p1"), storage);
+ expect(loadOrgDraft(orgDraftKey("alice", "p1"), storage)).toBeNull();
+ expect(loadOrgDraft(orgDraftKey("bob", "p1"), storage)?.mission).toBe("Bob's");
+ });
+
+ it("degrades to no draft when storage throws", () => {
+ const key = orgDraftKey("alice", "p1");
+ expect(loadOrgDraft(key, throwingStorage)).toBeNull();
+ expect(() => saveOrgDraft(key, draft(), throwingStorage)).not.toThrow();
+ expect(() => clearOrgDraft(key, throwingStorage)).not.toThrow();
+ });
+});
diff --git a/packages/web/test/org-examples.test.ts b/packages/web/test/org-examples.test.ts
new file mode 100644
index 00000000..5ec849e8
--- /dev/null
+++ b/packages/web/test/org-examples.test.ts
@@ -0,0 +1,37 @@
+/**
+ * org-examples.ts: the four example missions offered under the create-organization
+ * dialog's mission field. The registry holds ids only and the chips are rendered from them,
+ * so an id with no entry in one of the dictionaries would render a blank chip rather than
+ * fail to compile — which is what this covers.
+ */
+import { describe, expect, it } from "vitest";
+import { ORG_EXAMPLES } from "../src/features/company/org-examples";
+import { zh } from "../src/lib/strings";
+import { en } from "../src/lib/strings-en";
+
+describe("organization mission examples", () => {
+ it("lists the four in their rendered order, each id once", () => {
+ const ids = ORG_EXAMPLES.map((example) => example.id);
+ expect(ids).toEqual(["research", "agentTuning", "cloudReseller", "mirror"]);
+ expect(new Set(ids).size).toBe(ids.length);
+ });
+
+ it("gives every example a name and a mission in both dictionaries", () => {
+ for (const dict of [zh, en]) {
+ for (const { id } of ORG_EXAMPLES) {
+ const copy = dict.company.missionExamples[id];
+ expect(copy.name).not.toBe("");
+ // The mission is what a click fills; the name is only the chip's one-line label, so
+ // a "mission" no longer than its own name is a copy mistake.
+ expect(copy.mission.length).toBeGreaterThan(copy.name.length);
+ }
+ }
+ });
+
+ it("keeps the names distinct, so four chips never read as one", () => {
+ for (const dict of [zh, en]) {
+ const names = ORG_EXAMPLES.map(({ id }) => dict.company.missionExamples[id].name);
+ expect(new Set(names).size).toBe(names.length);
+ }
+ });
+});
diff --git a/packages/web/test/org-sessions.test.ts b/packages/web/test/org-sessions.test.ts
new file mode 100644
index 00000000..7ca55558
--- /dev/null
+++ b/packages/web/test/org-sessions.test.ts
@@ -0,0 +1,344 @@
+/**
+ * The company sidebar's 工位 group (features/company/org-sessions.ts) and the development
+ * list's organization filter (session-grouping): a desk row per employee in chart order
+ * whether or not a desk exists, the session list's live status winning over both snapshots,
+ * the glyph a row draws, an employee's own state read from every Session the organization
+ * attributes to it — its ticket sessions included, though no list shows them as a group —
+ * the split of a loaded list into the user's own rows and the organizations', and the totals
+ * corrected by what that split hid.
+ */
+import { describe, expect, it } from "vitest";
+import type {
+ OrgChartResponse,
+ OrgSessionsResponse,
+ SessionCategoryCounts,
+ SessionInfo,
+ SessionStatus,
+} from "@prismshadow/penguin-server/api";
+import { deskRows, liveEmployeeStates, orgRowActivity } from "../src/features/company/org-sessions";
+import {
+ countsWithoutOrgSessions,
+ isOrgSession,
+ splitDevelopmentList,
+ withoutOrgSessions,
+} from "../src/lib/session-grouping";
+
+const liveStatuses = (entries: Record<string, SessionStatus>): ReadonlyMap<string, SessionStatus> =>
+ new Map(Object.entries(entries));
+
+const employee = (
+ agentId: string,
+ name: string,
+ extra: Partial<OrgChartResponse["employees"][number]> = {},
+): OrgChartResponse["employees"][number] => ({
+ agentId,
+ name,
+ title: "Engineer",
+ reportsTo: agentId === "ceo" ? null : "ceo",
+ workspace: ".",
+ state: "idle",
+ spend: { own: 0, cumulative: 0 },
+ ...extra,
+});
+
+const chart: OrgChartResponse = {
+ ceoAgentId: "ceo",
+ employees: [
+ employee("ceo", "Alice", {
+ title: "CEO",
+ state: "running",
+ desk: { sessionId: "s-ceo", workspace: "/w", openedAt: "2026-09-02T00:00:00Z" },
+ }),
+ employee("pm", "Product"),
+ employee("dev", "Dana"),
+ ],
+};
+
+const sessions: OrgSessionsResponse = {
+ desks: [
+ { agentId: "pm", name: "Product", sessionId: "s-pm", status: "compacting", workspace: "/w" },
+ {
+ agentId: "ceo",
+ name: "Alice",
+ sessionId: "s-ceo",
+ status: "idle",
+ workspace: "/w",
+ lastActiveAt: "2026-09-02T00:00:00Z",
+ },
+ ],
+ tickets: [
+ {
+ ticketId: "2026-09-docs",
+ title: "Docs",
+ status: "in_progress",
+ sessions: [
+ {
+ sessionId: "s-t1",
+ agentId: "pm",
+ status: "running",
+ lastActiveAt: "2026-09-03T08:00:00Z",
+ },
+ { sessionId: "s-t2", agentId: "ceo", status: "idle", title: "Write docs" },
+ ],
+ },
+ {
+ ticketId: "2026-09-site",
+ title: "Site",
+ status: "in_progress",
+ sessions: [
+ {
+ sessionId: "s-t3",
+ agentId: "dev",
+ status: "idle",
+ title: "Build the site",
+ lastActiveAt: "2026-09-03T09:00:00Z",
+ },
+ ],
+ },
+ { ticketId: "2026-09-empty", title: "Nothing yet", status: "proposed", sessions: [] },
+ ],
+};
+
+describe("deskRows", () => {
+ it("keeps chart order and lists an employee whose desk was never opened", () => {
+ expect(deskRows(chart, sessions)).toEqual([
+ { agentId: "ceo", name: "Alice", jobTitle: "CEO", sessionId: "s-ceo", status: "idle" },
+ {
+ agentId: "pm",
+ name: "Product",
+ jobTitle: "Engineer",
+ sessionId: "s-pm",
+ status: "compacting",
+ },
+ { agentId: "dev", name: "Dana", jobTitle: "Engineer", sessionId: null, status: "idle" },
+ ]);
+ });
+
+ it("falls back to the chart's own running state for a desk the sessions route has not listed", () => {
+ const rows = deskRows(chart, { desks: [], tickets: [] });
+ expect(rows[0]).toMatchObject({ agentId: "ceo", sessionId: "s-ceo", status: "running" });
+ expect(rows[2]).toMatchObject({ agentId: "dev", sessionId: null, status: "idle" });
+ });
+
+ it("stands in with the sessions route while no chart has been read", () => {
+ expect(deskRows(null, sessions).map((d) => d.agentId)).toEqual(["pm", "ceo"]);
+ expect(deskRows(null, undefined)).toEqual([]);
+ });
+
+ // The snapshots only move on an organization event, and a run ending publishes none: a desk
+ // that stopped would sit on "running" until an unrelated event happened to arrive.
+ it("takes the session list's live status over both snapshots", () => {
+ const live = liveStatuses({ "s-ceo": "running", "s-pm": "idle" });
+ expect(deskRows(chart, sessions, live).map((d) => [d.agentId, d.status])).toEqual([
+ ["ceo", "running"],
+ ["pm", "idle"],
+ // No desk session, so nothing live to read: the chart's own state stands.
+ ["dev", "idle"],
+ ]);
+ // The chart's desk id counts too, even before the sessions route has listed it.
+ expect(
+ deskRows(chart, { desks: [], tickets: [] }, liveStatuses({ "s-ceo": "idle" }))[0],
+ ).toMatchObject({ agentId: "ceo", status: "idle" });
+ // And without a chart, the sessions route's own rows take it as well.
+ expect(deskRows(null, sessions, liveStatuses({ "s-pm": "running" }))[0]).toMatchObject({
+ agentId: "pm",
+ status: "running",
+ });
+ });
+
+ it("falls back to the snapshot for a desk the session list has not loaded", () => {
+ expect(deskRows(chart, sessions, liveStatuses({})).map((d) => d.status)).toEqual([
+ "idle",
+ "compacting",
+ "idle",
+ ]);
+ });
+});
+
+describe("orgRowActivity", () => {
+ it("draws the live states and nothing when settled", () => {
+ expect(orgRowActivity("running")).toBe("running");
+ expect(orgRowActivity("compacting")).toBe("compacting");
+ expect(orgRowActivity("idle")).toBeNull();
+ });
+});
+
+describe("liveEmployeeStates", () => {
+ it("reads every Session the organization attributes to an employee, live status first", () => {
+ // The chart says the CEO is running; the live list has settled its desk and its ticket
+ // session, so the employee has stopped.
+ const states = liveEmployeeStates(
+ chart.employees,
+ sessions,
+ liveStatuses({ "s-ceo": "idle", "s-t2": "idle", "s-pm": "idle", "s-t1": "idle" }),
+ );
+ expect([...states]).toEqual([
+ ["ceo", "idle"],
+ ["pm", "idle"],
+ // Its only session (s-t3) is not loaded, so the snapshot's own status stands.
+ ["dev", "idle"],
+ ]);
+ });
+
+ it("is running while any of them is running or compacting", () => {
+ // The CEO's desk has settled and one of its ticket sessions has started: it is at work.
+ expect(
+ liveEmployeeStates(chart.employees, sessions, liveStatuses({ "s-t2": "running" })).get("ceo"),
+ ).toBe("running");
+ // Compaction is work too, and here it is the desk that is doing it.
+ expect(
+ liveEmployeeStates(chart.employees, sessions, liveStatuses({ "s-pm": "compacting" })).get(
+ "pm",
+ ),
+ ).toBe("running");
+ // The chart's own desk id counts even before the sessions route lists that desk.
+ expect(
+ liveEmployeeStates(
+ chart.employees,
+ { desks: [], tickets: [] },
+ liveStatuses({ "s-ceo": "running" }),
+ ).get("ceo"),
+ ).toBe("running");
+ });
+
+ it("falls back to the organization's snapshot, and then to the chart's own state", () => {
+ // Nothing live at all: the sessions route still says the desk is compacting and one of the
+ // ticket sessions is running.
+ const states = liveEmployeeStates(chart.employees, sessions);
+ expect(states.get("pm")).toBe("running");
+ // The CEO's snapshot rows have all settled, so the chart's stale "running" gives way.
+ expect(states.get("ceo")).toBe("idle");
+ // No sessions listing at all: only the chart's own state is left to go on.
+ expect(liveEmployeeStates(chart.employees, undefined).get("dev")).toBe("idle");
+ expect(liveEmployeeStates(chart.employees, undefined).get("ceo")).toBe("running");
+ });
+
+ it("leaves a budget-paused employee paused, whatever its sessions are doing", () => {
+ const paused = [{ agentId: "pm", state: "paused" as const, desk: { sessionId: "s-pm" } }];
+ expect(
+ liveEmployeeStates(paused, sessions, liveStatuses({ "s-pm": "running" })).get("pm"),
+ ).toBe("paused");
+ });
+});
+
+describe("isOrgSession", () => {
+ it("reads either mark, and an empty orgId as no organization", () => {
+ expect(isOrgSession({ orgId: "acme" })).toBe(true);
+ // The durable stamp still answers once the organization is deleted and `orgId` is gone.
+ expect(isOrgSession({ client: "org" })).toBe(true);
+ expect(isOrgSession({})).toBe(false);
+ expect(isOrgSession({ orgId: "" })).toBe(false);
+ expect(isOrgSession({ orgId: "", client: "web" })).toBe(false);
+ });
+});
+
+describe("splitDevelopmentList", () => {
+ const rows = [
+ { sessionId: "a" },
+ { sessionId: "s-ceo", orgId: "acme" },
+ { sessionId: "b", client: "web" },
+ { sessionId: "s-t1", orgId: "acme" },
+ // Its organization is gone, so nothing resolves an orgId for it any more.
+ { sessionId: "s-orphan", client: "org" },
+ ];
+
+ it("moves the organizations' rows into their own list, keeping order on both sides", () => {
+ expect(splitDevelopmentList(rows)).toEqual({
+ own: [{ sessionId: "a" }, { sessionId: "b", client: "web" }],
+ organization: [
+ { sessionId: "s-ceo", orgId: "acme" },
+ { sessionId: "s-t1", orgId: "acme" },
+ { sessionId: "s-orphan", client: "org" },
+ ],
+ });
+ });
+
+ it("treats an empty orgId as no organization", () => {
+ expect(withoutOrgSessions([{ sessionId: "a", orgId: "" }, { sessionId: "b" }])).toEqual([
+ { sessionId: "a", orgId: "" },
+ { sessionId: "b" },
+ ]);
+ });
+
+ it("hides the organizations' rows whatever the company-mode switches say", () => {
+ // There is no switch to pass any more: this list is the user's own conversations, and a
+ // Session the scheduler drives is not one whether or not company mode is on screen.
+ expect(withoutOrgSessions(rows).map((s) => s.sessionId)).toEqual(["a", "b"]);
+ });
+});
+
+describe("countsWithoutOrgSessions", () => {
+ const row = (over: Partial<SessionInfo>): SessionInfo =>
+ ({
+ sessionId: "s",
+ projectId: "p",
+ agentId: "ceo",
+ provider: "custom",
+ modelId: "m",
+ workspace: "/org",
+ approvalMode: "allow-all",
+ createdAt: "2026-09-02T00:00:00Z",
+ lastActiveAt: "2026-09-02T00:00:00Z",
+ status: "idle",
+ pendingApprovalCount: 0,
+ pendingFollowUpCount: 0,
+ hasTrace: true,
+ archived: false,
+ ...over,
+ }) as SessionInfo;
+ const counts = new Map<string, SessionCategoryCounts>([
+ ["ceo", { active: 3, subagent: 0, schedule: 0, benchmark: 0, archived: 1 }],
+ ["other", { active: 2, subagent: 0, schedule: 0, benchmark: 0, archived: 0 }],
+ ]);
+ const workspaceCounts = new Map<string, Readonly<Record<string, SessionCategoryCounts>>>([
+ ["ceo", { "/org": { active: 3, subagent: 0, schedule: 0, benchmark: 0, archived: 1 } }],
+ ["other", { "/w": { active: 2, subagent: 0, schedule: 0, benchmark: 0, archived: 0 } }],
+ ]);
+
+ it("subtracts each hidden row from its Agent's totals and from its Workspace's share", () => {
+ const out = countsWithoutOrgSessions(counts, workspaceCounts, [
+ row({ sessionId: "s-desk", orgId: "acme" }),
+ row({ sessionId: "s-old", orgId: "acme", archived: true }),
+ ]);
+ expect(out.byAgent.get("ceo")).toEqual({
+ active: 2,
+ subagent: 0,
+ schedule: 0,
+ benchmark: 0,
+ archived: 0,
+ });
+ expect(out.byWorkspace.get("ceo")?.["/org"]).toEqual({
+ active: 2,
+ subagent: 0,
+ schedule: 0,
+ benchmark: 0,
+ archived: 0,
+ });
+ // Another Agent's totals are untouched, and the store's own maps are never written into.
+ expect(out.byAgent.get("other")).toEqual({
+ active: 2,
+ subagent: 0,
+ schedule: 0,
+ benchmark: 0,
+ archived: 0,
+ });
+ expect(counts.get("ceo")).toEqual({
+ active: 3,
+ subagent: 0,
+ schedule: 0,
+ benchmark: 0,
+ archived: 1,
+ });
+ });
+
+ it("gives the maps straight back when nothing is hidden, and never counts below zero", () => {
+ expect(countsWithoutOrgSessions(counts, workspaceCounts, []).byAgent).toBe(counts);
+ const out = countsWithoutOrgSessions(counts, workspaceCounts, [
+ row({ agentId: "other", workspace: "/w", orgId: "acme" }),
+ row({ agentId: "other", workspace: "/w", orgId: "acme" }),
+ row({ agentId: "other", workspace: "/w", orgId: "acme" }),
+ ]);
+ expect(out.byAgent.get("other")?.active).toBe(0);
+ expect(out.byWorkspace.get("other")?.["/w"]?.active).toBe(0);
+ });
+});
diff --git a/packages/web/test/org-trigger.test.ts b/packages/web/test/org-trigger.test.ts
new file mode 100644
index 00000000..d7cf4fcd
--- /dev/null
+++ b/packages/web/test/org-trigger.test.ts
@@ -0,0 +1,102 @@
+/**
+ * The `[org_trigger]` banner's summary (features/chat/org-trigger.ts): built from core's
+ * own marker so the two cannot drift — the kind, the identifying subject per kind, the
+ * employee's id in front of its parenthesis, the fire time and the budget line; plus the
+ * parse chain's place for it in user-message-body (a trigger is never the user's own text).
+ */
+import { describe, expect, it } from "vitest";
+import { buildOrgTriggerMessage } from "@prismshadow/penguin-core/markers";
+import {
+ orgTriggerAgentId,
+ parseOrgTriggerMessage,
+ summarizeOrgTrigger,
+} from "../src/features/chat/org-trigger";
+import { parseUserMessageBody } from "../src/features/chat/user-message-body";
+
+describe("summarizeOrgTrigger", () => {
+ it("names the event and its fire time for a calendar trigger", () => {
+ const text = buildOrgTriggerMessage(
+ {
+ org: "acme",
+ employee: "pm (Product manager, reports to ceo)",
+ kind: "event",
+ event: "daily_standup",
+ firedAt: "2026-09-02T01:00:00Z",
+ budget: "$1.20 / $50",
+ },
+ "Check the board.",
+ );
+ const parsed = parseOrgTriggerMessage(text);
+ expect(parsed).not.toBeNull();
+ expect(summarizeOrgTrigger(parsed!.origin)).toEqual({
+ org: "acme",
+ kind: "event",
+ agentId: "pm",
+ subject: "daily_standup",
+ change: null,
+ firedAt: "2026-09-02T01:00:00Z",
+ budget: "$1.20 / $50",
+ });
+ expect(parsed!.rest).toBe("Check the board.");
+ });
+
+ it("names the message for a mention, the ticket and change for a notice, the ticket for work, nothing for init", () => {
+ const summary = (origin: Parameters<typeof buildOrgTriggerMessage>[0]) =>
+ summarizeOrgTrigger(parseOrgTriggerMessage(buildOrgTriggerMessage(origin, ""))!.origin);
+ expect(
+ summary({ org: "o", employee: "ceo", kind: "mention", message: "m-1 from user:alice" }),
+ ).toMatchObject({
+ subject: "m-1 from user:alice",
+ change: null,
+ firedAt: null,
+ });
+ expect(
+ summary({
+ org: "o",
+ employee: "ceo",
+ kind: "ticket_notice",
+ ticket: "2026-09-docs",
+ change: "assigned",
+ }),
+ ).toMatchObject({ subject: "2026-09-docs", change: "assigned" });
+ expect(
+ summary({
+ org: "o",
+ employee: "ceo",
+ kind: "ticket_work",
+ ticket: "2026-09-docs",
+ change: "done",
+ }),
+ ).toMatchObject({
+ subject: "2026-09-docs",
+ change: null,
+ });
+ expect(summary({ org: "o", employee: "ceo", kind: "init" })).toMatchObject({
+ subject: null,
+ budget: null,
+ });
+ });
+
+ it("reads the agent id off the employee line with or without its parenthesis", () => {
+ expect(orgTriggerAgentId("ceo")).toBe("ceo");
+ expect(orgTriggerAgentId("pm (Product manager, reports to ceo)")).toBe("pm");
+ });
+});
+
+describe("parseUserMessageBody with an organization trigger", () => {
+ it("strips the block, keeps the body and flags the message as a trigger", () => {
+ const text = buildOrgTriggerMessage(
+ { org: "o", employee: "ceo", kind: "init" },
+ "Confirm the mission.",
+ );
+ expect(parseUserMessageBody(text)).toEqual({
+ body: "Confirm the mission.",
+ scheduled: false,
+ orgTrigger: true,
+ });
+ });
+
+ it("leaves an ordinary message untouched", () => {
+ expect(parseUserMessageBody("hello")).toEqual({ body: "hello", scheduled: false });
+ });
+});
diff --git a/packages/web/test/overview-summary.test.ts b/packages/web/test/overview-summary.test.ts
new file mode 100644
index 00000000..6aae03f5
--- /dev/null
+++ b/packages/web/test/overview-summary.test.ts
@@ -0,0 +1,398 @@
+/**
+ * The overview page's shaping (features/company/overview-summary.ts): the employee counts,
+ * the board as a segmented bar, today's timeline with its marks, the spend against the
+ * budget, the inbox rows with their order and filters, the first-steps decision and the
+ * mission fold's guess.
+ */
+import { describe, expect, it } from "vitest";
+import type {
+ OrgChannelMessage,
+ OrgEmployeeState,
+ OrgInbox,
+ OrgTicketItem,
+} from "@prismshadow/penguin-server/api";
+import {
+ BOARD_SEGMENT_TONE,
+ FIRST_STEPS,
+ INBOX_ROWS,
+ TIMELINE_TONE,
+ boardSummary,
+ employeeCounts,
+ firstSteps,
+ inboxCounts,
+ inboxMatches,
+ inboxRows,
+ missionClampedGuess,
+ spendSummary,
+ todaySummary,
+} from "../src/features/company/overview-summary";
+import { TICKET_COLUMNS } from "../src/features/company/ticket-board";
+
+const ticket = (ticketId: string, extra: Partial<OrgTicketItem> = {}): OrgTicketItem => ({
+ ticketId,
+ title: ticketId,
+ status: "review",
+ owner: "user:alice",
+ notify: [],
+ priority: "P1",
+ sessions: [],
+ running: false,
+ cost: 0,
+ ...extra,
+});
+
+const roster = [
+ { agentId: "a", state: "running", desk: { sessionId: "s1", workspace: "/w", openedAt: "t" } },
+ { agentId: "b", state: "idle", desk: { sessionId: "s2", workspace: "/w", openedAt: "t" } },
+ { agentId: "c", state: "paused" },
+ { agentId: "d", state: "idle" },
+] as const;
+
+describe("employeeCounts", () => {
+ it("counts desks, running and budget-paused employees", () => {
+ expect(employeeCounts(roster)).toEqual({ total: 4, onDesk: 2, running: 1, paused: 1 });
+ });
+
+ it("counts the live states where they are known, and the snapshot's for the rest", () => {
+ // "a" finished (the chart still says running), "d" started, "c" stays budget-paused.
+ const live = new Map<string, OrgEmployeeState>([
+ ["a", "idle"],
+ ["d", "running"],
+ ]);
+ expect(employeeCounts(roster, live)).toEqual({ total: 4, onDesk: 2, running: 1, paused: 1 });
+ expect(employeeCounts(roster, new Map([["a", "idle"]]))).toMatchObject({
+ running: 0,
+ paused: 1,
+ });
+ });
+
+ it("is all zeros for no employees", () => {
+ expect(employeeCounts([])).toEqual({ total: 0, onDesk: 0, running: 0, paused: 0 });
+ });
+});
+
+describe("boardSummary", () => {
+ it("lists every column in lifecycle order with its share of the whole board", () => {
+ const b = boardSummary({ proposed: 1, in_progress: 2, review: 1, done: 4, rejected: 0 });
+ expect(b.total).toBe(8);
+ expect(b.open).toBe(4);
+ expect(b.segments.map((s) => s.status)).toEqual([...TICKET_COLUMNS]);
+ expect(b.segments.map((s) => s.count)).toEqual([1, 2, 1, 4, 0]);
+ expect(b.segments.reduce((n, s) => n + s.share, 0)).toBeCloseTo(1);
+ expect(b.segments[4]?.share).toBe(0);
+ });
+
+ it("treats a missing column as zero and an empty board as no shares", () => {
+ const b = boardSummary({});
+ expect(b.total).toBe(0);
+ expect(b.open).toBe(0);
+ expect(b.segments.every((s) => s.count === 0 && s.share === 0)).toBe(true);
+ });
+
+ it("gives every column a fill tone", () => {
+ for (const status of TICKET_COLUMNS) expect(BOARD_SEGMENT_TONE[status]).toBeTruthy();
+ });
+});
+
+describe("todaySummary", () => {
+ it("orders instances by time, marks unevaluated ones upcoming, and buckets the outcomes", () => {
+ const t = todaySummary([
+ { agentId: "a", name: "later", nextFireAt: "2026-09-02T15:00:00Z" },
+ {
+ agentId: "b",
+ name: "fired",
+ title: "Board review",
+ lastFiredAt: "2026-09-02T08:00:00Z",
+ nextFireAt: "2026-09-03T08:00:00Z",
+ lastOutcome: "fired",
+ },
+ { agentId: "c", name: "missed", lastFiredAt: "2026-09-02T09:00:00Z", lastOutcome: "missed" },
+ { agentId: "d", name: "errored", lastFiredAt: "2026-09-02T10:00:00Z", lastOutcome: "error" },
+ { agentId: "e", name: "queued", lastFiredAt: "2026-09-02T11:00:00Z", lastOutcome: "queued" },
+ { agentId: "f", name: "paused", lastFiredAt: "2026-09-02T12:00:00Z", lastOutcome: "paused" },
+ { agentId: "g", name: "untimed" },
+ ]);
+ expect(t.total).toBe(7);
+ expect(t.entries.map((e) => e.key)).toEqual([
+ "b/fired",
+ "c/missed",
+ "d/errored",
+ "e/queued",
+ "f/paused",
+ "a/later",
+ "g/untimed",
+ ]);
+ expect(t.entries[0]).toMatchObject({ title: "Board review", mark: "fired" });
+ expect(t.entries[5]).toMatchObject({ title: "later", mark: "upcoming" });
+ expect(t.entries[6]).toMatchObject({ at: null, mark: "upcoming" });
+ expect({
+ fired: t.fired,
+ queued: t.queued,
+ failed: t.failed,
+ paused: t.paused,
+ upcoming: t.upcoming,
+ }).toEqual({ fired: 1, queued: 1, failed: 2, paused: 1, upcoming: 2 });
+ });
+
+ it("prefers the last firing's time over the next one", () => {
+ const t = todaySummary([
+ {
+ agentId: "a",
+ name: "x",
+ lastFiredAt: "2026-09-02T08:00:00Z",
+ nextFireAt: "2026-09-03T08:00:00Z",
+ lastOutcome: "fired",
+ },
+ ]);
+ expect(t.entries[0]?.at).toBe(Date.parse("2026-09-02T08:00:00Z"));
+ });
+
+ it("gives every mark a tone, failures in danger", () => {
+ expect(TIMELINE_TONE.missed).toBe("danger");
+ expect(TIMELINE_TONE.error).toBe("danger");
+ expect(TIMELINE_TONE.fired).toBe("success");
+ expect(TIMELINE_TONE.upcoming).toBe("attention");
+ });
+});
+
+describe("spendSummary", () => {
+ it("derives the ratio and the remainder from a budget", () => {
+ expect(spendSummary({ cost: 25, budget: 100 })).toEqual({
+ cost: 25,
+ budget: 100,
+ ratio: 0.25,
+ remaining: 75,
+ });
+ });
+
+ it("keeps the server's ratio when it sends one and reports overspend as a negative remainder", () => {
+ expect(spendSummary({ cost: 120, budget: 100, ratio: 1.2 })).toEqual({
+ cost: 120,
+ budget: 100,
+ ratio: 1.2,
+ remaining: -20,
+ });
+ });
+
+ it("has no ratio or remainder without a budget", () => {
+ expect(spendSummary({ cost: 3 })).toEqual({
+ cost: 3,
+ budget: null,
+ ratio: null,
+ remaining: null,
+ });
+ expect(spendSummary({ cost: 3, budget: 0 })).toEqual({
+ cost: 3,
+ budget: null,
+ ratio: null,
+ remaining: null,
+ });
+ });
+});
+
+const ME = "user:alice";
+
+const message = (
+ id: string,
+ time: string,
+ extra: Partial<OrgChannelMessage> = {},
+): OrgChannelMessage => ({
+ id,
+ time,
+ sender: "agent:bob",
+ hop: 0,
+ text: id,
+ mentions: [ME],
+ ...extra,
+});
+
+/** The page's own naming is not what these tests are about: principals stand for themselves. */
+const inbox = (source: Partial<OrgInbox> = {}) =>
+ inboxRows({
+ inbox: { mentions: [], blockedTickets: [], doneTickets: [], ...source },
+ names: (principal) => principal,
+ });
+
+/** One row of each category, plus a done ticket whose id carries no date and that never got stamped closed. */
+const mixed = () =>
+ inbox({
+ mentions: [
+ message("m1", "2026-09-01T08:00:00Z", { text: "standup done" }),
+ message("m2", "2026-09-07T09:00:00Z", { text: " \n@alice ping\nsecond line" }),
+ ],
+ blockedTickets: [
+ ticket("2026-09-06-blocked", {
+ status: "in_progress",
+ blocked: "waiting on legal",
+ blockedBy: "agent:carol",
+ }),
+ ],
+ doneTickets: [
+ { ...ticket("2026-09-05-done", { status: "done", owner: "agent:carol" }) },
+ { ...ticket("nodate", { status: "done" }) },
+ ],
+ });
+
+describe("inboxRows", () => {
+ it("orders by time descending and leaves an undated row last", () => {
+ expect(mixed().map((r) => r.key)).toEqual([
+ "mention/m2",
+ "blocked/2026-09-06-blocked",
+ "done/2026-09-05-done",
+ "mention/m1",
+ "done/nodate",
+ ]);
+ });
+
+ it("ranks rows of the same instant by category: what names you, then what is stuck, then what landed", () => {
+ const at = "2026-09-06T00:00:00.000Z";
+ const rows = inbox({
+ mentions: [message("m", at)],
+ blockedTickets: [ticket("2026-09-06-b", { blocked: "waiting" })],
+ doneTickets: [{ ...ticket("2026-09-06-d", { status: "done" }), closedAt: at }],
+ });
+ expect(rows.map((r) => r.category)).toEqual(["mention", "blocked", "done"]);
+ });
+
+ it("produces the three categories, each pointing at what it is about", () => {
+ const rows = mixed();
+ // A mention leads with its first line that carries anything, and names its sender.
+ expect(rows.find((r) => r.key === "mention/m2")).toMatchObject({
+ category: "mention",
+ title: "@alice ping",
+ detail: "agent:bob",
+ tone: "attention",
+ target: { kind: "channel", channelId: "default_channel" },
+ });
+ // A blocked ticket says why it is stuck, then who it waits on.
+ expect(rows.find((r) => r.key === "blocked/2026-09-06-blocked")).toMatchObject({
+ category: "blocked",
+ title: "2026-09-06-blocked",
+ detail: "waiting on legal · agent:carol",
+ tone: "attention",
+ target: { kind: "ticket", ticketId: "2026-09-06-blocked" },
+ });
+ // A done ticket asks nothing of the reader: its owner as the aside, and a muted mark.
+ expect(rows.find((r) => r.key === "done/2026-09-05-done")).toMatchObject({
+ category: "done",
+ detail: "agent:carol",
+ tone: "muted",
+ target: { kind: "ticket", ticketId: "2026-09-05-done" },
+ });
+ });
+
+ it("carries whichever half of a blocked ticket's aside was recorded, and none of neither", () => {
+ const rows = inbox({
+ blockedTickets: [
+ ticket("2026-09-01-reason", { blocked: "waiting on legal" }),
+ ticket("2026-09-02-who", { blocked: " ", blockedBy: "agent:carol" }),
+ ticket("2026-09-03-nothing"),
+ ],
+ });
+ expect(rows.find((r) => r.key === "blocked/2026-09-01-reason")?.detail).toBe(
+ "waiting on legal",
+ );
+ expect(rows.find((r) => r.key === "blocked/2026-09-02-who")?.detail).toBe("agent:carol");
+ expect(rows.find((r) => r.key === "blocked/2026-09-03-nothing")?.detail).toBeUndefined();
+ });
+
+ it("dates a ticket by when it was closed, falling back to its id's day and then to nothing", () => {
+ const rows = mixed();
+ expect(rows.find((r) => r.key === "blocked/2026-09-06-blocked")?.time).toBe(
+ "2026-09-06T00:00:00.000Z",
+ );
+ expect(rows.find((r) => r.key === "done/2026-09-05-done")?.time).toBe(
+ "2026-09-05T00:00:00.000Z",
+ );
+ expect(rows.find((r) => r.key === "done/nodate")?.time).toBeNull();
+ const closed = inbox({
+ doneTickets: [
+ { ...ticket("2026-09-05-done", { status: "done" }), closedAt: "2026-09-08T10:00:00Z" },
+ ],
+ });
+ expect(closed[0]?.time).toBe("2026-09-08T10:00:00Z");
+ });
+
+ it("is empty for an inbox a server older than the field did not send", () => {
+ expect(inboxRows({ inbox: undefined, names: (p) => p })).toEqual([]);
+ expect(inbox()).toEqual([]);
+ });
+
+ it("keeps the newest rows when there are more than the cap", () => {
+ const many = Array.from({ length: INBOX_ROWS + 20 }, (_, i) =>
+ message(`m${i}`, new Date(Date.UTC(2026, 0, 1, 0, i)).toISOString()),
+ );
+ const rows = inbox({ mentions: many });
+ expect(rows).toHaveLength(INBOX_ROWS);
+ expect(rows[0]?.key).toBe(`mention/m${INBOX_ROWS + 19}`);
+ });
+});
+
+describe("inbox filters", () => {
+ it("counts the rows each chip would show", () => {
+ expect(inboxCounts(mixed())).toEqual({ all: 5, mention: 2, blocked: 1, done: 2 });
+ });
+
+ it("admits everything under all, and one category under each of the rest", () => {
+ const rows = mixed();
+ expect(rows.every((r) => inboxMatches(r, "all"))).toBe(true);
+ expect(rows.filter((r) => inboxMatches(r, "done")).map((r) => r.key)).toEqual([
+ "done/2026-09-05-done",
+ "done/nodate",
+ ]);
+ expect(rows.filter((r) => inboxMatches(r, "blocked"))).toHaveLength(1);
+ });
+});
+
+describe("firstSteps", () => {
+ it("is fresh while nobody but the CEO is employed and the board is empty", () => {
+ const s = firstSteps({
+ employeeCount: 1,
+ boardTotal: 0,
+ ceoDeskOpened: true,
+ calendarCount: 0,
+ });
+ expect(s.fresh).toBe(true);
+ expect(s.done).toEqual({ ceo: true, hire: false, schedule: false });
+ expect(s.next).toBe("hire");
+ });
+
+ it("points at the CEO first when the desk was never opened", () => {
+ const s = firstSteps({
+ employeeCount: 1,
+ boardTotal: 0,
+ ceoDeskOpened: false,
+ calendarCount: 0,
+ });
+ expect(s.next).toBe("ceo");
+ });
+
+ it("stops being fresh once someone is hired or a ticket is filed", () => {
+ expect(
+ firstSteps({ employeeCount: 2, boardTotal: 0, ceoDeskOpened: true, calendarCount: 0 }).fresh,
+ ).toBe(false);
+ expect(
+ firstSteps({ employeeCount: 1, boardTotal: 1, ceoDeskOpened: true, calendarCount: 0 }).fresh,
+ ).toBe(false);
+ });
+
+ it("has no next step once all three are done", () => {
+ const s = firstSteps({
+ employeeCount: 3,
+ boardTotal: 0,
+ ceoDeskOpened: true,
+ calendarCount: 2,
+ });
+ expect(s.done).toEqual({ ceo: true, hire: true, schedule: true });
+ expect(s.next).toBeNull();
+ expect(FIRST_STEPS).toEqual(["ceo", "hire", "schedule"]);
+ });
+});
+
+describe("missionClampedGuess", () => {
+ it("offers the fold for a mission with a line break or one longer than a line", () => {
+ expect(missionClampedGuess("Ship the marketplace.")).toBe(false);
+ expect(missionClampedGuess("Ship it.\nThen tell everyone.")).toBe(true);
+ expect(missionClampedGuess("x".repeat(200))).toBe(true);
+ });
+});
diff --git a/packages/web/test/page-hints.test.ts b/packages/web/test/page-hints.test.ts
new file mode 100644
index 00000000..1704bc8f
--- /dev/null
+++ b/packages/web/test/page-hints.test.ts
@@ -0,0 +1,85 @@
+/**
+ * page-hints.ts unit tests: the key's user / Project / organization / page scope, the round
+ * trip through an injected storage, and the two ways a browser refuses to cooperate — a
+ * storage that throws, and one that silently drops the write. Both must read as "not
+ * dismissed" rather than throwing while an empty page renders.
+ */
+import { describe, expect, it } from "vitest";
+import type { HintStorage } from "../src/features/company/page-hints";
+import { dismissHint, hintKey, isHintDismissed } from "../src/features/company/page-hints";
+
+function memoryStorage(initial: Record<string, string> = {}): HintStorage & {
+ map: Map<string, string>;
+} {
+ const map = new Map(Object.entries(initial));
+ return {
+ map,
+ getItem: (k) => map.get(k) ?? null,
+ setItem: (k, v) => void map.set(k, v),
+ };
+}
+
+const throwingStorage: HintStorage = {
+ getItem: () => {
+ throw new Error("private mode");
+ },
+ setItem: () => {
+ throw new Error("quota");
+ },
+};
+
+describe("hintKey", () => {
+ it("names the user, the Project, the organization and the page", () => {
+ expect(hintKey("alice", "p1", "acme", "calendar")).toBe(
+ "penguin.orgPageHint.alice.p1.acme.calendar",
+ );
+ });
+
+ it("separates every scope it carries, and gives a signed-out browser its own bucket", () => {
+ const key = hintKey("alice", "p1", "acme", "calendar");
+ expect(key).not.toBe(hintKey("bob", "p1", "acme", "calendar"));
+ expect(key).not.toBe(hintKey("alice", "p2", "acme", "calendar"));
+ expect(key).not.toBe(hintKey("alice", "p1", "other", "calendar"));
+ expect(key).not.toBe(hintKey("alice", "p1", "acme", "tickets"));
+ expect(hintKey(null, "p1", "acme", "calendar")).toBe("penguin.orgPageHint..p1.acme.calendar");
+ });
+});
+
+describe("isHintDismissed / dismissHint", () => {
+ it("reads a hint nobody has dismissed as still standing", () => {
+ const storage = memoryStorage();
+ expect(isHintDismissed(hintKey("alice", "p1", "acme", "calendar"), storage)).toBe(false);
+ });
+
+ it("remembers the dismissal, and only for the hint that was dismissed", () => {
+ const storage = memoryStorage();
+ const calendar = hintKey("alice", "p1", "acme", "calendar");
+ const tickets = hintKey("alice", "p1", "acme", "tickets");
+ dismissHint(calendar, storage);
+ expect(isHintDismissed(calendar, storage)).toBe(true);
+ expect(isHintDismissed(tickets, storage)).toBe(false);
+ expect(isHintDismissed(hintKey("bob", "p1", "acme", "calendar"), storage)).toBe(false);
+ });
+
+ it("stays dismissed when it is dismissed twice", () => {
+ const storage = memoryStorage();
+ const key = hintKey("alice", "p1", "acme", "tickets");
+ dismissHint(key, storage);
+ dismissHint(key, storage);
+ expect(storage.map.size).toBe(1);
+ expect(isHintDismissed(key, storage)).toBe(true);
+ });
+
+ it("degrades to 'not dismissed' when storage throws, and the write costs the click nothing", () => {
+ const key = hintKey("alice", "p1", "acme", "calendar");
+ expect(() => dismissHint(key, throwingStorage)).not.toThrow();
+ expect(isHintDismissed(key, throwingStorage)).toBe(false);
+ });
+
+ it("degrades to 'not dismissed' when a write is silently dropped", () => {
+ const dropping: HintStorage = { getItem: () => null, setItem: () => undefined };
+ const key = hintKey("alice", "p1", "acme", "tickets");
+ dismissHint(key, dropping);
+ expect(isHintDismissed(key, dropping)).toBe(false);
+ });
+});
diff --git a/packages/web/test/remark-autolink-boundary.test.ts b/packages/web/test/remark-autolink-boundary.test.ts
index 7c6de1d9..33da63c8 100644
--- a/packages/web/test/remark-autolink-boundary.test.ts
+++ b/packages/web/test/remark-autolink-boundary.test.ts
@@ -1,8 +1,9 @@
/**
- * Where a bare URL ends. GFM's autolink literal stops at whitespace and trims a little ASCII
- * punctuation, which leaves CJK — the comma, the clause after it, or plain text run up against the
- * host — inside the href. These pin the boundary at the last ASCII character, and pin the two
- * things that must not change: explicit links, and URLs that are already fine.
+ * Where a bare URL ends. GFM's autolink literal stops at whitespace and only then trims trailing
+ * punctuation, so anything that follows the URL without a space — CJK text, a comma, the `**` that
+ * was meant to close a bold span — is swallowed into the href. These pin the boundary where GFM
+ * stopped looking, and pin the three things that must not change: explicit links, URLs that are
+ * already fine, and the markers a URL legitimately carries in its middle.
*/
import { describe, expect, it } from "vitest";
import React from "react";
@@ -26,6 +27,13 @@ function plainText(markdown: string): string {
).replace(/<[^>]*>/g, "");
}
+/** The rendered markup, for the assertions about which span a link ended up inside. */
+function html(markdown: string): string {
+ return renderToStaticMarkup(
+ React.createElement(ReactMarkdown, { remarkPlugins: REMARK_PLUGINS }, markdown),
+ );
+}
+
describe("a bare URL ends at the last ASCII character", () => {
it("stops before CJK punctuation, and the punctuation stays in the sentence", () => {
expect(firstLink("见 https://penguin.ooo,然后继续")).toEqual([
@@ -92,3 +100,81 @@ describe("what must not change", () => {
]);
});
});
+
+describe("a bare URL ends before a Markdown span marker", () => {
+ it("keeps the `**` a bold span opened out of the href", () => {
+ // The report: `**打开 <url>**查看`, where the closing `**` is followed by CJK rather than a
+ // space, so GFM's trail never fires and the href carries the two asterisks.
+ expect(firstLink("请**打开 http://127.0.0.1:4321/**查看")).toEqual([
+ "http://127.0.0.1:4321/",
+ "http://127.0.0.1:4321/",
+ ]);
+ // They go back to the sentence rather than disappearing. They stay literal there: a `**`
+ // between a `/` and a CJK character closes nothing under CommonMark's flanking rule, which
+ // is why `请**打开 abc/**查看` is not bold either.
+ expect(plainText("请**打开 http://127.0.0.1:4321/**查看")).toContain("**查看");
+ });
+
+ it("leaves the same sentence alone when the bold span did close", () => {
+ // A space after the closing `**` is all it takes: the emphasis resolves while parsing, the
+ // markers never reach the URL, and this pass has nothing to do.
+ const rendered = html("**打开 http://127.0.0.1:4321/** 看看");
+ expect(rendered).toContain("<strong>");
+ expect(firstLink("**打开 http://127.0.0.1:4321/** 看看")).toEqual([
+ "http://127.0.0.1:4321/",
+ "http://127.0.0.1:4321/",
+ ]);
+ });
+
+ it("ends before `*`, `~` and a backtick, which no URL ends with", () => {
+ expect(firstLink("见 http://x.test/?q=*看")).toEqual([
+ "http://x.test/?q=",
+ "http://x.test/?q=",
+ ]);
+ expect(firstLink("见 http://x.test/a~~好")).toEqual(["http://x.test/a", "http://x.test/a"]);
+ // A backtick is the one marker GFM's own trail does not know about, so it reaches the href
+ // even at the end of a line, where it arrives percent-encoded as `%60`.
+ expect(firstLink("见 http://x.test/`用法")).toEqual(["http://x.test/", "http://x.test/"]);
+ expect(firstLink("see http://x.test/`")).toEqual(["http://x.test/", "http://x.test/"]);
+ });
+
+ it("ends before a lone trailing `*` even with nothing to close", () => {
+ // GFM already does this one when the `*` ends the line, and the rule here is the same at a
+ // CJK boundary: a trailing `*` is never part of a URL, opener or no opener.
+ expect(firstLink("http://x.test/a*")).toEqual(["http://x.test/a", "http://x.test/a"]);
+ expect(plainText("http://x.test/a*")).toContain("*");
+ });
+
+ it("ends before a trailing `_` only when something opened one", () => {
+ // `_` is ordinary in a path, so a trailing one is only a closing marker if the paragraph
+ // spells an opener before the link.
+ expect(firstLink("_见 http://x.test/a_看")).toEqual(["http://x.test/a", "http://x.test/a"]);
+ expect(firstLink("见 http://x.test/a_看")).toEqual(["http://x.test/a_", "http://x.test/a_"]);
+ });
+
+ it("ends before a closer the URL never opened", () => {
+ expect(firstLink("见 http://x.test/a]看")).toEqual(["http://x.test/a", "http://x.test/a"]);
+ expect(firstLink("见 http://x.test/a>看")).toEqual(["http://x.test/a", "http://x.test/a"]);
+ });
+});
+
+describe("markers a URL legitimately carries", () => {
+ it("keeps `_` and `*` inside the URL, trimming only a trailing run", () => {
+ expect(firstLink("**see http://x.test/a_b**")).toEqual([
+ "http://x.test/a_b",
+ "http://x.test/a_b",
+ ]);
+ expect(html("**see http://x.test/a_b**")).toContain("<strong>");
+ expect(firstLink("_http://x.test/_")).toEqual(["http://x.test/", "http://x.test/"]);
+ expect(html("_http://x.test/_")).toContain("<em>");
+ });
+
+ it("keeps parentheses the URL balances itself", () => {
+ expect(firstLink("(http://x.test/a(b))")).toEqual(["http://x.test/a(b)", "http://x.test/a(b)"]);
+ // Same URL with CJK after the closing paren, which is where GFM's own balancing stops.
+ expect(firstLink("见 (http://x.test/a(b))看")).toEqual([
+ "http://x.test/a(b)",
+ "http://x.test/a(b)",
+ ]);
+ });
+});
diff --git a/packages/web/test/session-project.test.ts b/packages/web/test/session-project.test.ts
index c0506ae3..0f9d4771 100644
--- a/packages/web/test/session-project.test.ts
+++ b/packages/web/test/session-project.test.ts
@@ -1,6 +1,15 @@
+/**
+ * session-project.ts unit tests: the Project isolation of a deep-linked Session, the probe
+ * key that scopes a failed lookup to its Project, and how the chat page settles which Session
+ * the route names when the loaded list does not hold it.
+ */
import { describe, expect, it } from "vitest";
import type { SessionInfo } from "@prismshadow/penguin-server/api";
-import { sessionForProject, sessionProbeKey } from "../src/features/chat/session-project";
+import {
+ resolveRoutedSession,
+ sessionForProject,
+ sessionProbeKey,
+} from "../src/features/chat/session-project";
const SESSION: SessionInfo = {
sessionId: "session-a",
@@ -34,3 +43,28 @@ describe("Session Project isolation", () => {
);
});
});
+
+describe("resolveRoutedSession", () => {
+ const other: SessionInfo = { ...SESSION, sessionId: "session-b" };
+
+ it("takes the list's row when it holds one", () => {
+ expect(resolveRoutedSession("session-a", [other, SESSION], null)).toBe(SESSION);
+ });
+
+ it("prefers the list's row over the fetched one — the list is the row events keep current", () => {
+ const stale: SessionInfo = { ...SESSION, status: "running" };
+ expect(resolveRoutedSession("session-a", [SESSION], stale)).toBe(SESSION);
+ });
+
+ it("falls back to the fetched row, which is what survives a list reload dropping it", () => {
+ // An organization's desk opened from the org chart: never in the development list, and
+ // dropped from the store again by the next reload.
+ expect(resolveRoutedSession("session-a", [], SESSION)).toBe(SESSION);
+ expect(resolveRoutedSession("session-a", [other], SESSION)).toBe(SESSION);
+ });
+
+ it("ignores a fetched row for another id, and answers nothing without a route", () => {
+ expect(resolveRoutedSession("session-a", [], other)).toBeNull();
+ expect(resolveRoutedSession(null, [SESSION], SESSION)).toBeNull();
+ });
+});
diff --git a/packages/web/test/settings-sections.test.ts b/packages/web/test/settings-sections.test.ts
index 8339e7c0..dbec93bb 100644
--- a/packages/web/test/settings-sections.test.ts
+++ b/packages/web/test/settings-sections.test.ts
@@ -58,13 +58,14 @@ describe("visibleSettingsSections", () => {
"account",
"proxy",
"uploads",
+ "company",
"users",
]);
});
it("gives a non-admin their own pages and nothing server-global", () => {
- // Not "fewer pages" — the exact list. Proxy, upload limits and user management are
- // admin surfaces, and the whole point of dropping them is that a non-admin is never
+ // Not "fewer pages" — the exact list. Proxy, upload limits, the company-mode master
+ // switch and user management are admin surfaces, and the whole point of dropping them is that a non-admin is never
// told they exist. Updating is not among them either way: it lives in the sidebar user
// menu, outside this dialog, for every account.
expect(plain.map((s) => s.key)).toEqual(["profile", "general", "appearance", "account"]);
@@ -80,6 +81,7 @@ describe("visibleSettingsSections", () => {
"appearance",
"proxy",
"uploads",
+ "company",
]);
});
@@ -93,6 +95,7 @@ describe("visibleSettingsSections", () => {
"account",
"proxy",
"uploads",
+ "company",
]);
});
});
diff --git a/packages/web/test/shell-org-status.test.ts b/packages/web/test/shell-org-status.test.ts
new file mode 100644
index 00000000..a9877965
--- /dev/null
+++ b/packages/web/test/shell-org-status.test.ts
@@ -0,0 +1,39 @@
+/**
+ * The shell's organization status marks (features/company/shell-org-status.ts): which state
+ * an organization headlines and its tone, and what a session-list group renders so a failed
+ * fetch never leaves a skeleton behind.
+ */
+import { describe, expect, it } from "vitest";
+import {
+ ORG_STATUS_TONE,
+ groupRender,
+ orgStatusKind,
+} from "../src/features/company/shell-org-status";
+
+describe("orgStatusKind", () => {
+ it("ranks invalid configuration above paused, and paused above active", () => {
+ expect(orgStatusKind({ status: "active" })).toBe("active");
+ expect(orgStatusKind({ status: "paused" })).toBe("paused");
+ expect(orgStatusKind({ status: "paused", invalid: "bad chart" })).toBe("invalid");
+ expect(orgStatusKind({ status: "active", invalid: "bad chart" })).toBe("invalid");
+ });
+
+ it("maps the three states to danger, attention and success", () => {
+ expect(ORG_STATUS_TONE).toEqual({ invalid: "danger", paused: "attention", active: "success" });
+ });
+});
+
+describe("groupRender", () => {
+ it("shows the skeleton only until a fetch has completed", () => {
+ expect(groupRender({ loaded: false, settled: false, count: 0 })).toBe("loading");
+ });
+
+ it("shows the error line once a fetch completed without this group", () => {
+ expect(groupRender({ loaded: false, settled: true, count: 0 })).toBe("error");
+ });
+
+ it("shows the list or the empty line once the group is held", () => {
+ expect(groupRender({ loaded: true, settled: true, count: 0 })).toBe("empty");
+ expect(groupRender({ loaded: true, settled: false, count: 3 })).toBe("list");
+ });
+});
diff --git a/packages/web/test/ticket-board.test.ts b/packages/web/test/ticket-board.test.ts
new file mode 100644
index 00000000..a391b0d2
--- /dev/null
+++ b/packages/web/test/ticket-board.test.ts
@@ -0,0 +1,173 @@
+/**
+ * ticket-board.ts unit tests: the five columns in lifecycle order, card sorting (priority,
+ * then due, then id), the blocked-only filter and the search box, the counts the overview
+ * shows, which moves need a reason, the "blocked on me" selection, the shape of an id slug,
+ * the overdue test, the day read off a ticket id, and the invalid-ticket list.
+ */
+import { describe, expect, it } from "vitest";
+import type { OrgTicketItem, OrgTicketsResponse } from "@prismshadow/penguin-server/api";
+import {
+ TICKET_COLUMNS,
+ allTickets,
+ boardColumns,
+ canMove,
+ invalidTickets,
+ isBlocked,
+ isOverdue,
+ isTicketSlug,
+ isTicketStatus,
+ matchesTicketQuery,
+ moveNeedsReason,
+ sortTickets,
+ ticketCreatedDate,
+} from "../src/features/company/ticket-board";
+
+function ticket(over: Partial<OrgTicketItem> & { ticketId: string }): OrgTicketItem {
+ return {
+ title: over.ticketId,
+ status: "proposed",
+ owner: "user:alice",
+ notify: [],
+ priority: "P1",
+ sessions: [],
+ running: false,
+ cost: 0,
+ ...over,
+ };
+}
+
+function board(over: Partial<OrgTicketsResponse["columns"]> = {}): OrgTicketsResponse {
+ return {
+ columns: { proposed: [], in_progress: [], review: [], done: [], rejected: [], ...over },
+ invalidFiles: [],
+ };
+}
+
+describe("columns", () => {
+ it("are the five statuses in lifecycle order", () => {
+ expect([...TICKET_COLUMNS]).toEqual(["proposed", "in_progress", "review", "done", "rejected"]);
+ expect(isTicketStatus("review")).toBe(true);
+ expect(isTicketStatus("blocked")).toBe(false);
+ expect(isTicketStatus(null)).toBe(false);
+ });
+
+ it("sort cards by priority, then earlier due date, then id", () => {
+ const sorted = sortTickets([
+ ticket({ ticketId: "t3", priority: "P1", due: "2026-09-10" }),
+ ticket({ ticketId: "t1", priority: "P2" }),
+ ticket({ ticketId: "t4", priority: "P1", due: "2026-09-01" }),
+ ticket({ ticketId: "t2", priority: "P0" }),
+ ticket({ ticketId: "t0", priority: "P1" }),
+ ]);
+ expect(sorted.map((t) => t.ticketId)).toEqual(["t2", "t4", "t3", "t0", "t1"]);
+ });
+
+ it("boardColumns renders every column, filtered to blocked cards on request", () => {
+ const res = board({
+ proposed: [
+ ticket({ ticketId: "a" }),
+ ticket({ ticketId: "b", blocked: "waiting", blockedBy: "user:alice" }),
+ ],
+ review: [ticket({ ticketId: "c", status: "review" })],
+ });
+ expect(boardColumns(res).map((c) => c.tickets.map((t) => t.ticketId))).toEqual([
+ ["a", "b"],
+ [],
+ ["c"],
+ [],
+ [],
+ ]);
+ expect(
+ boardColumns(res, { blockedOnly: true }).map((c) => c.tickets.map((t) => t.ticketId)),
+ ).toEqual([["b"], [], [], [], []]);
+ expect(allTickets(res).map((t) => t.ticketId)).toEqual(["a", "b", "c"]);
+ });
+
+ it("the search box matches title, id, owner and parent, case-insensitively, and the owner's name through the chart", () => {
+ const t = ticket({
+ ticketId: "2026-09-02-site",
+ title: "Build the Marketplace site",
+ owner: "agent:mk_dev",
+ parent: "2026-09-02-launch",
+ });
+ const names = new Map([["mk_dev", "Dev"]]);
+ expect(matchesTicketQuery(t, "")).toBe(true);
+ expect(matchesTicketQuery(t, " marketplace ")).toBe(true);
+ expect(matchesTicketQuery(t, "09-02-site")).toBe(true);
+ expect(matchesTicketQuery(t, "mk_dev")).toBe(true);
+ expect(matchesTicketQuery(t, "launch")).toBe(true);
+ expect(matchesTicketQuery(t, "dev", names)).toBe(true);
+ expect(matchesTicketQuery(t, "seo")).toBe(false);
+ const res = board({
+ proposed: [t, ticket({ ticketId: "x", title: "SEO", blocked: "r" })],
+ done: [ticket({ ticketId: "y", title: "Marketplace launch post", status: "done" })],
+ });
+ expect(
+ boardColumns(res, { query: "market" }).map((c) => c.tickets.map((x) => x.ticketId)),
+ ).toEqual([["2026-09-02-site"], [], [], ["y"], []]);
+ // Both narrowings apply at once.
+ expect(
+ boardColumns(res, { query: "seo", blockedOnly: true }).map((c) =>
+ c.tickets.map((x) => x.ticketId),
+ ),
+ ).toEqual([["x"], [], [], [], []]);
+ });
+});
+
+describe("moves and blocks", () => {
+ it("only a move into rejected needs a reason, and a same-column drop is no move", () => {
+ expect(moveNeedsReason("rejected")).toBe(true);
+ expect(moveNeedsReason("done")).toBe(false);
+ expect(canMove("proposed", "proposed")).toBe(false);
+ expect(canMove("proposed", "in_progress")).toBe(true);
+ });
+
+ it("an empty blocked string is not blocked", () => {
+ expect(isBlocked(ticket({ ticketId: "a", blocked: "" }))).toBe(false);
+ expect(isBlocked(ticket({ ticketId: "b", blocked: "r" }))).toBe(true);
+ expect(isBlocked(ticket({ ticketId: "c" }))).toBe(false);
+ });
+});
+
+describe("id slug", () => {
+ it("accepts lowercase words joined by hyphens and nothing else", () => {
+ expect(isTicketSlug("marketplace")).toBe(true);
+ expect(isTicketSlug("marketplace-site")).toBe(true);
+ expect(isTicketSlug("a-b-c")).toBe(true);
+ // Digits are the date prefix's job, not the slug's.
+ expect(isTicketSlug("site2")).toBe(false);
+ expect(isTicketSlug("2026-site")).toBe(false);
+ expect(isTicketSlug("Marketplace")).toBe(false);
+ expect(isTicketSlug("marketplace site")).toBe(false);
+ expect(isTicketSlug("marketplace_site")).toBe(false);
+ expect(isTicketSlug("marketplace-")).toBe(false);
+ expect(isTicketSlug("-marketplace")).toBe(false);
+ expect(isTicketSlug("")).toBe(false);
+ expect(isTicketSlug("站点")).toBe(false);
+ });
+});
+
+describe("card facts", () => {
+ it("a due date is overdue only once today has passed it", () => {
+ expect(isOverdue("2026-09-01", "2026-09-02")).toBe(true);
+ expect(isOverdue("2026-09-02", "2026-09-02")).toBe(false);
+ expect(isOverdue("2026-09-03", "2026-09-02")).toBe(false);
+ expect(isOverdue(undefined, "2026-09-02")).toBe(false);
+ expect(isOverdue("soon", "2026-09-02")).toBe(false);
+ });
+
+ it("reads the creation day off the id and leaves other shapes alone", () => {
+ expect(ticketCreatedDate("2026-09-02-marketplace")).toBe("2026-09-02");
+ expect(ticketCreatedDate("2026-09-02-t-fb79d3")).toBe("2026-09-02");
+ expect(ticketCreatedDate("marketplace")).toBeNull();
+ expect(ticketCreatedDate("2026-09-02")).toBeNull();
+ });
+
+ it("lists the tickets the server flagged, in column order", () => {
+ const res = board({
+ proposed: [ticket({ ticketId: "a" }), ticket({ ticketId: "b", invalid: "duplicate id" })],
+ review: [ticket({ ticketId: "c", status: "review", invalid: "status mismatch" })],
+ });
+ expect(invalidTickets(res).map((t) => t.ticketId)).toEqual(["b", "c"]);
+ });
+});
diff --git a/packages/web/test/ticket-detail-load.test.ts b/packages/web/test/ticket-detail-load.test.ts
new file mode 100644
index 00000000..b4e82497
--- /dev/null
+++ b/packages/web/test/ticket-detail-load.test.ts
@@ -0,0 +1,85 @@
+/**
+ * The ticket detail is revealed only once the names it reads are in.
+ *
+ * The dialog fetches three things: the ticket itself, the organization's board and its roster.
+ * The owner, the parent, the children and every history line render an id until the last two
+ * land and a name afterwards — and an id and a name are different lengths, so revealing the
+ * ticket on its own reflows the whole panel a moment later, under a reader who has already
+ * started reading it. The skeleton therefore waits for both, and the roster's arrival is
+ * counted as settled whether it resolved or failed, so a failed fetch opens the dialog on the
+ * ids rather than holding the skeleton open for names that are never coming.
+ *
+ * Gating on the ticket alone is the state this came from and the obvious thing to simplify back
+ * to: the extra term looks redundant next to a fetch the code calls best effort. So the shape is
+ * parsed rather than trusted to the comment beside it — with the TypeScript parser, since which
+ * branch a condition guards is not a question a regex over the file can answer.
+ */
+import { describe, expect, it } from "vitest";
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import ts from "typescript";
+
+const FILE = fileURLToPath(new URL("../src/features/company/ticket-dialog.tsx", import.meta.url));
+
+/** Parse once; both checks ask a question about shape, not about text. */
+function parse(source: string): ts.SourceFile {
+ return ts.createSourceFile(FILE, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+}
+
+/** Whether `name` is called anywhere under `node`. */
+function calls(node: ts.Node, name: string): boolean {
+ if (ts.isCallExpression(node) && node.expression.getText() === name) return true;
+ return node.getChildren().some((child) => calls(child, name));
+}
+
+/** Every conditional whose "then" branch renders a `<Skeleton>`, as its condition's source text. */
+function skeletonGuards(source: string): string[] {
+ const tree = parse(source);
+ const guards: string[] = [];
+ const rendersSkeleton = (node: ts.Node): boolean => {
+ if (ts.isJsxSelfClosingElement(node) || ts.isJsxOpeningElement(node)) {
+ if (node.tagName.getText() === "Skeleton") return true;
+ }
+ return node.getChildren().some(rendersSkeleton);
+ };
+ const walk = (node: ts.Node): void => {
+ if (ts.isConditionalExpression(node) && rendersSkeleton(node.whenTrue)) {
+ guards.push(node.condition.getText());
+ }
+ ts.forEachChild(node, walk);
+ };
+ walk(tree);
+ return guards;
+}
+
+describe("the ticket detail's loading gate", () => {
+ const guards = skeletonGuards(readFileSync(FILE, "utf8"));
+
+ it("guards the skeleton on the ticket and on the roster it reads", () => {
+ expect(guards).toHaveLength(1);
+ const [guard] = guards as [string];
+ // The ticket, because there is nothing to show without it.
+ expect(guard).toMatch(/detail/);
+ // And the roster, because showing the ticket without it is what makes the panel jump.
+ expect(guard).toMatch(/contextReady/);
+ });
+
+ it("counts the roster as settled even when its fetch fails", () => {
+ // The marker belongs in a `finally`, not beside the successful assignment: a failed board or
+ // chart fetch has to open the dialog on the ids rather than leave the skeleton pulsing. Asked
+ // of the try/finally itself, so moving the call into the `try` fails here even though the
+ // word `finally` is still in the file a line above it.
+ const tries: ts.TryStatement[] = [];
+ const walk = (node: ts.Node): void => {
+ if (ts.isTryStatement(node)) tries.push(node);
+ ts.forEachChild(node, walk);
+ };
+ walk(parse(readFileSync(FILE, "utf8")));
+
+ const settling = tries.filter((t) => calls(t, "setContextOrg"));
+ expect(settling).toHaveLength(1);
+ const [statement] = settling as [ts.TryStatement];
+ expect(statement.finallyBlock && calls(statement.finallyBlock, "setContextOrg")).toBe(true);
+ expect(calls(statement.tryBlock, "setContextOrg")).toBe(false);
+ });
+});
diff --git a/packages/web/test/ticket-history.test.ts b/packages/web/test/ticket-history.test.ts
new file mode 100644
index 00000000..89880075
--- /dev/null
+++ b/packages/web/test/ticket-history.test.ts
@@ -0,0 +1,89 @@
+/**
+ * ticket-history.ts unit tests: the order and keys of the history rows the drawer lists, that
+ * a row carries only what happened and never the note the action wrote, and the per-list
+ * counts the two folded sections report.
+ */
+import { describe, expect, it } from "vitest";
+import type { OrgTicketDetail, OrgTicketHistoryEntry } from "@prismshadow/penguin-server/api";
+import { ticketHistoryRows, ticketSummaryCounts } from "../src/features/company/ticket-history";
+
+const entry = (over: Partial<OrgTicketHistoryEntry> = {}): OrgTicketHistoryEntry => ({
+ at: "2026-09-08T10:00:00.000Z",
+ by: "user:alice",
+ action: "created",
+ ...over,
+});
+
+describe("ticketHistoryRows", () => {
+ it("lists the newest first and keys every row apart", () => {
+ const rows = ticketHistoryRows([
+ entry({ at: "2026-09-08T10:00:00.000Z", action: "created" }),
+ entry({ at: "2026-09-08T11:00:00.000Z", action: "moved", note: "in_progress" }),
+ entry({ at: "2026-09-08T11:00:00.000Z", action: "moved", note: "review" }),
+ ]);
+ expect(rows.map((r) => r.action)).toEqual(["moved", "moved", "created"]);
+ expect(new Set(rows.map((r) => r.key)).size).toBe(3);
+ });
+
+ it("keeps who acted and when, and drops what the action wrote", () => {
+ const rows = ticketHistoryRows([
+ entry({ by: "agent:mk_dev", action: "progress", note: "drafted the schema" }),
+ ]);
+ expect(rows).toEqual([
+ {
+ key: "0-2026-09-08T10:00:00.000Z-progress",
+ at: "2026-09-08T10:00:00.000Z",
+ by: "agent:mk_dev",
+ action: "progress",
+ },
+ ]);
+ });
+
+ it("keeps an entry that predates the history's timestamps", () => {
+ expect(ticketHistoryRows([entry({ at: "" })])[0]!.at).toBe("");
+ });
+
+ it("is empty for a ticket with no history", () => {
+ expect(ticketHistoryRows([])).toEqual([]);
+ });
+});
+
+describe("ticketSummaryCounts", () => {
+ const detail = (
+ children: string[],
+ sessions: number,
+ ): Pick<OrgTicketDetail, "children" | "sessionItems"> => ({
+ children,
+ sessionItems: Array.from({ length: sessions }, (_, i) => ({
+ sessionId: `s${i}`,
+ agentId: "mk_dev",
+ status: "idle" as const,
+ })),
+ });
+
+ it("counts the children and the ticket's sessions", () => {
+ expect(ticketSummaryCounts(detail(["a", "b"], 3))).toEqual({
+ children: 2,
+ sessions: 3,
+ childrenEmpty: false,
+ sessionsEmpty: false,
+ });
+ });
+
+ it("reports each list's emptiness on its own, so one fold's count never speaks for the other", () => {
+ expect(ticketSummaryCounts(detail([], 0))).toEqual({
+ children: 0,
+ sessions: 0,
+ childrenEmpty: true,
+ sessionsEmpty: true,
+ });
+ expect(ticketSummaryCounts(detail([], 1))).toMatchObject({
+ childrenEmpty: true,
+ sessionsEmpty: false,
+ });
+ expect(ticketSummaryCounts(detail(["a"], 0))).toMatchObject({
+ childrenEmpty: false,
+ sessionsEmpty: true,
+ });
+ });
+});
diff --git a/plugins/README.md b/plugins/README.md
index 69a8dfb7..5919b984 100644
--- a/plugins/README.md
+++ b/plugins/README.md
@@ -11,11 +11,14 @@ Included plugins, by category (`PLUGIN_CATEGORIES` in `packages/core/src/plugins
| Office Productivity | `data-analysis`, `use-firecrawl`, `use-bento-slides`, `humanizer`, `goal`, `continual-learning` |
| Software Development | `software-development`, `use-claude-code` |
| AI App Development | `agent-development`, `model-development`, `skill-porting`, `agent-tuning` |
+| Agent Company | `agent-company` |
-`humanizer`, `use-claude-code` and `continual-learning` carry `preinstall: false`, so `default_agent` does not get them at initialization — they are installed from the library on demand. `goal` is the stop hook behind goal mode: its `start.mjs` writes the Session's `GOAL.json` and composes round 1, its `stop.mjs` reads the Trace after every Task and injects the next round or ends the goal. `continual-learning` hands a long task's condensed excerpt to a background subagent that folds the findings into the agent's skills.
+`humanizer`, `use-claude-code`, `continual-learning` and `agent-company` carry `preinstall: false`, so `default_agent` does not get them at initialization — they are installed from the library on demand (`agent-company` by the organization itself, when it creates the CEO and hires employees, or by hand onto any Agent that should be able to create one). `goal` is the stop hook behind goal mode: its `start.mjs` writes the Session's `GOAL.json` and composes round 1, its `stop.mjs` reads the Trace after every Task and injects the next round or ends the goal. `continual-learning` hands a long task's condensed excerpt to a background subagent that folds the findings into the agent's skills.
`agent-tuning` powers the self-improvement loop: create the Target Agent, design a Benchmark, evaluate it, optimize it to version N+1 with a snapshot before every round.
+`agent-company` is the whole toolkit of company mode, entry point included. `company-setup` is that entry point: the skill that creates an organization with the user, asking one question at a time and ending at `penguin org create`, leaving hiring and tickets to the CEO. `company-employee` is the protocol every desk and ticket session follows, and `company-ceo`, `company-hr` and `company-finance` are the playbooks of those titles. `company-mirror` is the sixth: the protocol a company of digital twins runs on instead, where every employee mirrors a real colleague and the company relays between people rather than filing tickets. Because the plugin is `preinstall: false`, `company-setup` is no longer on every Agent by default — an Agent gets it by installing `agent-company` from the library (the Agents page), and the CEO and the employees carry it already.
+
## Documentation
- [Skills & Plugins](https://penguin.ooo/docs/skills)
diff --git a/plugins/agent-company/icon.svg b/plugins/agent-company/icon.svg
new file mode 100644
index 00000000..81cab88a
--- /dev/null
+++ b/plugins/agent-company/icon.svg
@@ -0,0 +1,9 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
+ <rect x="8.5" y="3" width="7" height="5" rx="1" />
+ <rect x="2.5" y="16" width="7" height="5" rx="1" />
+ <rect x="14.5" y="16" width="7" height="5" rx="1" />
+ <path d="M12 8v4" />
+ <path d="M6 12h12" />
+ <path d="M6 12v4" />
+ <path d="M18 12v4" />
+</svg>
diff --git a/plugins/agent-company/package.json b/plugins/agent-company/package.json
new file mode 100644
index 00000000..6f35ba37
--- /dev/null
+++ b/plugins/agent-company/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "@penguinharness/agent-company",
+ "version": "0.2.11",
+ "description": "Company mode for PenguinHarness agents: creating the organization with the user, the employee protocol every desk and ticket session follows, plus the CEO, HR and finance playbooks for running an organization on calendar events, tickets, channels and budgets.",
+ "license": "Apache-2.0",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/Prism-Shadow/penguin-harness.git",
+ "directory": "plugins/agent-company"
+ },
+ "files": [
+ "plugin.json",
+ "icon.svg",
+ "skills",
+ "hooks",
+ "LICENSE"
+ ],
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/plugins/agent-company/plugin.json b/plugins/agent-company/plugin.json
new file mode 100644
index 00000000..5018bd16
--- /dev/null
+++ b/plugins/agent-company/plugin.json
@@ -0,0 +1,9 @@
+{
+ "description": "Run a Project's agents as a company: create the organization with the user one question at a time, then the employee protocol every desk and ticket session follows (trigger blocks, the ticket board, channel etiquette, budgets), plus the CEO, HR and finance playbooks — mission to tickets, hiring and calendars, budgets and cost audits — and the mirror protocol for a company of digital twins that relays between real people.",
+ "description_zh": "把 Project 里的 Agent 组织成一家公司:先与用户一问一答地创建组织,再是每个工位会话与工单会话都遵循的员工协议(触发块、工单看板、频道礼仪、预算),以及 CEO、人事与财务的操作手册——使命拆解为工单、招募与日程、预算与成本巡检——还有让数字分身在真人之间传话的镜像协议。",
+ "short_description": "Company setup plus the employee, CEO, HR, finance and mirror playbooks.",
+ "short_description_zh": "创建组织,以及员工、CEO、人事、财务、镜像公司的操作手册。",
+ "version": "2026.09.14.3",
+ "category": "agent-company",
+ "preinstall": false
+}
diff --git a/plugins/agent-company/skills/company-ceo/SKILL.md b/plugins/agent-company/skills/company-ceo/SKILL.md
new file mode 100644
index 00000000..697b7adb
--- /dev/null
+++ b/plugins/agent-company/skills/company-ceo/SKILL.md
@@ -0,0 +1,160 @@
+---
+name: company-ceo
+description: Run a PenguinHarness organization as its CEO — turn the mission into a ticket tree, hire HR and finance first, partition the shared workspace, schedule the calendar, open a channel per stream, review tickets and report to the board in the all-hands channel.
+---
+
+# Company CEO
+
+The CEO is the root of the employee tree: the one employee an organization is created with, whose budget is the whole organization's and whose duties are to turn the mission into tickets, hire, partition the workspace, accept and review tickets, and report to the board — the humans of the Project — in the all-hands channel. Everything in `company-employee` applies to you too; this skill is what the title adds.
+
+## Before you start
+
+If the message only names this skill without a concrete request, ask what the CEO should do — plan, hire, review, report. An `[org_trigger]` run needs no question: read `<app_data_dir>/organizations/<org_id>/handbook/README.md` and act; a `kind: init` run follows the checklist at the end of this skill.
+
+## Mission to tickets
+
+A ticket is the organization's unit of collective work; the mission becomes a tree of tickets, and the tree is what the board reads.
+
+- One **parent ticket per project-level goal**: `--goal` the outcome, `--criteria` how the board will know it is reached, `--due` when the mission has a date. Its owner is you or the employee who leads that stream. `--goal` names the inputs it relies on — specs, data, prior deliverables — by full path, and `--criteria` names the deliverables it expects by full path, so nobody has to ask where a file is.
+- **One owner per ticket.** `--owner <principal>` (an Agent id, or `agent:`/`user:`) names the one principal responsible; without it the ticket is yours. Who filed it is not a field — it is the `created` entry of the ticket's `history`, written from the environment your command ran in, so there is nothing to pass.
+- **Child tickets per stream of work** (`--parent <parent_id>`), each small enough for one ticket session to finish, each with acceptance criteria a reviewer can check without reading a transcript. `--priority P0` for what blocks everything else; `P2` is the default.
+- New tickets land in `proposed`. Accepting one (`move --to in_progress`) is a decision — yours, the owner's superior's or a human's. Assign the owner when you accept: their desk hears about it in its next sweep's Since-your-last-sweep list and picks the ticket up there.
+- **You file and assign; the owner's desk starts the work.** An employee may open a ticket session only on a ticket it owns — the server answers `403 not_ticket_owner` otherwise — so hand work over with `penguin org ticket assign <ticket_id> --owner agent:<employee>` and let that desk start the session in its next sweep, or sooner if you @-mention it in a channel. Run `penguin org ticket start` only for the tickets you own yourself.
+- Anyone may propose. Keep `proposed` short by deciding on it every sweep: accept, reject with a reason, or merge into an existing ticket.
+
+```bash
+penguin org ticket create --title "Launch the marketing site" --goal "A public site at the agreed domain" \
+ --criteria "Pages live; Lighthouse >= 90; analytics wired" --priority P1 --due 2026-09-30
+penguin org ticket create --title "Site: content" --goal "Copy for every page" --criteria "Reviewed by the CEO" \
+ --parent 2026-09-01-launch-the-marketing-site --owner agent:<org_id>_writer
+penguin org ticket move 2026-09-01-site-content --to in_progress
+# A title with no English words in it yields no slug; name the id yourself:
+penguin org ticket create --title "上线站点" --goal "…" --slug launch-the-site
+```
+
+A ticket's cost is the cost of its contributing sessions, rolled up along `parent`; `penguin org finance` shows each parent's total, so the tree is also the budget's structure.
+
+## Hiring
+
+Every employee is an Agent. Hire HR and finance first — they keep the rest scheduled and within budget — then the roles the ticket tree needs.
+
+```bash
+penguin org hire --new-agent <org_id>_hr --name "HR" --title "HR" --reports-to <org_id>_ceo \
+ --duties "Keep every employee's calendar populated; hire, evaluate and improve employees" --workspace people --budget 30
+penguin org hire --new-agent <org_id>_finance --name "Finance" --title "Finance" --reports-to <org_id>_ceo \
+ --duties "Set budgets, audit spend daily, explain alerts and propose savings" --workspace finance --budget 20
+penguin org hire --new-agent <org_id>_dev --name "Developer" --title "Developer" --reports-to <org_id>_ceo \
+ --duties "Own the implementation tickets" --workspace site --budget 80
+```
+
+- `--new-agent` creates the Agent in the Project with the `agent-company` and `agent-development` plugins installed by default — the protocol, and the `penguin` orchestration commands every employee needs; `--skills` adds library skills on top. `--agent-id` employs an Agent that already exists. Ids match `^[a-z][a-z0-9_]{1,63}$`; prefix them with `<org_id>_`.
+- `--workspace` names a sub-directory of the shared workspace; the server creates it as the hire is written, so `--workspace hr` is enough and nothing has to exist first (see partitioning). Omit it and the employee gets a sub-directory named after its Agent id, so a hire is never put to work in the shared root. `--reports-to` names an employee. Everyone reports to exactly one superior and the tree must not loop.
+- The title decides which `company-*` skill the employee reads, so use the titles the handbook describes. Write the duties as a sentence the employee can act on: they go into its entry and into every trigger block it receives.
+- Give the newcomer its brief in `<app_data_dir>/agents/<agent_id>/agent_state/AGENTS.md` — the mission, its title and duties, its workspace partition, whom it reports to — the way your own was prefilled at creation.
+- Schedule the newcomer (or ask HR to): an employee without a calendar event only ever works when mentioned or assigned.
+- Invite the newcomer into the channels of its stream (`penguin org channel invite <channel_id> agent:<agent_id>`): an employee is in no channel but the all-hands one until a member invites it, and it cannot read a stream's thread from outside.
+- `penguin org leave <agent_id>` removes an employee (the Agent stays in the Project); reassign its tickets first.
+
+## Partitioning the shared workspace
+
+The shared workspace is `<app_data_dir>/organizations/<org_id>/workspace/`. Its root is nobody's desk: it holds the shared inputs. Every desk works in a sub-directory of it — yours is `ceo` — so two employees never edit the same tree:
+
+1. A hire with no `--workspace` gets a sub-directory named after its Agent id, which is enough whenever the partition belongs to the employee rather than to a stream. Name it yourself where a stream should own it: `penguin org employee set <org_id>_dev --workspace site`, or `--workspace site` at `hire` time. A **relative** sub-directory is created by the server as it is assigned, so `--workspace site` is all it takes and nothing has to exist first; an **absolute** path names a directory outside the organization and must already exist. Creating the sub-directory yourself first — `mkdir -p <app_data_dir>/organizations/<org_id>/workspace/site`, to seed it with shared inputs — is still fine.
+2. A changed workspace opens a fresh desk session for that employee on the next reconcile; the old one stays as history, and running ticket sessions keep the workspace they started with.
+
+Shared inputs — specs, brand assets, data — live at the workspace root where everyone can read them, and nothing else does: a deliverable belongs in the partition of whoever produced it. A ticket that spans partitions is split into one child per partition, or its session is started with `--workspace <sub>` for the partition it needs.
+
+## One channel per stream
+
+Talk is partitioned the way the workspace is. `default_channel` is the all-hands channel — everyone is in it, and it is where the board reads — so a stream's day-to-day thread belongs in a channel of its own, opened at kickoff and holding exactly the people and employees that stream needs:
+
+```bash
+penguin org channel create ch_site --name "Site" --purpose "Building and shipping the marketplace site"
+penguin org channel invite ch_site agent:<org_id>_dev agent:<org_id>_writer
+penguin org channel create ch_marketing --name "Marketing" --purpose "SEO, the social launch and the paid slots"
+penguin org channel invite ch_marketing agent:<org_id>_marketer
+```
+
+- One channel per stream (`ch_site`, `ch_marketing`, `ch_finance` …), plus one for a ticket big enough to carry its own thread; ids follow `^[a-z][a-z0-9_]{1,63}$` and `default_channel` is taken. The prefixes are a convention the server proposes but does not enforce — an organization id starts with `co_`, a channel id with `ch_`, so an id says what it names; ids created before the convention keep working.
+- A new channel holds only its creator. Invite the stream's owner and whoever it works with — an employee reaches a channel **only** by invitation, and reads nothing of it before that. Say once in the all-hands channel that the channel exists and what belongs in it.
+- Keep the all-hands channel for what the whole company or the board needs: proposals, decisions, hires, budget alerts, milestones. Everything else has a home.
+- `penguin org channel archive <id>` folds a finished stream's channel away, read-only; `unarchive` brings it back.
+
+## Scheduling
+
+The calendar is the only recurring driver. Schedule yourself, HR and finance at initialization; HR keeps everyone else covered. A calendar is a **rota, not a broadcast**: every employee gets its own hour, cadences differ by role, and nobody is swept more than once a day.
+
+| Role | Cadence | Hour (organization timezone) |
+| --- | --- | --- |
+| CEO (you) | daily | 09:00 |
+| HR | every 3 days | 10:00 |
+| Finance | weekly | 16:00 |
+| Developers, writers, operators | daily | a distinct half-hour between 09:30 and 12:00 |
+| Reviewers, marketing, research | every 2–3 days | a distinct hour in the afternoon |
+
+Rules that follow from the table: never `--start-at now` for a recurring event (it pins everyone to the same minute); compute the next occurrence of the role's hour as an ISO instant with the organization's UTC offset; one recurring event per employee (a second one only for a different cadence, such as a weekly retrospective beside a daily sweep); no two employees on the same start minute; leave weekends to the weekly and 3-day cadences rather than adding events.
+
+- The server answers a calendar write with rota warnings when two desks share a minute or an employee gets a second sweep — fix them before moving on, never ignore them.
+
+```bash
+# Tomorrow 09:00 in Asia/Shanghai (UTC+8): write the instant with its offset.
+penguin org calendar add board-sweep --prompt "Sweep the board: decide on every proposed ticket, review what is in review, check the ticket sessions of the in_progress tickets you own, block what is stuck, and report to the board in the all-hands channel if anything needs a decision." --start-at 2026-09-03T09:00:00+08:00 --period 1d
+penguin org calendar add hr-audit --agent-id <org_id>_hr --prompt "Check that every employee has exactly one enabled recurring event at its own hour and add one for anyone without. Evaluate whoever finished a ticket since your last run." --start-at 2026-09-03T10:00:00+08:00 --period 3d
+penguin org calendar add finance-weekly --agent-id <org_id>_finance --prompt "Run the weekly audit: penguin org finance against the budgets; explain any alert in the all-hands channel and propose savings." --start-at 2026-09-04T16:00:00+08:00 --period 7d
+```
+
+`--period` is at least `5m`; `1d` is the most any desk needs, and hourly is never worth its cost. Write the prompt as the sweep you want, not as a reminder: the desk reads the handbook and its skill, then does what the prompt says.
+
+## Reviewing tickets
+
+`review` is where owners put finished work. Review against `## Acceptance criteria` and the artifacts in the workspace, then:
+
+- `penguin org ticket move <id> --to done` when the criteria hold — the `notify` list and the owner hear about it in their own next sweep; nothing is posted in a channel, because the board is read from the board;
+- `penguin org ticket move <id> --to rejected --reason "<what is missing>"` when they do not; the reason lands in `## Result`. Work worth retrying gets a new child ticket, or the owner writes a progress line and moves the ticket back to `in_progress`;
+- a ticket that has sat `in_progress` without a progress line for days is either blocked (ask the owner to `block` it with a reason) or abandoned (reassign it);
+- a ticket moved to `review` with an empty `sessions` list was done at somebody's desk: send it back with a progress line asking for a ticket session, because no work belongs at a desk. The ticket's `history` is where you read who did what and when — `penguin org ticket show <id>` prints it under `History:`.
+
+Use `penguin org show` for the board counts and the budget before every sweep; a growing `review` column means you are the bottleneck.
+
+## Decisions belong to the board
+
+Important decisions are proposed, not taken. Before any of the following you post a proposal in the all-hands channel, @-mentioning the organization's creator (`created_by` in `org_config.toml`, as `@user:<id>`), and **stop** — you act only after the board confirms:
+
+- your reading of the mission and the plan derived from it (streams, first tickets, priorities);
+- hiring: which roles, how many, with what budgets and models — the whole plan in one message, not one hire at a time;
+- budgets: setting or raising any employee's budget, or your own;
+- rejecting a ticket someone else proposed, or closing a P0 / P1 ticket as done without a review;
+- anything that reaches outside the organization — publishing, registering accounts, sending mail, spending money, changing `org_config.toml`;
+- changing this handbook's rules or the organization's structure (moving a subordinate to another manager, offboarding).
+
+Write the proposal so it can be answered in one line: what you propose, why, what it costs, and the alternatives you rejected, ending with the explicit question. Then end the run. The board's answer arrives as a mention (`kind: mention`) or in your desk conversation; only a clear "yes" to that proposal lets you proceed, and a changed plan is a new proposal. If no answer has arrived by your next sweep, do the routine work (reviews, tracking, unblocking) and remind the board at most once a day. Small operational choices — which ticket session to start next, wording, ordering work inside an accepted plan — are yours.
+
+## Reporting to the board
+
+The board is the humans of the Project. Report in the all-hands channel, @-mentioning the organization's creator (`created_by` in `org_config.toml`, as `@user:<id>`) — at most once per sweep, and only when there is something to decide or a milestone to report:
+
+```bash
+penguin org channel send -m "@user:alice Site launch: content done, build in review, domain blocked on you (2026-09-01-domain). Budget 41%. Decision needed: launch date." --ref-ticket 2026-09-01-launch-the-marketing-site
+```
+
+One message: what finished, what is blocked and on whom, spend against budget, the decision you need. Completions are not reported one by one — the sweep report carries them. Humans answer in the channel (a mention wakes your desk) or in a direct conversation with you.
+
+## The init work run
+
+A `kind: init` trigger is the first message of a new organization's CEO; its body is the mission and the initialization tasks.
+
+**First, read what kind of company the mission asks for.** If it says the organization **mirrors a real company** — a digital twin (数字分身) per real colleague, a company whose job is to relay between people rather than to produce anything of its own — follow `company-mirror` instead and skip the checklist below entirely: that company hires from the real org chart the board hands you, and it schedules nothing, files nothing and partitions nothing. Everything else is an ordinary mission; work through the following, in order:
+
+1. **Read the handbook**, then write ONE proposal to the board in the all-hands channel: your reading of the mission, the streams and first tickets you intend to file, the roles you intend to hire (HR and finance first) with their budgets and model, and how you will split the shared workspace. **Name your own budget in that proposal** — the `budget:` line of the trigger block is what the board gave you (100 USD per month unless creation said otherwise), and since budgets accumulate along the reporting line it is the whole company's cap: every salary you propose has to fit inside it. If the plan does not fit, say so and ask for the number you need instead of proposing hires that will pause the company. End with the question, @-mention the creator, and **end the run** — nothing is hired, scheduled or filed before the answer. Write it in the organization's working language, the one the handbook's 「工作语言」 / “Working language” section names — as you write every message, ticket, document and brief from here on; commands, ids, file names and field names stay ASCII.
+2. **When the board confirms** (a mention or a message in your desk conversation), hire HR and finance, then the confirmed roles (`penguin org hire --new-agent <org_id>_<role> …`, default plugins).
+3. **Partition the shared workspace** as confirmed. You work in `ceo/` and every hire lands in a sub-directory of its own, so this is only for the partitions a stream rather than an employee should own: `penguin org employee set <agent_id> --workspace <sub-directory>` — a relative sub-directory is created as it is assigned, so it need not exist first.
+4. **Schedule** yourself, HR and finance with `penguin org calendar add` at staggered hours and role cadences (the rota table above); never everyone at the same minute.
+5. **File the confirmed tickets**: the parent per goal and the first children per stream, owners assigned, accepted into `in_progress` only for what the board confirmed. Assigning is where the work starts moving — each owner's desk picks its tickets up in its next sweep; start a ticket session yourself only for a ticket you own.
+6. **Open one channel per stream** (`penguin org channel create ch_<stream> --name …`) and invite its owner (`penguin org channel invite ch_<stream> agent:<agent_id>`), so a stream's thread does not drown the all-hands channel.
+7. **Report** to the creator in one message in the all-hands channel: whom you hired, how the workspace is split, what is scheduled, which channels are open, which tickets are open — and the next decision, if any, you need from the board.
+
+## Cautions
+
+- **Do the ticket work in ticket sessions**, not at your desk: your desk is the organization's scheduler, and its context must survive for months.
+- **Your budget is the organization's.** Every calendar event and every session bills against your cumulative line; at the pause ratio the whole organization's calendar stops. Hire and schedule within it, and take finance's proposals seriously.
+- **The handbook is yours to keep current.** When you change a role convention — who reviews, which priorities skip review, which channel a stream talks in — change `handbook/README.md`: it is what every employee reads first. `handbook/` is the company's knowledge base: record every decision the board took as `decisions/<yyyy-mm-dd>-<slug>.md` (the question, the answer, what it changes) and list it in the index, so a later run — yours or anyone's — reads the decision instead of asking again.
diff --git a/plugins/agent-company/skills/company-employee/SKILL.md b/plugins/agent-company/skills/company-employee/SKILL.md
new file mode 100644
index 00000000..bdb6bcba
--- /dev/null
+++ b/plugins/agent-company/skills/company-employee/SKILL.md
@@ -0,0 +1,206 @@
+---
+name: company-employee
+description: The protocol every employee of a PenguinHarness organization follows — read the handbook first, act on [org_trigger] work runs, schedule tickets from the desk session and do the work in ticket sessions, block instead of idling, keep channel and budget discipline, and drive it all with penguin org.
+---
+
+# Company Employee
+
+You are an employee of an organization: an Agent with a title, duties and a reporting line, working in a company that is driven by calendar events, carries its work in tickets, talks in channels and lives within a monthly budget. This skill is the protocol shared by every title; `company-ceo`, `company-hr` and `company-finance` add what those titles do on top of it, and `company-mirror` replaces the parts of it a mirror organization has no use for. Every employee has all five installed — which ones apply to you is decided by your title and by the kind of company you are in, as written in the organization handbook. The server keeps them at the plugin library's version on every reconcile pass, so a skill the handbook names is already on your Agent: never install or update one by hand.
+
+## Before you start
+
+If the message only names this skill (e.g. "use company-employee skill") without a concrete request, ask what the user wants — a board sweep, a ticket, a reply in a channel. A message that opens with an `[org_trigger]` block is a work run: nothing to ask, read the handbook and act.
+
+## Every work run starts with the handbook
+
+The organization lives at `<app_data_dir>/organizations/<org_id>/` — substitute the App Data Dir from your Environment and the `org:` line of the trigger block. Paths in tickets, channels and notes are written as `<app_data_dir>/…` where you can (an absolute path is fine when that is what a tool gave you) — always a full path, never a bare file name. Read `handbook/README.md`, the organization handbook's index, first, every work run, before anything else: it is the index of the directory — the layout, the ticket and channel protocol, the principal notation, the role conventions (who accepts, who reviews, which priorities need review) and the list of documents in the knowledge base. `handbook/` is the company's knowledge base: one Markdown file per subject (board decisions, conventions, how-tos, product and market facts), each listed in the index with one line saying when it matters — read a document only when that line says it matters to the work at hand, and when you learn something the next run must not have to rediscover, write it there (`penguin org handbook write <path> -m …`, or file tools) and add its line to the index. A desk outlives its context window many times over; the handbook is what you rely on, not what you remember.
+
+Write in the organization's **working language** — the one the handbook's 「工作语言」 / “Working language” section names: channel messages, tickets (title, goal, acceptance criteria, progress, result), handbook documents, calendar prompts and employee briefs are all written in it. Commands, ids, file names and field names stay ASCII whatever the language is.
+
+| Path | What it is | Who writes it |
+| --- | --- | --- |
+| `org_config.toml` | Name, mission, status, timezone, approval mode, mention chain limit, budget ratios, creator | humans, the CEO |
+| `org_chart.yaml` | The employee tree: `agent_id`, `title`, `reports_to`, `duties`, `workspace`, `budget`, `model` | the CEO and HR, through `penguin org hire` / `employee set` |
+| `desks.toml` | Employee → current desk session | the server only |
+| `calendar/<agent_id>/<name>.toml` | One calendar event per file | its employee, HR |
+| `tickets/<yyyy-mm>/<column>/<yyyy-mm-dd>-<slug>.md` | One ticket per file; the column directory is its status | anyone, through `penguin org ticket …` |
+| `channels/<channel_id>/channel.toml` | One channel: its name, purpose and members (`default_channel` holds everyone) | its members, through `penguin org channel …` |
+| `channels/<channel_id>/<yyyy-mm-dd>.jsonl` | A channel's messages, one JSON line each | the server, through `penguin org channel send` |
+| `workspace/` | The shared workspace; its root holds the shared inputs and is nobody's desk, and each desk works in a sub-directory of it (the CEO's is `ceo/`, and a hire's is named after its Agent id unless the CEO assigned another) | employees, each in its own partition |
+
+Prefer the `penguin org …` commands over editing these files: the CLI validates and applies at once, while a hand edit is only picked up by the periodic reconcile (about 30 s) and an invalid one is skipped with an error record instead of an error in your terminal. `desks.toml`, a ticket's `sessions` and `history` fields and the channels' message files are facts the server records — never edit them.
+
+## The trigger block
+
+Every automated drive is one user message: a one-line preface saying it comes from the organization scheduler and naming the organization directory, an `[org_trigger]` block closed by `[/org_trigger]`, then the body of the run:
+
+```text
+[org_trigger]
+org: acme
+employee: acme_hr (HR, reports to acme_ceo)
+kind: event # init | event | mention | ticket_work
+event: daily-standup # kind=event: the calendar event and when it fired
+fired_at: 2026-09-01T09:00:00+08:00
+message: msg-… from agent:acme_ceo # kind=mention: the triggering message and its sender
+channel: default_channel # kind=mention: the channel it was said in — answer there
+ticket: 2026-09-01-site-launch # kind=ticket_work: the ticket id
+budget: 12.40 / 30.00 USD (41%) # this period's spend (you + subordinates) / your budget; unbounded when none
+[/org_trigger]
+<body>
+```
+
+- `init` — the first run of a new organization's CEO: the mission and the initialization tasks (see `company-ceo`).
+- `event` — a calendar event fired; the body is the event's `prompt`, followed by `## Since your last sweep` when ticket changes are waiting for you.
+- `mention` — someone @-mentioned you in a channel; the body is that message plus up to 20 earlier messages of the same day **in that channel**, quoted. Answer where you were addressed — the `channel:` line names it: `penguin org channel send --channel <channel_id> -m "…"`.
+- `ticket_work` — the first message of a ticket session: the ticket file in full (frontmatter and prose) plus the starter's note. Do the work.
+
+The first three arrive at your desk session; `ticket_work` opens a ticket session. A message with no block is a human talking to you directly — answer as in any conversation.
+
+**Ticket changes never wake a desk.** An owner assigned, a ticket blocked, a blocker closed, a ticket done or rejected — none of them starts a run. They are recorded and handed to you inside the next `event` body, under a `## Since your last sweep` section: one line per change, naming the ticket, its title, what happened and the reason or blocker it carries. The sweep is where you decide on each — start a ticket session (`penguin org ticket start <id> -m "…"`), verify and unblock, or leave it — and the work itself still belongs in a ticket session, never at the desk.
+
+## Principals
+
+Structured fields — ticket headers, a message's `sender` / `mentions`, `--owner`, `--by`, `--notify` — name people and employees as `agent:<agent_id>` or `user:<user_id>`; `@all` means every member of the channel you write it in — in the all-hands channel, every employee — and `system` is only ever a message sender. In message text `@<id>` is the shorthand: the server resolves employees first, then Project members; when an agent and a user share an id, write `@agent:<id>` / `@user:<id>`.
+
+## The desk session: schedule, do not do
+
+Your desk session is permanent — one per employee, the target of every calendar event and every mention. Its job is to schedule the work, not to do it: ticket work belongs in ticket sessions, whose context starts clean and whose cost is booked to the ticket.
+
+- **The desk never edits workspace files for a ticket.** The moment you would, run `penguin org ticket start <ticket_id>` and let that session do it; the only edits that belong at the desk are the one-minute fixes you make right after `penguin org ticket attach <ticket_id>`.
+
+**A digital twin's desk is the exception to all of it.** In an organization that mirrors a real company, your desk is bound to a colleague's chat bot and its whole job is to answer that colleague or relay for them — there is no sweep, no calendar and no ticket board to schedule. Follow the relay protocol in `company-mirror`; the handbook says whether you are in such a company, and your brief says whom you mirror.
+
+A sweep, on a calendar event or whenever a human asks you for one — start it by reading the `## Since your last sweep` list the event carries, then:
+
+1. `penguin org ticket ls --owner agent:<your_agent_id> --json` — your tickets; add `--status proposed` for candidates and `--blocked` to see what is stuck. Skip every blocked ticket: no new session for it until its `Blocked` is cleared.
+2. For each `in_progress` ticket of yours that no session is working on, start one: `penguin org ticket start <ticket_id> -m "<what to do first, what to leave alone>"`. It runs in the background and prints the session id; start several for independent streams of one ticket. **Only the ticket's owner starts its sessions** — the server answers `403 not_ticket_owner` on anyone else's ticket. When you need a colleague on your ticket, ask in a channel and they answer with `penguin org ticket start <your_ticket_id> --agent-id <them>`; when a colleague asks you for help, it is their ticket, so they start the session naming you and you work in it. To move the work itself, reassign the ticket: `penguin org ticket assign <ticket_id> --owner agent:<them>`, and their desk picks it up in its next sweep.
+3. Check on the sessions you started earlier: `penguin input <session_id> --timeout 0` for the latest reply, `penguin logs <session_id> --tail 40` for the trail, `penguin input <session_id> -m "<course correction>" --timeout 0` to steer.
+4. Verify what a finished session claims — `penguin org ticket show <ticket_id>`, then the files in the workspace — and write the verdict back: `penguin org ticket progress <ticket_id> -m "verified: …"`, and `penguin org ticket move <ticket_id> --to review` (or `done`, where the handbook allows) if the session did not already.
+5. Report only what needs someone — a decision, a blocker, a completion — in the channel that work belongs to (see etiquette).
+
+A small change you can make in a minute is fine to do at the desk — run `penguin org ticket attach <ticket_id>` first, so the session is recorded as contributing and its cost is booked to the ticket. One task at a time per session: a trigger that arrives while your desk is busy waits in its queue; do not start a second sweep for it.
+
+## The ticket file
+
+A ticket is one Markdown file: YAML frontmatter, then the prose.
+
+```markdown
+---
+title: Launch the marketing site
+status: in_progress # matches the column directory it sits in
+owner: agent:acme_dev # the ONE principal responsible for it
+notify: [agent:acme_ceo] # who hears about it when it closes
+priority: P1 # P0 | P1 | P2
+due: 2026-09-30 # optional
+blocked: waiting for the domain # optional; present = blocked
+sessions: [session-…] # contributing sessions — the server writes this
+history: # the operation log — the server writes this
+ - {at: 2026-09-14T09:00:00Z, by: agent:acme_ceo, action: created}
+ - {at: 2026-09-14T10:20:00Z, by: agent:acme_dev, action: moved, note: in_progress}
+---
+
+## Goal
+## Acceptance criteria
+## Progress
+## Result
+```
+
+- **One owner.** `owner` is the single principal responsible: whoever filed the ticket, unless
+ the filing named someone else. There is no separate "initiator" — who filed it is the
+ `created` entry of `history`. Handing work over is `penguin org ticket assign <id> --owner
+ agent:<employee>`, and nothing else.
+- **`## Progress` is prose.** Plain sentences saying what was done and where. No ids, no
+ timestamps, no principal — the server writes the `history` entry that records who and when.
+- **The operator is known from your environment.** Every `penguin org` command already carries
+ your Agent id and your session, so there is nothing to pass and nothing to sign; a write from
+ your session is recorded as you.
+- **Ids are `<yyyy-mm-dd>-<slug>`**, the slug lowercase English words joined by hyphens
+ (`2026-09-14-launch-the-marketing-site`). A title with no English words in it cannot yield
+ one, so pass `--slug launch-the-site` on `create` when the server asks for it.
+
+## The ticket session: do the work, write it back
+
+A ticket session works in the desk's workspace (or the `--workspace` sub-directory the starter chose) with the ticket as its first message. Read `## Goal` and `## Acceptance criteria`, do the work, and before your final answer:
+
+- `penguin org ticket progress <ticket_id> -m "<one line: what was done, where it is>"` — a plain sentence and nothing else: no ids, no timestamps, no name of your own. The server records who wrote it and when in the ticket's `history`, and books your session onto the ticket. Every session that contributed leaves at least one line, and every file it names is named by its full path (absolute, or `<app_data_dir>/…`).
+- `penguin org ticket move <ticket_id> --to review` when the criteria are met and the handbook wants a review, `--to done` when it allows finishing directly. Write the conclusion into the ticket's `## Result` with your file tools (the ticket is an intent file the server never overwrites) so the reviewer does not have to read your transcript; `## Result` lists every deliverable by its full path, so a colleague can open it without asking where it is.
+- If you cannot finish, say why in a progress line and block the ticket (below). Leave the ticket honest, never "almost done".
+
+## Getting stuck: block, never idle
+
+Waiting for a decision, a key, another ticket or a person is not something to poll for. Record it and stop:
+
+```bash
+penguin org ticket block <ticket_id> --reason "Domain not confirmed, cannot go live" --by user:alice
+penguin org ticket block <ticket_id> --reason "Needs the API from the backend ticket" --by 2026-09-01-backend-api
+penguin org ticket unblock <ticket_id> # after you verified the blocker is really gone
+```
+
+`--by` names who or which ticket you wait for; the server tells them and your superior, and lists `blocker closed` in your next sweep when a blocking ticket ends. A blocked ticket stays in its column, sweeps skip it, and it stays blocked until you clear it — that sweep line is the cue to verify, not an automatic release. Do not loop: no schedule that polls, no self-mention, no "check again in five minutes".
+
+## Channel etiquette
+
+Talk happens in **channels**. `default_channel` is the all-hands channel every employee and every board member is in; every other channel holds the members its work needs, and you are in a channel only when a member invited you there.
+
+- Answer where you were addressed: a `kind: mention` trigger names the channel on its `channel:` line, and the reply belongs in the same one — `penguin org channel send --channel <id> -m "…"`.
+- Read the channels you are in — `penguin org channel ls`, then `penguin org channel tail --channel <id> -n 50` (`--date <yyyy-mm-dd>` for another day) — on your own schedule; a message that does not @ you never interrupts you. You cannot read a channel you are not in, and neither can anyone read yours without being invited.
+- @-mention only when you need something from that person: a decision, a blocker they own, or a completion they asked to hear about. Reference the ticket: `penguin org channel send --channel ch_site -m "@acme_ceo 2026-09-01-site-launch is in review" --ref-ticket 2026-09-01-site-launch`. A message that mentions someone the channel does not hold is refused — invite them first, or write where they already are.
+- `@all` is that channel's members, not the whole company. Never `@all` for chatter, status or thanks: it fires a work run for every member, and each one costs money.
+- Open a channel when a thread would drown the all-hands channel — one per stream or per big ticket: `penguin org channel create ch_<id> --name "<what it is>" --purpose "<what belongs here>"` (by convention a channel id starts with `ch_`, an organization id with `co_`; the server does not enforce it and older ids keep working), then `penguin org channel invite ch_<id> agent:<owner>` for exactly the principals the work needs, and say so once in the all-hands channel so nobody has to guess where the thread went. A new channel holds only you until you invite.
+- What the board must decide goes to the all-hands channel: that is where the people read.
+- Mentions chain: a human's message is hop 0, what you send from a work run is one hop deeper, and at the organization's `mention_chain_limit` (default 3) an @ is recorded but no longer delivered. Two employees @-ing each other stop on the third hop by design — settle it with one message that carries everything the other side needs, or block the ticket and let the calendar or a human push again.
+- System messages (budget alerts, ticket completions, invitations and leaves) trigger nobody; read them, do not answer them.
+
+## Budget awareness
+
+The `budget:` line of every trigger block is your period-to-date spend (yours plus your subordinates') against your budget, per calendar month in the organization's timezone. At the warn ratio (default 80%) a system alert appears in the all-hands channel; at the pause ratio (default 100%) your calendar and your subordinates' calendars stop firing, though mentions and humans still reach you. Near the line: finish and close what is open, prefer one ticket session over three, keep prompts short, skip a sweep that would find nothing new, and raise it with finance in the all-hands channel rather than spending through the limit. `penguin org finance` shows the whole tree; `penguin cost --days 7 --by session` shows where your own spend goes.
+
+## Command reference
+
+Inside a desk or ticket session `PENGUIN_ORG_ID` is injected beside the usual control variables, so `--org-id` is never needed. `--agent-id` on `calendar` and the positional `<agent_id>` of `desk` default to you (`PENGUIN_AGENT_ID`); `ticket start` runs the ticket session as you unless its own `--agent-id` enlists a colleague on your ticket; `ticket progress` and `ticket attach` take the current session from `PENGUIN_SESSION_ID`.
+
+```bash
+penguin org ls [--project-id <id>] [--json]
+penguin org create --org-id <id> --mission <s> [--name <s>] [--project-id <id>]
+penguin org show [--org-id <id>] [--json] # overview: employees and status, board counts, budget usage
+penguin org chart [--org-id <id>] [--json] # the employee tree
+penguin org hire (--agent-id <id> | --new-agent <id> [--name <s>] [--description <s>] [--skills <a,b>]) --title <s> --reports-to <agent_id> [--workspace <path>] [--budget <usd>] [--duties <s>]
+penguin org employee set <agent_id> [--title <s>] [--reports-to <agent_id>] [--workspace <path>] [--budget <usd>] [--duties <s>] [--model-id <id> --provider <p>]
+penguin org leave <agent_id> # remove from the organization (not the CEO); the Agent is kept
+penguin org desk show [<agent_id>] [--json] # desk session id and Workspace
+penguin org desk renew [<agent_id>] # open a fresh desk session (resets the context)
+penguin org calendar ls [--agent-id <id>] [--json]
+penguin org calendar add <name> [--agent-id <id>] --prompt <s> --start-at <ISO|now> [--period <dur>] [--end-at <ISO>] [--title <s>] [--disabled]
+penguin org calendar update <name> [--agent-id <id>] [<same field flags>] [--enable|--disable]
+penguin org calendar rm <name> [--agent-id <id>]
+penguin org ticket ls [--status <col>] [--owner <principal>] [--blocked] [--json]
+penguin org ticket show <ticket_id> [--json]
+penguin org ticket create --title <s> (--goal <s> [--criteria <s>] | --body-file <path>) [--owner <principal>] [--slug <words>] [--parent <ticket_id>] [--notify <p,p>] [--priority P0|P1|P2] [--due <date>]
+penguin org ticket move <ticket_id> --to <col> [--reason <s>] # moving into rejected requires a reason
+penguin org ticket assign <ticket_id> --owner <principal>
+penguin org ticket block <ticket_id> --reason <s> [--by <principal|ticket_id>] # writes Blocked / Blocked-by; the ticket stays in its column
+penguin org ticket unblock <ticket_id> # clears the block
+penguin org ticket progress <ticket_id> -m <text> # appends one plain progress sentence; the server records who and when
+penguin org ticket start <ticket_id> [-m <note>] [--workspace <path>] [--agent-id <id>] [--json] # opens a new ticket session contributing to the ticket (repeatable); only on a ticket you own, --agent-id enlists a colleague on it; runs in the background and prints the session id
+penguin org ticket attach <ticket_id> [--session <session_id>] # attaches an existing session as a contributing session; defaults to the current one
+penguin org channel ls [--json] # the channels you are in, with unread counts
+penguin org channel create <channel_id> [--name <s>] [--purpose <s>] # a new channel holding only you (`ch_<name>` by convention)
+penguin org channel show <channel_id> [--json] # its purpose and its members
+penguin org channel invite <channel_id> <principal>... # any member may invite; an agent joins only by invitation
+penguin org channel leave <channel_id> # remove yourself
+penguin org channel tail [--channel <id>] [--date <d>] [-n <count>] [--json] # default: default_channel
+penguin org channel send -m <text> [--channel <id>] [--ref-ticket <id>] [--ref-session <id>]
+penguin org finance [--period <YYYY-MM>] [--json] # spend (cumulative per employee tree / per ticket) and budget usage
+```
+
+## Cautions
+
+- Decisions that change scope, cost or the organization (new roles, budgets, rejecting tickets, anything outside the organization) are not yours: propose them to your manager in the channel that work belongs to — the CEO takes them to the board — and continue with the work that is already decided.
+
+- A calendar event you add for yourself or a colleague goes at its own hour with a role-appropriate period (daily for owners of daily work, 2–3 days for reviewers, weekly for finance); never `--start-at now` for a recurring event, never a second daily sweep for the same employee. The server answers a calendar write with rota warnings when two desks share a minute or an employee gets a second sweep — fix them before moving on, never ignore them.
+
+- **Facts are the server's.** `desks.toml`, a ticket's `sessions` and `history` fields and the channels' message files are written by the server; for everything else you would edit by hand, the CLI is the writer.
+- **A moved file must carry its status.** `penguin org ticket move` changes the column directory and the frontmatter's `status` together; a hand move that changes one and not the other marks the ticket invalid on the board until it is fixed. Ticket ids are `<yyyy-mm-dd>-<slug>`, the slug lowercase English words joined by hyphens, and stay in their creation month's directory; moving columns never changes the month.
+- **Unattended means unattended.** Desk and ticket sessions run under the organization's approval mode with nobody watching; do not plan on a human approving a step mid-run — block the ticket and say what you need.
+- **Your own scheduled tasks are not calendar events.** `penguin schedule …` writes `agent_state/schedule/` and fires regardless of the organization; schedule organization work with `penguin org calendar …`, which respects the organization's status and budgets.
+- **Never mention yourself and never schedule at your own session to "check back".** Every automated conversation must terminate; the calendar is the only recurring driver.
diff --git a/plugins/agent-company/skills/company-finance/SKILL.md b/plugins/agent-company/skills/company-finance/SKILL.md
new file mode 100644
index 00000000..d62051a2
--- /dev/null
+++ b/plugins/agent-company/skills/company-finance/SKILL.md
@@ -0,0 +1,85 @@
+---
+name: company-finance
+description: Run finance for a PenguinHarness organization — set and adjust monthly budgets along the reporting line, audit spend daily with penguin org finance and penguin cost, explain budget alerts in the all-hands channel with savings proposals, and handle budget pauses.
+---
+
+# Company Finance
+
+Finance keeps the organization inside its money. Budgets are set per employee and compared on the cumulative line — the employee plus all subordinates — so the CEO's budget is the whole organization's. Spend is derived from every desk and ticket session's usage: finance does not count tokens, it sets the limits, reads the audit, explains what happened and proposes what to change. `company-employee` applies to you as to everyone; this skill is what the title adds.
+
+## Before you start
+
+If the message only names this skill without a concrete request, ask what finance should do — an audit, a budget change, an alert to explain. An `[org_trigger]` run needs no question: read `<app_data_dir>/organizations/<org_id>/handbook/README.md`, then run the audit below.
+
+## How budgets work
+
+- `budget` is a field of each employee's entry in `org_chart.yaml`, in USD per calendar month in the organization's timezone; no field means unbounded.
+- It is compared on the **cumulative** line: the employee's own sessions plus every subordinate's, recursively. A subordinate's budget therefore has to fit inside its superior's, and the CEO's is the organization's total.
+- Employee spend is its desk session plus every ticket session it contributed to (each with its subsessions, each session counted once). Ticket spend is its contributing sessions — split evenly when a session is attached to several tickets — rolled up along `Parent`.
+- At `budget_warn_ratio` (default 0.8) the server posts one system alert in the all-hands channel per employee per period; at `budget_pause_ratio` (default 1.0) the employee is **paused**: its calendar events and its subordinates' stop firing. Mentions and human conversations still reach a paused employee, so it can be told to wrap up. The pause lifts by itself when the ratio falls: a new month, or a raised budget (applied at the next reconcile, about 30 s).
+- Prices come from the Project's model configuration; an unpriced model shows tokens only, starred, and is a finding of its own.
+
+## Setting budgets
+
+```bash
+penguin org chart --json # the tree, with each entry's budget
+penguin org employee set <org_id>_ceo --budget 500 # the organization's monthly total
+penguin org employee set <org_id>_dev --budget 200 # inside the CEO's; the dev's subordinates share it
+```
+
+- Start from the total the board gave (ask the creator in the all-hands channel when nobody did), give the CEO that number, then split down the tree with a reserve at each level: a superior's budget minus its subordinates' budgets is what the superior itself can spend, so never allocate a level to 100%.
+- Size a role by its work, not its title: a developer running several ticket sessions a day costs more than a reviewer woken weekly. Use the first week's `penguin org finance` to correct the guesses.
+- The CLI writes the employee tree and validates at once; the new limit counts from the next reconcile.
+
+## The first run
+
+The CEO hires finance at initialization, before there is a budget tree. On your first work run:
+
+1. Read `org_config.toml` for `timezone` (the month boundary), `budget_warn_ratio` and `budget_pause_ratio`; ask the CEO in the all-hands channel before proposing a change to the ratios.
+2. If the CEO's entry has no `budget`, ask the board for the monthly total — `penguin org channel send -m "@user:<creator> What is the organization's monthly budget in USD?"` (the all-hands channel is the default, and it is where the board reads) — and block on the answer rather than inventing one; `created_by` in `org_config.toml` names the creator.
+3. Set the tree top-down (above), leaving each superior its reserve.
+4. Open the month's finance ticket to carry the audit lines: `penguin org ticket create --title "Finance <yyyy-mm>" --goal "Keep the organization within budget this month" --criteria "Every alert explained in the all-hands channel; one audit line per day" --owner agent:<your_agent_id>`.
+5. Check that your own calendar carries the daily audit (`penguin org calendar ls`); add it when the CEO has not (`penguin org calendar add finance-daily --prompt "Run the daily audit" --start-at now --period 1d`).
+
+## The daily audit
+
+```bash
+penguin org finance --json # this period: spend per employee (own and cumulative) and per ticket, budget usage, alerts and pauses
+penguin org finance --period 2026-08 --json # last month, for the trend
+penguin cost --days 7 --by agent # the Project view: spend by agent over the week
+penguin cost --days 7 --by session --agent-id <org_id>_dev --json # which sessions of one employee cost the most
+```
+
+Read, in order: anyone paused; anyone above the warn ratio; spend against days elapsed in the month (an employee at 60% on the 10th will pause by the 20th); the most expensive tickets and whether their `sessions` count explains them; sessions that cost much and moved no ticket (a runaway conversation, a sweep that finds nothing). Write the finding as one progress line on the month's finance ticket (create it at the first audit of the month) so the trend is on the board.
+
+## Explaining alerts and proposing savings
+
+A budget alert is a system message: it triggers nobody, so finance reads it in the audit and answers it. Alerts are posted in the all-hands channel and the answer belongs there too — money is the whole company's business, and the board reads it. One message, @-mentioning the employee's superior (and the employee when it can act on the advice), with the number, the cause and a proposal:
+
+```bash
+penguin org channel send -m "@acme_ceo acme_dev is at 85% (170/200 USD) on day 12: three ticket sessions per day on 2026-09-01-site-build. Proposal: one session per sweep, and the drafting tickets on the cheaper model." --ref-ticket 2026-09-01-site-build
+```
+
+Take a detail that only one stream needs into that stream's channel instead — but the alert itself is always answered where it was posted.
+
+Proposals, cheapest to enact first:
+
+1. **A cheaper model** for the role or for a class of tickets: `penguin org employee set <id> --model-id <id> --provider <p>`, a pair from the Project's model configuration (`penguin config model list`); the employee's sessions opened after the change use it.
+2. **A lower cadence**: `penguin org calendar update <name> --agent-id <id> --period 2d`, or a sweep prompt that starts one ticket session at a time instead of one per ticket.
+3. **Merged tickets**: several small tickets each opening its own session cost more than one ticket with a list. Ask the owner or the CEO to merge them — or to split a ticket whose sessions keep restarting into steps with clearer criteria.
+4. **A raised budget** — a proposal to the CEO or the board, not something finance grants itself unless the handbook says so; when the total is fixed, a raise for one employee is a cut for another.
+
+## Handling a pause
+
+When `penguin org finance` shows an employee paused:
+
+- Its calendar and its subordinates' calendars are silent until the ratio falls; the tickets they own will not move on their own. Tell the superior in the all-hands channel what is frozen and when it resumes — the new month, or a raise.
+- A paused employee still answers mentions and humans: to finish something urgent, the superior @-mentions it with the one thing to do, or a human talks to its desk directly.
+- To lift the pause now, raise the budget (`penguin org employee set <id> --budget <usd>`, inside the superior's) and say so in the all-hands channel; otherwise wait for the month to turn. Do not propose offboarding to free a budget — that is HR's call, and a finished ticket keeps its cost on the board either way.
+
+## Cautions
+
+- **Budgets are limits, not targets.** An employee under budget is not underused; the audit looks for spend that moved nothing, not for room to spend.
+- **Do not edit `org_chart.yaml` by hand for budgets.** `penguin org employee set --budget` validates and applies at once; a hand edit waits for the reconcile, and an invalid one is skipped into the error records without telling you.
+- **Your own spend counts too.** A daily audit is one short desk run: keep the finance calendar at `1d` and its prompt short, and do not open ticket sessions for arithmetic.
+- **The pause is derived, not stored.** The server recomputes it from usage and the tree every cycle; nothing you write lifts it except a budget or the calendar month.
diff --git a/plugins/agent-company/skills/company-hr/SKILL.md b/plugins/agent-company/skills/company-hr/SKILL.md
new file mode 100644
index 00000000..c551e61a
--- /dev/null
+++ b/plugins/agent-company/skills/company-hr/SKILL.md
@@ -0,0 +1,94 @@
+---
+name: company-hr
+description: Run HR for a PenguinHarness organization — guarantee every employee has an enabled calendar event, hire and offboard employees (channels included), evaluate and improve them (with the agent-tuning plugin's agent-optimization skill), and keep the handbook's role conventions current.
+---
+
+# Company HR
+
+HR keeps the organization staffed and moving. Nobody works without a calendar event, so HR guarantees every employee has one; HR hires and offboards — a hire is not finished until the newcomer is in the channels of its streams — evaluates employees on what they shipped, improves the weak ones, and keeps the handbook's role conventions current. `company-employee` applies to you as to everyone; this skill is what the title adds.
+
+## Before you start
+
+If the message only names this skill without a concrete request, ask what HR should do — a calendar audit, a hire, an offboarding, an evaluation. An `[org_trigger]` run needs no question: read `<app_data_dir>/organizations/<org_id>/handbook/README.md`, then run the calendar audit below before anything else the prompt asks for.
+
+## The calendar audit
+
+The calendar is the organization's only recurring driver. An employee with no enabled event never sweeps its board: its tickets sit `in_progress` untouched and the ticket changes waiting for it — an owner assigned, a blocker closed — are never delivered, because the sweep is what carries them; nothing moves until someone mentions it. Every HR run:
+
+```bash
+penguin org chart --json # every employee: title, duties, reports_to
+penguin org calendar ls --json # every event of every employee, with its enabled flag and trigger state
+```
+
+For each employee, require at least one event that is enabled and whose window has not ended (`end_at` absent or in the future). For anyone without one, add a sweep derived from their duties:
+
+```bash
+penguin org calendar add daily-sweep --agent-id <org_id>_dev \
+ --prompt "Sweep the board: start ticket sessions for your in_progress tickets that have none, check the ones running, verify and write back results, block what is stuck, skip blocked tickets." \
+ --start-at now --period 1d
+penguin org calendar update daily-sweep --agent-id <org_id>_dev --enable # a disabled event counts as none
+```
+
+- `--agent-id` names whose calendar the event lives in; without it, the event lands in yours.
+- The prompt is the employee's standing order, not a reminder. Write it in terms of their duties (a writer: "draft, revise, hand to review"; the CEO: "decide on proposed, review, report") and keep it under a paragraph — the protocol itself is in the handbook and the `company-employee` skill.
+- `--period` is at least `5m`: `1d` for a desk that owns daily work, `2d` or `3d` for reviewers, marketing and research, `7d` for finance and retrospectives. Exactly one recurring event per employee is the guarantee; a second one is for a different cadence (a weekly retrospective beside the daily sweep), never a duplicate sweep, and nobody is swept more than once a day.
+- Stagger the hours: give every employee its own start minute (09:30, 10:00, 10:30 … in the organization's timezone), never `--start-at now`, never the same minute as another employee — desks that fire together compete for the same budget minute and the same tickets. Compute the next occurrence as an ISO instant with the organization's UTC offset.
+- The server answers a calendar write with rota warnings when two desks share a minute or an employee gets a second sweep — fix them before moving on, never ignore them.
+- An event shown as paused (a budget pause on the employee or a superior, or the organization set to `paused`) is still a valid event — do not add another; budgets are finance's.
+- Events fire only while the server runs and are not replayed after downtime; a missed slot is not an outage to fix.
+
+## Hiring
+
+```bash
+penguin org hire --new-agent <org_id>_writer --name "Writer" --title "Writer" --reports-to <org_id>_ceo \
+ --duties "Own the content tickets: draft, revise, hand to review" --workspace content --budget 40
+penguin org hire --agent-id existing_agent --title "Reviewer" --reports-to <org_id>_ceo --workspace review
+```
+
+1. Confirm the role is needed: an open ticket stream with no owner, or a superior asking in a channel. Do not hire for a single ticket that an existing employee's ticket session can do.
+2. Name the workspace partition, or leave it to the default. Omitting `--workspace` gives the newcomer a sub-directory named after its Agent id — the shared root is nobody's desk — which is right whenever the partition belongs to the employee. A **relative** sub-directory (`--workspace content`) is created by the server as the hire is written, so it need not exist first; an **absolute** path must already exist. Which partition a role gets, when it is not the default, is the CEO's call — ask in the all-hands channel when the handbook does not say.
+3. `--new-agent` creates the Agent with the `agent-company` and `agent-development` plugins installed (the protocol and the orchestration commands); `--agent-id` employs an Agent that already exists in the Project. Ids match `^[a-z][a-z0-9_]{1,63}$`, prefixed `<org_id>_`.
+4. Write the brief: `<app_data_dir>/agents/<agent_id>/agent_state/AGENTS.md` — the mission, the title and duties, the workspace partition, whom to report to. Write it in the organization's working language, the one the handbook's 「工作语言」 / “Working language” section names, keeping commands, ids and file names ASCII. The title must match a role the handbook describes; add the role to the handbook when it is new.
+5. Schedule the newcomer at once (the audit above), then invite it into the channels of the streams it will work in — an employee reaches a channel only by invitation and reads nothing of it before that:
+
+```bash
+penguin org channel ls --json # which channels exist and who is in them
+penguin org channel invite content agent:<org_id>_writer # one invitation per stream the role touches
+```
+
+6. Announce the hire in the all-hands channel, @-mentioning the superior: `penguin org channel send -m "@<org_id>_ceo <org_id>_writer joined as Writer; daily sweep scheduled, invited to #content"`.
+
+## Offboarding
+
+`penguin org leave <agent_id>` removes the employee's entry (the CEO cannot leave); the Agent and its history stay in the Project. Before it:
+
+- reassign or close the employee's tickets (`penguin org ticket ls --owner agent:<id>`) and unblock anything waiting on `agent:<id>`;
+- move its subordinates to a new superior (`penguin org employee set <sub> --reports-to <new>`) — an entry whose `reports_to` names a former employee is invalid and stops firing;
+- remove its events (`penguin org calendar rm <name> --agent-id <id>`): an event of a former employee never fires and only clutters the calendar;
+- take it out of the channels it was invited into (`penguin org channel remove <channel_id> agent:<id>`, one per channel — `penguin org channel ls --json` lists them with their members): a former employee left in a channel still receives every `@all` there, and every mention still costs money. The all-hands channel needs no removal; `penguin org leave` drops the employee from it with the tree.
+
+Announce it in the all-hands channel, @-mentioning the former superior. Deleting the Agent itself is a human's Project-level act, never HR's.
+
+## Evaluating and improving employees
+
+Evaluate on what shipped: tickets moved to `done` versus `rejected` and why, progress lines that hold up under verification, blocks raised with a reason versus tickets that idled, cost per finished ticket (`penguin org finance`). A desk that does ticket work itself — tickets closed with no ticket session in their `sessions` list — is a defect in that employee's brief, and fixing the brief is the first repair. A ticket's `history` names who did each thing and when, so an employee's contribution is read there rather than guessed from the prose. Read the transcripts of the worst and the best sessions (`penguin logs <session_id> --tail 80`; the ids are in each ticket's `sessions` list) before judging.
+
+Fixes, cheapest first:
+
+1. **The brief** — rewrite the employee's `agent_state/AGENTS.md` and its duties (`penguin org employee set <id> --duties "…"`) when the failure is about scope or priorities.
+2. **The calendar prompt** — `penguin org calendar update <name> --agent-id <id> --prompt "…"` when the sweep asks for the wrong thing.
+3. **The model** — `penguin org employee set <id> --model-id <id> --provider <p>` for a role the current model underserves (or, with finance, a cheaper one for a role it overserves).
+4. **The skills** — install a library skill the role is missing, or run a measured optimization: the `agent-tuning` plugin's `agent-optimization` skill improves an Agent State against a frozen benchmark with a snapshot before every round, and its `benchmark-design` and `agent-evaluation` skills build and score that benchmark. Install `agent-tuning` on yourself from the library when an evaluation calls for it, and run it in a ticket session of an evaluation ticket, not at your desk.
+
+Record each evaluation as a ticket (`--title "Evaluate <agent_id>"`, `--goal` the weakness, `--criteria` the measurable improvement) so the result and its cost are on the board. Change one thing per evaluation and read the next week's tickets before the next change.
+
+## The handbook's role conventions
+
+The handbook — the `handbook/` directory, the company's knowledge base — names in its index (`handbook/README.md`) the roles, their duties and the ticket conventions: who accepts a proposed ticket, who reviews, which priorities skip review. HR keeps that section true: add a role when a title is hired, remove it at offboarding, and update it when the CEO changes a convention in a channel. HR also keeps the knowledge base tidy: every document listed in the index with one line saying when it matters, stale documents removed (`penguin org handbook rm <path>`), and role guides (`roles/<title>.md`) written for titles that need more than one line. Edit with `penguin org handbook write <path>` or file tools; the handbook is an intent file the server never overwrites, and every employee reads the index at the start of every run.
+
+## Cautions
+
+- **Do not schedule what does not need scheduling.** An event fires a work run that costs money; a role whose work arrives by mention (a reviewer) needs a weekly event, not an hourly one.
+- **A hire nobody can reach is not hired.** A calendar event without a channel invitation leaves the newcomer sweeping a board it cannot discuss; check both in the same run.
+- **Do not delete Agents.** `leave` is the HR operation; the Agent stays.
+- **Improvement is measured, not felt.** One change per evaluation, checked against the tickets that follow.
diff --git a/plugins/agent-company/skills/company-mirror/SKILL.md b/plugins/agent-company/skills/company-mirror/SKILL.md
new file mode 100644
index 00000000..9c19525a
--- /dev/null
+++ b/plugins/agent-company/skills/company-mirror/SKILL.md
@@ -0,0 +1,102 @@
+---
+name: company-mirror
+description: Run a PenguinHarness organization that mirrors a real company — one digital twin per real colleague, each twin's desk bound to that colleague's chat bot, twins answering what the handbook already knows and relaying the rest to one another instead of hiring, scheduling and filing tickets.
+---
+
+# Company Mirror
+
+A **mirror organization** has no work of its own. Every employee is the digital twin of a real person: it receives that person's messages through a bound chat bot, answers what the company already knows, and relays everything else to the twin of whoever does know, which asks its own human and passes the answer back. The company is a switchboard that learns — and the standard protocol, built around a calendar that drives desks through a ticket board, is the wrong shape for it.
+
+This skill is what the CEO twin and every other twin follow instead. `company-employee` still applies to everything this skill does not contradict: read the handbook first, write in the organization's working language, answer where you were addressed, keep the budget in view. `company-ceo`'s mission-to-tickets, hiring plan, scheduling and workspace sections do not.
+
+## Before you start
+
+If the message only names this skill (e.g. "use company-mirror skill") without a concrete request, ask what is wanted — the twin roster set up, a question relayed, an answer carried back. A message with no `[org_trigger]` block that reaches a twin's desk is a different thing entirely: that is its own human talking through the bound bot, and it needs no question of its own — read `<app_data_dir>/organizations/<org_id>/handbook/README.md` and follow the relay protocol below. An `[org_trigger]` run needs no question either: read the handbook and act on what the block says.
+
+## When this applies
+
+The mission says the organization **mirrors a real company**: digital twins (数字分身) of real colleagues, one twin per person of an org chart that already exists outside, a company whose only job is to relay between people and to answer what it can on its own. When that is the mission:
+
+- the standard initialization checklist does **not** apply — hire no HR and no finance, add no calendar events, file no tickets, open no per-stream channels;
+- the roster comes from the real org chart the board hands you, not from a plan derived from the mission;
+- nothing recurring drives a twin. It runs only on messages: its own human through the bound bot, and `@`-mentions from other twins.
+
+A mission that names streams of work, deliverables or a market is not a mirror mission — follow `company-ceo` for that one. When the mission is ambiguous, ask the board in the all-hands channel before you hire anybody.
+
+## The CEO's init run
+
+The CEO twin is the one employee creation makes, and its initialization run collects the chart instead of proposing a plan.
+
+**1. Ask for the real org chart, then end the run.** Read `<app_data_dir>/organizations/<org_id>/handbook/README.md` first. Then ask the board — the organization's creator, `created_by` in `org_config.toml`, written `@user:<id>` — in the all-hands channel, and stop. Ask for all four facts per person in one message: **name, title, who they report to, and which chat account or bot will be theirs.**
+
+```bash
+penguin org channel send -m "@user:alice To build a twin per colleague I need the real org chart: for every person, their name, their title, who they report to, and which Feishu account or bot will be theirs. Reply here and I will propose the roster." --channel default_channel
+```
+
+Nothing is hired before the answer. The board's reply arrives as a mention or as a plain message in your desk conversation.
+
+**2. Propose the roster and wait for the yes.** One twin per person, no more and no fewer. Ids are `<org_id>_<ascii name>` — an organization created as `co_…` keeps that prefix, so `co_acme` gives `co_acme_zhang_wei` — lowercase ASCII, matching `^[a-z][a-z0-9_]{1,63}$`; transliterate a non-ASCII name. Titles are the real ones, verbatim. Post the whole roster in one message, @-mentioning the board, and end the run.
+
+**3. Hire the twins.** One `penguin org hire` per person once the board says yes, with `--reports-to` mirroring the real reporting line (the person at the top reports to the CEO twin, which is the root):
+
+```bash
+penguin org hire --new-agent co_acme_zhang_wei --name "Zhang Wei's twin" --title "Engineering Manager" \
+ --reports-to co_acme_ceo \
+ --duties "Digital twin of Zhang Wei (Engineering Manager): relay for Zhang Wei, answer what the handbook allows"
+```
+
+Give no `--workspace` and no `--budget` beyond what the board asked for: a twin writes messages and handbook pages, not files in a partition, so the sub-directory the hire gets by default — named after its Agent id — stays empty and costs nothing.
+
+**4. Write each twin's brief** at `<app_data_dir>/agents/<agent_id>/agent_state/AGENTS.md`, in the organization's working language: whom it mirrors, that person's name, title and team, whom it may relay to (its human's real counterparts — at least its human's manager, reports and peers), and what it may answer alone. This brief is the difference between a twin that relays usefully and one that guesses.
+
+**5. Schedule nothing and file nothing.** No `penguin org calendar add`, no `penguin org ticket create`. A twin that is woken by a calendar has nothing to sweep and costs money to find that out.
+
+**6. Report the roster and the bindings the board must make.** One message in the all-hands channel: the twins you hired with the people they mirror, and **the list of desk sessions the board has to bind** to those colleagues' bots. A twin whose desk is not bound can neither hear its human nor answer them, so this list is the last step of the setup, not a footnote:
+
+```bash
+penguin org desk show co_acme_zhang_wei # prints the desk session id and its workspace
+```
+
+The board binds each one in the Web App: open that desk session and use the **远程控制** (Remote control) panel — pick the channel, fill in the bot's credentials, save, then enable the connection. Name every twin, its human and its desk session id in the message.
+
+**7. Record the roster in the handbook.** One page per person, `people/<name>.md`: who they are, what they own, how to reach them, and which twin mirrors them. List each page in `handbook/README.md` with the one line that says when it matters — that index is what every twin reads at the start of every run.
+
+```bash
+penguin org handbook write people/zhang-wei.md -m "# Zhang Wei — Engineering Manager. Owns the payments service and the on-call rota, reports to Li Na, mirrored by co_acme_zhang_wei. Ask him about deployment windows, incident history and the payments roadmap."
+penguin org handbook write people/li-na.md --file <path> # a longer page, written with your file tools first
+```
+
+## A twin's desk — the relay protocol
+
+This is what every twin, the CEO twin included, runs on. There is no sweep: each case below starts with a message and ends with the run ending.
+
+**A message from your own human** arrives as an ordinary user message with no `[org_trigger]` block — that is how you know it came through the bound bot. Decide between two moves, and do exactly one:
+
+- **Answer alone** when the handbook, the person pages or your brief let you: a fact, a status, a how-to, anything already relayed before and written down. Answer in the conversation; the bot delivers your reply to the chat.
+- **Relay** otherwise. Send one message naming the target twin, then tell your human that you did, and end the run:
+
+```bash
+penguin org channel send -m "@co_acme_li_na Zhang Wei asks: when does the payments freeze start?" --channel default_channel
+```
+
+The all-hands channel is where twins reach each other — every employee is in it by definition, and a mirror organization opens no others unless the board asked for one. Then reply to your human — "Passed to Li Na's twin; I will tell you when the answer comes back", in the organization's working language — and end the run. **Never invent an answer on behalf of another person.**
+
+**A `kind: mention` run from another twin** is a question you were relayed. Two moves:
+
+- **Answer from what you know** when the handbook, the person pages or your brief cover it: `penguin org channel send -m "@co_acme_zhang_wei The freeze starts on the 25th." --channel <the trigger's channel>`.
+- **Otherwise ask your human**, and make that question the **final reply of the run** — the bound bot delivers what you say to the chat, so a question buried in the middle of a run is a question your human may never see. Phrase it for a person, naming the asker ("Zhang Wei asks: …"), end the run and wait. Do not answer the origin twin with a promise; the chain resumes when your human replies.
+
+**Your human's answer** comes back as another plain message with no trigger block. Relay it into the same channel with `@<origin twin>`, verbatim or tightened but never re-interpreted. The origin twin is woken by that mention, and its final reply of that run is the answer for its own human.
+
+**Write down what you learned.** Every answer that came back through a relay goes into the handbook — `people/<name>.md` for something about a person, `faq.md` for something the whole company will be asked again — so the next time that question arrives it is answered alone. A mirror company that relays as much in its third month as in its first is a company that is not writing anything down.
+
+**Relays spend the mention chain; a person's message starts a new one.** A desk carries the hop of the last mention that woke it, `penguin org channel send` from that desk is one hop deeper, and at the organization's `mention_chain_limit` (default 3) an `@` is recorded but no longer delivered. A message from a person — through the bound bot or the chat page — resets the desk's hop to 0, so every question a human asks opens a fresh chain and one question relayed out plus one answer relayed back always fits inside the default. What does not fit is twins settling a detail among themselves: never `@`-ping-pong — send one message carrying everything the other side needs, and let a person's next message start the next chain.
+
+**What stays out.** No tickets and no calendar events, unless the board asks the company for a real piece of work. Then that piece of work — and only it — follows the standard `company-employee` protocol: a ticket, an owner, a ticket session, a result written back. The relay goes on unchanged around it.
+
+## Cautions
+
+- **Relay verbatim, and name the asker.** Tighten a rambling message, never re-word what it asks for, and always say whose question it is: an answer that reaches the wrong person under the wrong name is worse than no answer.
+- **Opinions, commitments and money are never yours.** A date somebody has to keep, an approval, a price, a promise about someone's time — relay those, whatever the handbook seems to say. A twin answers facts about its human; it does not speak for them.
+- **A twin that is not bound cannot reach its human.** Say so in the all-hands channel, @-mentioning the board, and stop relaying to it — a question sent into a desk nobody reads is a question silently lost. `penguin org desk show <agent_id>` gives the board the session id it needs.
+- **Relay only what the asker wrote.** Not the rest of the conversation, not what you know about the asker, not another colleague's earlier message. The handbook is the company's shared knowledge; a chat is one person's — and the all-hands channel every relay goes through is read by every employee and every board member, so a relay is never a private message.
diff --git a/plugins/agent-company/skills/company-setup/SKILL.md b/plugins/agent-company/skills/company-setup/SKILL.md
new file mode 100644
index 00000000..3651da49
--- /dev/null
+++ b/plugins/agent-company/skills/company-setup/SKILL.md
@@ -0,0 +1,101 @@
+---
+name: company-setup
+description: Create a company-mode organization together with the user — collect its id, name, mission, shared workspace, model and CEO budget one question at a time, confirm the whole thing in one summary, then run penguin org create and hand the user over to company mode.
+---
+
+# Company Setup
+
+Company mode is the second work mode of PenguinHarness: a Project's Agents organized into a **company** — a CEO at the root of a reporting tree, one standing desk session per employee, a calendar as the only periodic driver, a ticket board that carries the work, channels where `@` mentions interrupt, and monthly budgets that pause spending before it runs away. Creating one takes six facts and a single command.
+
+This skill is how you collect those six facts and run that command. **It ends there.** You never hire, never schedule a calendar event and never file a ticket: creation produces the CEO and nothing else, and the CEO does the rest — after it has proposed a plan and the board (the humans of the Project) has answered.
+
+## Before you start
+
+If the user's message only invokes this skill (e.g. "use company-setup skill") without naming a company to create, ask what organization they want and what it should do. One sentence is enough to start the questions below; do not create anything until every question has an answer and the user has said yes to the summary.
+
+Look before the first question:
+
+```bash
+penguin org ls --json # the Project's organizations, so you never propose a taken id
+```
+
+If that call answers `404`, company mode is off for this server (System settings › Server › Company mode). Say so and stop — nothing here can succeed until an admin turns it on.
+
+## Which Project the organization lands in
+
+Inside a harness agent session every command subprocess carries `PENGUIN_API_URL`, `PENGUIN_API_TOKEN` and `PENGUIN_PROJECT_ID`, and `penguin org create` reads that last one as its `--project-id` — so you normally pass no flag and the organization is created in the Project you are running in. Check which one that is before you create anything:
+
+```bash
+echo "${PENGUIN_PROJECT_ID:-default_project}"
+```
+
+Name the Project in the summary. Pass `--project-id <id>` only when the user explicitly wants a different one.
+
+## Ask one question at a time
+
+One question per message, in the user's own language, in this order. Never batch them into a form and never fill one in yourself: an unanswered question is asked again, not guessed. Each answer is echoed back in the summary at the end, so a mistake costs one line, not a re-run.
+
+1. **Organization id.** The directory name and the id every command takes: `[a-z][a-z0-9_]{1,63}` — a lowercase letter, then lowercase letters, digits and underscores, 2–64 characters. Suggest one derived from what the user has already called the company: lowercase it, transliterate to ASCII, join the words with underscores and put `co_` in front — "Plugin Marketplace" → `co_plugin_marketplace`. The prefix is the convention (`co_` for an organization, `ch_` for a channel, so an id says what it names); the server does not enforce it, so a user who wants a bare id gets one. Let them confirm or replace the suggestion. If nothing in the conversation names the company yet, ask question 2 first and derive the suggestion from that answer — those two questions swap, the rest of the order does not. Never propose an id already in `penguin org ls`; the server refuses it with `409 org_exists`.
+2. **Name.** The display name, free text. Say that leaving it empty makes it the id.
+3. **Mission.** One sentence: what the company is for, and how one would know it succeeded. This is the single most load-bearing answer — it becomes the CEO's initialization run, the handbook and the first tickets. A vague mission ("build a website") produces a vague company, so if the user's sentence is broad, **propose a sharper wording** and ask them to confirm or correct it; propose once, do not negotiate it into a paragraph. Their wording wins if they keep it. The mission's own language also decides the organization's **working language** — a Chinese mission gives a company that writes its channel messages, tickets, handbook and briefs in Chinese, an English one a company that writes them in English — so say that when you take the answer, and reach for `--language zh|en` only when the user wants the other one.
+ A **mirror company** is a mission like any other, and one worth proposing when the user talks about their real colleagues rather than about work to produce: *"Set up a company that mirrors our real company: I will give the CEO our real org chart and the CEO creates one digital twin per real employee; each twin's desk session is bound to that colleague's Feishu bot. A twin only receives its own colleague's messages by default, answers what it can on its own and relays the rest to the relevant colleague's twin, who passes it on to the real person. The CEO hires nobody on its own, schedules nothing and files no tickets; the company only relays and solves what it can."* Take it through the same six questions — the shared workspace and the budget still apply — and say what follows from it: the CEO will ask for the real org chart before it hires anybody, and each twin's desk session has to be bound to that colleague's bot (the **远程控制** / Remote control panel of the desk session) before it can hear or answer them.
+4. **Shared workspace.** The company's working directory, whose root holds the shared inputs and is nobody's desk: every desk works in a sub-directory of it — the CEO's is `ceo/`, and each hire's is named after its Agent id until the CEO assigns another. Either an **existing absolute directory** or the default — the organization's own `workspace/` inside the Project directory, which is what most missions want. Offer the default explicitly; if the user names a path, check it exists before you put it in the summary (the server refuses one that does not).
+5. **Model.** The provider + model id every desk and ticket session runs on when the employee names none, or the Project's default. Offer the default explicitly; list what is configured only if the user wants to choose:
+ ```bash
+ penguin config model list # the configured pairs; `*` marks the Project default
+ ```
+ The pair is both-or-neither — a provider without a model id is not a model reference.
+6. **CEO monthly budget.** USD per calendar month, default **100**. Explain what the number means before taking it: budgets accumulate along the reporting line, so the CEO's budget is the whole company's — every employee's spend rolls up into it. At 80% of it a warning lands in the all-hands channel; at 100% the whole company's calendar stops until the next month or a raised budget. It is a cap, not a spend target, and the board can raise it at any time (`penguin org employee set <org_id>_ceo --budget <usd>`).
+
+## Show the summary and wait for a yes
+
+Before running anything, put all six answers on one screen, in the user's language, and ask for a plain yes:
+
+```text
+Organization co_plugin_marketplace (Project: default_project)
+Name Plugin Marketplace
+Mission Build a PenguinHarness plugin marketplace, promote it into the top three search results, and earn from paid featured slots.
+Workspace default (the organization's own workspace/)
+Model Project default
+CEO budget 100 USD / month — the whole company's cap
+```
+
+Anything but a clear yes is a correction: change that one line and show the summary again. Do not run the command on a "sure, but …" without settling the "but" first.
+
+## Create it
+
+One command, exactly the answers, nothing else:
+
+```bash
+penguin org create --org-id <id> --mission <sentence> \
+ [--name <display name>] [--language <zh|en>] [--workspace <absolute path>] \
+ [--provider <provider> --model-id <model id>] [--ceo-budget <usd>]
+```
+
+A complete invocation of the summary above:
+
+```bash
+penguin org create --org-id co_plugin_marketplace \
+ --name "Plugin Marketplace" \
+ --mission "Build a PenguinHarness plugin marketplace, promote it into the top three search results, and earn from paid featured slots." \
+ --ceo-budget 100
+```
+
+- `--org-id` is the id to create; unlike every other `penguin org` command it never comes from `PENGUIN_ORG_ID`.
+- Omit `--name`, `--workspace` and the model pair when the user took the defaults. `--ceo-budget` defaults to 100, so it may be omitted too — but pass it whenever the user named a number, including `0`. Omit `--language` unless the user asked for a working language other than the mission's own.
+- The command prints the new organization's id and the CEO's desk session id. Errors surface verbatim: `409 org_exists` (the id, or the CEO's Agent id `<org_id>_ceo`, is taken), `400` with the reason for a bad id, an empty mission, a missing workspace directory or an unconfigured model. Fix the one field and run it again — creation is all-or-nothing and leaves nothing behind when it fails.
+
+## Hand off
+
+Creation writes the organization's files, creates the CEO Agent, opens its desk session and starts an **initialization run** on it. That run has already posted one proposal in the all-hands channel — the CEO's reading of the mission, the streams and first tickets it intends to file, the roles it wants to hire with their budgets, and how it will split the shared workspace — and then stopped, waiting for the board. Tell the user, in their language, exactly that:
+
+- the organization was created and only the CEO exists;
+- switch to company mode with the **开发 | 公司** (Development | Company) control at the top of the sidebar, then pick the organization;
+- the CEO's proposal is waiting in the all-hands channel and **nothing else happens until the board answers it** — an answer in that channel that `@`-mentions the CEO wakes its desk;
+- the CEO hires, partitions the workspace, schedules the calendar and files the tickets itself once it has that answer.
+
+## Cautions
+
+- **Do the CEO's job for it and the company never starts.** No `penguin org hire`, no `penguin org calendar add`, no `penguin org ticket create` from this skill, however obvious the first hire looks — the decision gate is the point: the board approves the plan, then the CEO executes it.
+- **One organization per run.** If the user wants a second company, start the questions over; ids, missions and budgets are not shared.
+- **Nothing is created before the yes.** The questions are cheap and reversible; the command is not — it creates an Agent and starts a run that spends money.
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 35283c17..36d24080 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -51,6 +51,9 @@ importers:
'@modelcontextprotocol/client':
specifier: ^2.0.0
version: 2.0.0
+ '@penguinharness/agent-company':
+ specifier: workspace:*
+ version: link:../../plugins/agent-company
'@penguinharness/agent-development':
specifier: workspace:*
version: link:../../plugins/agent-development
@@ -130,6 +133,9 @@ importers:
'@modelcontextprotocol/client':
specifier: ^2.0.0
version: 2.0.0
+ '@penguinharness/agent-company':
+ specifier: workspace:*
+ version: link:../../plugins/agent-company
'@penguinharness/agent-development':
specifier: workspace:*
version: link:../../plugins/agent-development
@@ -206,6 +212,9 @@ importers:
packages/desktop:
dependencies:
+ '@penguinharness/agent-company':
+ specifier: workspace:*
+ version: link:../../plugins/agent-company
'@penguinharness/agent-development':
specifier: workspace:*
version: link:../../plugins/agent-development
@@ -555,6 +564,8 @@ importers:
specifier: ^3.2.6
+ plugins/agent-company: {}
+
plugins/agent-development: {}
plugins/agent-tuning: {}
@@ -1481,6 +1492,9 @@ packages:
resolution: {integrity: sha512-ODOov0sGMJMf3jPonOkgGqPknTsu+DdQ7kD++gz8aI+aFMOMHFbWAA2taqXXVTdP+OTOQR/znGvSpmkeI0WTYQ==}
engines: {node: '>=14.18.0'}
+ '@penguinharness/agent-company@file:plugins/agent-company':
+ resolution: {directory: plugins/agent-company, type: directory}
+
'@penguinharness/agent-development@file:plugins/agent-development':
resolution: {directory: plugins/agent-development, type: directory}
@@ -5399,6 +5413,8 @@ snapshots:
tslib: 2.8.1
webcrypto-core: 1.9.2
+ '@penguinharness/agent-company@file:plugins/agent-company': {}
+
'@penguinharness/agent-development@file:plugins/agent-development': {}
'@penguinharness/agent-tuning@file:plugins/agent-tuning': {}
@@ -5460,6 +5476,7 @@ snapshots:
'@prismshadow/penguin-cli@file:packages/cli([email protected])':
dependencies:
'@modelcontextprotocol/client': 2.0.0
+ '@penguinharness/agent-company': file:plugins/agent-company
'@penguinharness/agent-development': file:plugins/agent-development
'@penguinharness/agent-tuning': file:plugins/agent-tuning
'@penguinharness/continual-learning': file:plugins/continual-learning
@@ -5491,6 +5508,7 @@ snapshots:
'@prismshadow/penguin-core@file:packages/core([email protected])([email protected])':
dependencies:
'@modelcontextprotocol/client': 2.0.0
+ '@penguinharness/agent-company': file:plugins/agent-company
'@penguinharness/agent-development': file:plugins/agent-development
'@penguinharness/agent-tuning': file:plugins/agent-tuning
'@penguinharness/continual-learning': file:plugins/continual-learning
@@ -5518,6 +5536,7 @@ snapshots:
'@prismshadow/penguin-core@file:packages/core([email protected])([email protected])([email protected])':
dependencies:
'@modelcontextprotocol/client': 2.0.0
+ '@penguinharness/agent-company': file:plugins/agent-company
'@penguinharness/agent-development': file:plugins/agent-development
'@penguinharness/agent-tuning': file:plugins/agent-tuning
'@penguinharness/continual-learning': file:plugins/continual-learning