SLOPSHOPPER

teams

A sibling of graph for requests too big for one pass: a TaskManager MCP (task-manager) sizes the request; size L is planned into a PRD and user stories, split…

panebandguardcommandtoaststatus
★ 3v0.60.1MITupdated 2026-10-26newkayak12/claude-skills/teams
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · teams
│ ┃ Teams ✕ › fix the failing auth test and add an audit log call │ ┃ No teams run in this session. │ ┃ ⏺ Read(src/auth.ts) │ ┃ q close ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /teams-status │ ⎿ teams: dev │ ⎿ teams: │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Teams
No teams run in this session. q close
README

teams

English · 한국어

teams runs a request the way a small software team would. A request that is too big for one pass is sized, planned, split into packages (one per piece of work), and each package is handed to its own worker in its own git worktree. Every result is judged before it is accepted, the accepted branches are merged into one integration tree, QA exercises the merged result, and a final goal gate decides whether the request was actually met. You get a report either way. A large (size L) request gets a PRD and user stories first. A small (size S) request skips all of that and is handed to the development harness, which plans, gates and reports it with its own stages.

Use teams when the work splits into parts, is not only code (a design doc, a PRD, a QA pass), or should keep running after you close the session. Use graph for a single code change you want to drive in one session.

graphteams
Good forone code request, one runsized/split requests, documents, PRDs, QA, backlogs
MCP serversgraph-engineering (graph_*)teams-engineering (team_*) + task-manager (tm_*) + teams-wiki (wiki_*)
Who drivesyour sessiona background daemon; your session only watches
Run files.harness-run/broker/.teams_output/broker/ (runs), ~/.harness/tasks/ (tasks)
Version line1.x0.x

Both can be enabled in the same project: the tool prefixes and run directories are distinct.

How it fits together

flowchart TB
  U["You, in a Claude Code session"] --> SK["Entry skill: orchestrate, develop, document, plan, qa, sprint"]
  SK -->|"tm_open / tm_run"| TM["task-manager MCP server, tm_* tools"]
  CLI["scripts/run.mjs, headless"] -->|"same open and wait"| TM
  TM -->|"spawns, detached"| DM["Task daemon"]
  DM <--> TJ[("task.json and ledger in ~/.harness/tasks")]
  DM -->|"one claude -p call per judging step"| J["Judge: size, areas, accept, plan-integrate, shape, critique, integrate, gate, report"]
  DM -->|"per package: worktree + driver"| P1
  DM -->|"per package: worktree + driver"| P2
  subgraph P1["Package P1: own worktree and branch"]
    D1["claude -p driver"] -->|"team_* tools"| B1["teams-engineering broker"]
    B1 --> R1["child graph run"]
  end
  subgraph P2["Package P2: own worktree and branch"]
    D2["claude -p driver"] -->|"team_* tools"| B2["teams-engineering broker"]
    B2 --> R2["child graph run"]
  end
  P1 -->|"accepted branch"| IT["Integration worktree"]
  P2 -->|"accepted branch"| IT
  IT --> RP["Report, retro.json, phase docs"]
  • task-manager (mcp/taskmanager.mjs) owns a task: its node graph, packages, worktrees and verdicts. It never does the work itself, and it reads child run files without ever writing them.
  • The daemon (mcp/daemon.mjs) is spawned by tm_open and outlives your session. It moves the task forward, calls a one-shot claude -p judge whenever a step needs judgment, and respawns dead or stalled drivers.
  • A driver is a headless claude -p session that drives one package's child run through the teams-engineering broker (mcp/broker.mjs, team_* tools). The broker is the same engine lineage as graph.
  • Integration merges accepted package branches into a separate integration worktree. teams never merges into your own branch; that tree is where the delivered work lives.

One task, start to finish

flowchart TD
  OPEN["tm_open"] --> SIZE{"size"}
  SIZE -->|"S"| SRUN["development harness run in the project directory, its own six stages"]
  SRUN --> SREP["report: the harness run's own goal gate and report, relayed"]
  SIZE -->|"L"| BS["brainstorm"]
  BS --> AREAS["areas: split the request by feature"]
  AREAS --> ACRIT{"areas-critique"}
  ACRIT -->|"coverage, overlap, criterion, granularity"| AREAS
  ACRIT -->|"sound"| PCARDS["planning cards PLAN-F1, PLAN-F2, ...<br/>one per feature area, full run each, in parallel"]
  PCARDS --> PACC{"accept, per card"}
  PACC -->|"rejected"| PCARDS
  PACC -->|"all accepted"| PI{"plan-integrate: merge into 10-prd.md and judge"}
  PI -->|"id collision, contradiction, missing feature"| PCARDS
  PI -->|"resplit: the split itself is wrong"| AREAS
  PI -->|"accepted"| SHAPE["shape: split the stories by ownership into packages"]
  SHAPE --> CRIT{"critique"}
  CRIT -->|"unsound"| SHAPE
  CRIT -->|"sound"| DISP["develop: each package runs the full harness in its own worktree<br/>plan → setgoal → critique → implement → test → gate → gate:goal → report<br/>in parallel where deps allow"]
  DISP --> ACC{"accept, per package"}
  ACC -->|"rejected"| DISP
  ACC -->|"all accepted"| INT{"integrate"}
  INT -->|"not verified"| REPAIR["repair package on the merged tree"]
  REPAIR --> INT
  INT -->|"verified"| QA{"QA cards QA-F1, QA-F2, ...<br/>one per feature area, in parallel"}
  QA -->|"defects found"| FIX["fix STORYs, dispatched like packages"]
  FIX --> INT
  QA -->|"clean"| AUDIT{"planning audit"}
  AUDIT -->|"unmet user stories"| FIX
  AUDIT -->|"all met"| GOAL{"gate:goal"}
  GOAL --> REPORT["report"]

What each step does:

StepWhat happensSwitch
sizeA judge decides S (one run is enough) or L (split it). You can pin it with size. A size-S task stops here in teams: it is handed to the development harness (the graph MCP, or the harness skill's Agent Team fallback), claude and codex taking part, which plans, sets goals, critiques, implements, tests and gates it with its own stages. No planning card, split, shape, worktree or QA card. The run is tagged with the task id; its own goal gate decides complete or partial, and its report is relayed.—
brainstormRestates intent, scope and approach; asks you questions only when interactive. Skipped when your session already passed decisions.brainstorm
areasThe EPIC's plan stage splits the request by feature: what a user must be able to do, grouped into feature areas. Each area becomes a planning card.—
areas-critiqueNew. A judge attacks the split before any card runs: a feature in no area, two areas planning the same feature, an area cut by module or layer instead of by what a user does, padded or merged areas. A refusal splits again with the defects as feedback.max_retries, human_gates
planning cardsOne STORY card per feature area (PLAN-F1, PLAN-F2, ...), each a full run in its own worktree, in parallel. Each writes its PRD section - goal, scope and non-goals, user stories with acceptance criteria (ids prefixed by the area, F1-US-1), open questions - and returns its user stories. A card is rejected when it wrote no PRD, a section is missing, it has no user stories, a story has no acceptance criteria, or a story id lacks the card's prefix; a rejected card is retried with the reasons. With acceptance already declared in the request each card runs a lighter chain.roles.planning (true, "light", "auto"; false is refused)
plan-integrateMerges every card's section into one 10-prd.md, then a judge checks it: story ids that collide, areas that contradict each other, a feature the request names that no card covers. A rejection sends the offending cards back with the gaps (or opens a card for the missing feature). When the split itself is wrong it returns resplit: the cards are retired (kept as history, out of the PRD) and areas splits again.max_retries, human_gates
shape → critiqueshape splits the merged user stories again, this time by ownership, into packages with touches[] and deps; every story must be implemented by some package. critique checks the split. An unsound shape is reshaped.—
develop (dispatch)The actual development. Each package gets its own git worktree and a driver session that runs the package's child run through the full harness: plan → setgoal → critique → implement → test → gate → gate:goal → report. plan is a build plan for that one package (files, interfaces, order of work, test plan, risks), not a re-split; setgoal carries the package's acceptance verbatim and critique checks the plan against it. A document package uses draft → review → gate in place of implement → test → gate. Packages whose deps are met run in parallel. See Inside one package.max_parallel_teams, vendor
acceptWhen a package's run finishes, a judge accepts or rejects its result. A rejection retries the package with the reasons attached.max_retries
integrateMerges the accepted branches and runs the checks. A seam no single package can see gets a repair package that works on the merged tree.—
QAOne QA card per feature area (QA-F1, QA-F2, ...), each a full run on the merged tree, in parallel, exercising its area's user stories. Once every card of the round has settled, their defects are filed together as fix STORYs, and the loop re-integrates and reopens every QA card. A card that runs out of retries is dropped from the round, not the round with it: its siblings' defects are still filed and the goal gate is told which area QA did not verify.roles.qa, qa_rounds
auditPlanning checks the merged result against the merged PRD. Unmet stories are filed like QA defects.roles.audit
gate:goalJudges the whole result against the original request (goal_threshold, default 90%).goal_threshold
reportAlways runs once the goal gate settles, pass or fail. Also writes retro.json for the next Sprint, including the user stories that did not ship - a story ships only when every package implementing it is in the final integration, and that integrate passed; there is no sub-EPIC, so unfinished work carries into the next Sprint (tm_open({context_from}) returns them as carryover_candidates). Its open questions include the ones a headless task decided for nobody, a package's contradicts_decision first, so the next Sprint's planning takes up a spec a package found could not hold. The session that opened the Sprint picks the carry-over and opens the next one; that is the long loop.—

Every loop has a budget (max_retries, qa_rounds, upstream_fix_rounds). When one runs out, the failure is settled: what depends on it is marked unreachable and the task goes on to its report instead of hanging. That holds before shape too: a split, a planning card or a planning integrate out of retries closes the task to a report and retro.json (with whatever PRD the cards wrote) instead of leaving it blocked with neither. A budget or timebox stop works the same way: nothing new is dispatched, the accepted packages are integrated, and the rest is listed as "Next backlog".

Two more loops exist but are left out of the diagram: an integrate conflict (two packages editing the same thing) needs tm_retry({repackage}), and a package that finds a bug in a package it depends on files an upstream fix there and waits for it (upstream_fix_rounds).

Inside one package

Every package runs the full harness inside its own child run, the same four steps the task runs around it (plan, set a goal, check it, build and judge). Planning cards (PLAN-F1, ...), QA cards (QA-F1, ...), the audit, and repair packages run the same shape:

flowchart LR
  PLN["plan"] --> SG["setgoal"] --> CR["critique"] --> CH["one chain per subgoal"] --> RD["reduce, if more than one subgoal"] --> GG["gate:goal"] --> RE["report"]

For a develop package, shape has already split the EPIC and critique has already checked that split, so the package's own plan is a build plan for this package: the files and modules to touch, the interfaces and data shapes, the order of work, the test plan and the risks. It does not split the EPIC again. setgoal usually keeps one subgoal and copies the package's acceptance into the spec word for word; critique judges the plan and spec against the package's brief and acceptance. The package's gate:goal verdict and report handoff are what the manager's accept reads. A human pin on the STORY (tm_assign, or assignee in the shape) applies to every subgoal the package's setgoal produces.

Each subgoal expands into a node chain chosen by its kind (KINDS in mcp/graph.mjs). The author of a stage is never the one who judges it.

flowchart LR
  subgraph code["subgoal: code"]
    C1["implement"] --> C2["test"] --> C3["gate"]
  end
  subgraph doc["document"]
    D1["draft"] --> D2["review"] --> D3["gate"]
  end
  subgraph pl["planning"]
    P1["investigate"] --> P2["draft"] --> P3["revise"] --> P4["gate"]
  end
  subgraph pll["planning-light"]
    L1["investigate"] --> L2["template-fill"] --> L3["gate"]
  end
  subgraph qa["qa"]
    Q1["cases"] --> Q2["execute"] --> Q3["gate"]
  end
  subgraph au["planning-audit"]
    A1["audit"] --> A2["gate"]
  end

A rejected gate retries its subgoal with the gate's gaps as feedback. An interactive planning run can stop after investigate with an ask card for you.

Which chain a subgoal gets depends on the run's flow: develop → code, document → document, plan → planning (or planning-light), qa → qa, and the post-QA audit → planning-audit.

Writing skills mount by stage: planning investigate mounts write:requirements; planning draft and template-fill mount write:prd; document draft mounts write:prd by default and write:adr when the setgoal names it.

Planning and QA run on cards, and every card is a full run like this one: a planning card (PLAN-F1, ...) in a worktree of its own, a QA card (QA-F1, ...) on the integration tree. The task itself runs the same six stages around its cards - areas is its plan, plan-integrate, accept and gate:goal are its gates - so no team runs a chain without a plan before it and a gate after it (design: _repo/docs/plans/2026-09-28-teams-cards-everywhere.md).

How a task ends

stateDiagram-v2
  [*] --> running: tm_open
  running --> waiting_human: a card needs a person
  waiting_human --> running: tm_submit or ask_timeout
  running --> blocked: stopped with work left and nothing runnable
  blocked --> running: tm_retry or resume-on-limit
  running --> complete: report written, everything delivered
  running --> partial: report written, something missing
  complete --> [*]
  partial --> [*]
StateMeaning
runningThe daemon is working on it.
waiting_humanA card needs you: an ask question, a stage you took with teams:take, or a human_gates verdict. See teams:inbox.
blockedIt stopped with work left and nothing it can run on its own, for example a spent retry budget, a driver that kept dying, or a usage limit. tm_retry opens a fresh attempt.
completeThe report is written and everything was delivered.
partialNew. The report is written but something was not delivered: a package not accepted or never dispatched, integrate failed, QA or audit gave no verdict, gate:goal did not pass, or nodes were settled/unreachable. partial_reasons: [...] says what.

Quick start

trophy rides along. From this version, the first interactive session after you install or update this plugin installs trophy (achievements) once, in user scope, if you don't have it. Nothing is sent until you say yes; uninstalling trophy is respected (it is never reinstalled). To opt out beforehand: mkdir -p ~/.claude/plugins/.newkayak12-trophy-ride.done. Needs sh (Windows without one is not covered).

Install. Install teams@newkayak12-claude-skills; that registers its three MCP servers (reload Claude Code if the tm_*/team_*/wiki_* tools do not show). teams:install is optional. It pins project defaults in .claude/team.json, adds a dispatch gate, and adds .claude/conventions/ (optionally filled from a reference project via develop:like-my-code). Without it, the built-in defaults apply. Details: docs/configuration.md#install.

Run. Pick the entry skill that matches the work. All of them open the same kind of task.

SkillUse for
teams:orchestrateAnything; the engine picks the flow.
teams:developCode.
teams:documentA design doc, guide or other written artifact.
teams:planA PRD.
teams:qaWriting and running test cases against existing work.
teams:sprintA prioritized backlog under a budget or timebox, ending in a retro.

Maintenance skills: teams:install and teams:remove (project setup), teams:patch (release bump for this repository's source).

Watch. You do not need to drive anything. Watch with:

To seeUse
Every EPIC, or one EPIC's STORY boardteams:board (tm_board)
One ticket (E-xxxxxxxx, E-xxxxxxxx/P2)teams:ticket (tm_ticket)
What a ticket is doing right nowteams:log (tm_log)
What is waiting on youteams:inbox; answer with teams:submit; claim a card with teams:take
A live page in the browsernode teams/scripts/view.mjs (pipeline, tickets and resources views; --once prints text)

Tickets follow Initiative (optional) > EPIC > STORY > TASK: I-<slug>, E-xxxxxxxx (the task), E-xxxxxxxx/Pn (a package; also E-xxxxxxxx/PLAN-F1 for a planning card and E-xxxxxxxx/QA-F1 for a QA card), E-xxxxxxxx/Pn/<subgoal> (a node chain).

Headless / CI. scripts/run.mjs opens a task and waits for it with no session in the loop:

node teams/scripts/run.mjs "<request>" [--kind auto|develop|document] [--size S|L]
  [--budget-usd <n>] [--timebox-minutes <n>] [--json] [--resume-on-limit]
node teams/scripts/run.mjs --resume <task_id>
ExitMeaning
0complete
3partial: report written, not everything delivered
2waiting_human: the question is printed; answer it with tm_submit, then --resume
1anything else that stopped (blocked, a usage limit it could not wait out)
64bad arguments
130Ctrl-C: the task keeps running in its daemon; the CLI only stops watching

All flags, the --resume-on-limit behaviour and the --json event stream: docs/configuration.md#headless.

Configuration

Put project defaults in .claude/team.json. The order is built-in default < team.json < an argument of the same name on tm_open/team_open. An unknown key or a bad value is ignored and noted in tm_status. The schema is TEAM_DEFAULTS in mcp/teamconfig.mjs. The full explanation of every key is in docs/configuration.md.

KeyDefaultWhat it does
vendor"auto"Which model vendor runs the nodes.
allocation"ordered"How nodes are routed across vendors ("ordered" or "balanced").
goal_threshold90Minimum match % for a goal gate to accept.
max_retries2Retries per package, shape and subgoal before the failure is settled.
retry_policy"continue"Whether a retry builds on the failed attempt's worktree or rolls it back first.
roles{planning:"auto", qa:true, audit:true}Which chain the planning cards run (true full, "light", "auto" light when acceptance is declared), and whether the QA cards and the audit run. planning: false is refused with a note: planning always runs.
brainstormtrueRuns the engine's own brainstorm step when no decisions were passed.
interactivefalseWhether questions, pins and human gates wait for a person or are decided by default.
human_gates[]Judging stages ("critique", "accept", "gate:goal", "areas-critique", "plan-integrate", ...) that a person decides instead of a model. A person refusing plan-integrate may pass resplit: true. Needs interactive: true: otherwise the listed gates auto-pass, and tm_open warns in notes.
ask_timeoutnullMilliseconds before an unanswered ask card takes its default answer; null waits forever.
max_parallel_teams"auto"How many develop packages run at once; "auto" adapts to rate limits and crashes.
max_parallel_ceilingnullUpper limit for the "auto" controller; null derives one from the CPU count.
driver_restarts2How many times a dead driver is respawned before its dispatch is marked blocked.
restart_period_minutes0Counts driver_restarts in a sliding window of this many minutes; 0 counts forever.
stall_minutes20A driver idle this long is flagged, and after 3x this long it is killed and respawned; 0 disables this.
budget_usdnullSpend cap for the whole task; at 100% nothing new is dispatched and the task closes to its report.
timebox_minutesnullThe same stop, measured in minutes since tm_open.
budget_grace_usdnullExtra spend a running dispatch may use after the stop before it is killed (10% of budget_usd when unset).
budget_grace_minutes5Extra time a running dispatch may use after the stop before it is killed.
qa_rounds2How many QA or audit rounds may file fix STORYs; further defects go to unresolved_defects.
upstream_fix_rounds2How many upstream fixes may be filed against one package.
docs_dir.teams_output/teamWhere the phase documents (INDEX.md, per-STORY pages, report) are written.
plugin_dirs[]Extra --plugin-dir paths for every driver and judge session.
initiativenullA label that groups several EPICs on the board; display only.

goal_judges and auto_reassign are call arguments only, not team.json keys.

Wiki memory (teams-wiki)

teams-wiki is a third MCP server in this plugin: the place where subagents (claude and codex node workers and drivers) communicate through documents in the main project's .teams_wiki, and project memory that outlives a session. The server works without the task engine; the engine uses it as described under "In the task engine".

flowchart LR
  subgraph PRJ["Main project (task.cwd)"]
    W[(".teams_wiki/&lt;space&gt;/&lt;slug&gt;.md")]
  end
  subgraph WORK["Workers: investigate, plan, implement, draft ... (claude and codex)"]
    N1["node in package worktree P1"]
    N2["node in package worktree P2"]
    N3["node of a later task"]
  end
  N1 -->|"wiki_write: findings, decisions, contracts, pitfalls"| W
  N2 -->|"wiki_search / wiki_get when it needs context"| W
  W -->|"read on their own"| N3
  subgraph JUDGE["Judging: review, gate, accept, critique, test, audit, qa execute, manager judges"]
    G["no wiki tools, prompt: the wiki is not evidence"]
  end
  JUDGE -.-x W
  W -->|"pages modified while the task ran"| RP["Report: Wiki 변경"]

What goes in. Only what someone will need later and cannot get from the code or git: a fact with its source, a decision with its reason, an interface or contract another package relies on, a pitfall. Pages link with [[space/slug]], so one page leads to the next. Progress logs, task status and verdicts do not go in; the report and the ledger already hold those.

Pages are markdown under .teams_wiki/<space>/<slug>.md, git-tracked and hand-editable; that is the source. .teams_wiki/.index.sqlite (FTS5 search plus the [[link]] graph) is disposable: delete it and the next call rebuilds it from the md files. Search has two modes: fts5 when node:sqlite with FTS5 exists, otherwise scan (it reads the md files directly; no index file). Same results either way. Node 18+ is enough; wiki_status, tm_status and the report show the mode.

ToolWhat it does
wiki_searchSearch pages (Korean and English).

| wiki_get | One page w

Source 4 files
hooks/mod.tsx 859 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Decision, DecisionsPayload, Mark, PaneView, ReportPayload, StatusInfo, SummaryItem, SummaryTask, SummaryTaskEntry, TeamsEvent, TeamsView } from '../types'
5import { askBandShown, carriesInput, fallbackSelection, paneKey, paneSlash, statusAnswer, stepClamp, storyRows } from './pane'
6import { STORY_SHRINK, columnWidths, epicCells, epicState, handoffCells, renderLines, rowLine, since, storyCells, tabRowPlan, footerPlan, workerCells } from './teams-draw'
7import type { Line } from './teams-draw'
8
9const cursor = atom({ plugin: 'teams', key: 'cursor' } as const, 0)
10const status = atom({ plugin: 'teams', key: 'status' } as const, null as StatusInfo | null)
11const summary = atom({ plugin: 'teams', key: 'summary' } as const, null as SummaryTask | null)
12const teams = atom({ plugin: 'teams', key: 'teams' } as const, null as TeamsView | null)
13const decisions = atom({ plugin: 'teams', key: 'decisions' } as const, null as { task_id: string; card: string | null; payload: DecisionsPayload } | null)
14const selected = atom({ plugin: 'teams', key: 'selected' } as const, null as string | null)
15const watch = atom({ plugin: 'teams', key: 'watch' } as const, [] as string[])
16const view = atom({ plugin: 'teams', key: 'view' } as const, 'floor' as PaneView)
17// every listed EPIC (live first, then stalled), the ids of the tick before, the one the pane shows, and the STORY row `g` opens
18const tasks = atom({ plugin: 'teams', key: 'tasks' } as const, [] as SummaryTaskEntry[])
19const taskIds = atom({ plugin: 'teams', key: 'taskIds' } as const, [] as string[])
20const epic = atom({ plugin: 'teams', key: 'epic' } as const, null as string | null)
21const row = atom({ plugin: 'teams', key: 'row' } as const, 0)
22// the spinner frame beside an acting worker; moved by the 800 ms clock only while a worker acts
23const frame = atom({ plugin: 'teams', key: 'frame' } as const, 0)
24// the report of one task: keyed to the task it was fetched for, so a card or tab never draws another's
25const report = atom({ plugin: 'teams', key: 'report' } as const, null as { task_id: string; payload: ReportPayload } | null)
26// the report behind the end-of-run card: its own atom, so an open Report tab on another task never
27// replaces it (nor it the tab)
28const cardReport = atom({ plugin: 'teams', key: 'cardReport' } as const, null as { task_id: string; payload: ReportPayload } | null)
29const lang = atom({ plugin: 'teams', key: 'lang' } as const, 'en' as 'en' | 'ko')
30
31// the end-of-run card per ended task: 'card' while it is shown, 'seen' once its report was opened,
32// 'dismissed' on the person's say-so
33type Ended = Record<string, 'card' | 'seen' | 'dismissed'>
34const ended = atom({ plugin: 'teams', key: 'ended' } as const, {} as Ended)
35const mark = (m: Ended, id: string, state: Ended[string]): Ended => ({ ...m, [id]: state })
36
37const PANE = 'teams-status'
38// opened by the person: it takes the keys, and Escape hands them back by closing it
39const OPEN = { id: PANE, title: 'Teams', focus: true, closeOnEscape: true } as const
40
41const en = {
42  tabFloor: 'Floor', tabStories: 'STORYs', tabDecisions: 'Decisions', tabLog: 'Log', tabReport: 'Report', close: 'q close',
43  teamPlanning: 'Planning', teamDevelop: 'Develop', teamQa: 'QA', teamAudit: 'Audit', teamEpic: 'EPIC', nodeWaiting: 'waiting for you',
44  decAll: 'all cards', decCard: 'Card {c}', decNone: 'No decisions recorded yet.',
45  kindProposal: 'proposed', kindRetry: 'retry', kindRejudge: 're-judge', kindResplit: 're-split', kindDefect: 'defect filed', kindAnswer: 'answered', kindDecision: 'decided',
46  vAccept: 'accepted', vSound: 'sound', vVerified: 'verified', vReject: 'rejected', vJudgeFailed: 'could not judge',
47  lineBlocking: 'blocking', lineProblems: 'problems', lineGaps: 'gaps', lineEvidence: 'evidence',
48  paneClosed: 'pane closed',
49  cardFinished: 'finished', cardBlocked: 'blocked', cardFailed: 'failed {n}', cardMore: '+{n} more', reportButton: 'report', dismiss: '×',
50  reportMissing: 'No report yet: {path}', reportTruncated: 'Shortened: {n} more lines in the file.',
51  stages: 'Stages', work: 'Work', cost: 'Cost',
52  youOthers: '{n} more in other runs', costLine: '{usd} · {turns} turns',
53  headLine: '{state} · {done}/{total}', wordIdle: 'idle', wordDone: 'done', wordStalled: 'stalled', wordFailed: 'failed', bandDone: '{done}/{total} done',
54  stateRunning: 'running', stateStalled: 'stalled', stateComplete: 'finished', stateFailed: 'failed',
55  stagePlan: 'Plan', stageBuild: 'Build', stageIntegrate: 'Integrate', stageQa: 'QA', stageGate: 'Final gate', stageReport: 'Report',
56  nowFix: 'Fixing defect', nowFixnext: 'Waiting to fix defect', nowBuild: 'Building', nowPlan: 'Planning', nowQa: 'QA', nowAnswer: 'Waiting for your answer',
57  nowIntegrate: 'Integrating', nowGate: 'Final gate', nowReport: 'Writing the report', nowDone: 'All done', nowIdle: 'Idle',
58  logPassed: '{s} passed', logFailed: '{s} failed', logFiled: '{s} filed', logIntegrated: '{s} integrated',
59  logDispatched: '{s} started', logWaiting: '{s} waiting for you', logFinished: '{s} finished',
60  noRun: 'No teams run in this session.', loading: 'Loading...', noLog: 'Nothing logged yet.',
61  workMore: '+{n} more', cmdDesc: 'Open or close the teams status pane', paneOpened: 'pane opened',
62  asksYou: '{who} asks you: {q}',
63  board: 'board', inboxOne: '{n} question for you', inboxMany: '{n} questions for you', statusWaiting: 'needs you: {n} waiting - open /teams-status',
64  pushRejected: 'rejected', pushNeedsYou: 'needs you', pushEnded: 'run ended', nodeFailed: 'failed',
65  prev: '◀', next: '▶', keysHint: '[ ] EPIC · j k row · 1-5 tabs', openHint: 'g open run', noStories: 'No STORY at work.',
66}
67
68// one table, two languages; the type keeps the keys identical
69export const STRINGS: Record<'en' | 'ko', Record<keyof typeof en, string>> = {
70  en,
71  ko: {
72    tabFloor: '현장', tabStories: '스토리', tabDecisions: '결정', tabLog: '기록', tabReport: '보고서', close: 'q 닫기',
73    teamPlanning: '기획', teamDevelop: '개발', teamQa: 'QA', teamAudit: '감사', teamEpic: '에픽', nodeWaiting: '답변 대기',
74    decAll: '전체 카드', decCard: '카드 {c}', decNone: '아직 기록된 결정이 없습니다.',
75    kindProposal: '제안', kindRetry: '재시도', kindRejudge: '재판정', kindResplit: '재분할', kindDefect: '결함 등록', kindAnswer: '답변', kindDecision: '결정',
76    vAccept: '승인', vSound: '타당', vVerified: '검증됨', vReject: '반려', vJudgeFailed: '판정 실패',
77    lineBlocking: '차단', lineProblems: '문제', lineGaps: '누락', lineEvidence: '근거',
78    paneClosed: '창을 닫았습니다',
79    cardFinished: '끝남', cardBlocked: '막힘', cardFailed: '실패 {n}', cardMore: '+{n}건 더', reportButton: '보고서', dismiss: '×',
80    reportMissing: '아직 보고서가 없습니다: {path}', reportTruncated: '일부만 표시: 파일에 {n}줄 더 있습니다.',
81    stages: '단계', work: '작업', cost: '비용',
82    youOthers: '다른 실행에 {n}건 더', costLine: '{usd} · {turns}턴',
83    headLine: '{state} · {done}/{total}', wordIdle: '유휴', wordDone: '완료', wordStalled: '멈춤', wordFailed: '실패', bandDone: '{done}/{total} 완료',
84    stateRunning: '진행 중', stateStalled: '멈춤', stateComplete: '완료', stateFailed: '실패',
85    stagePlan: '계획', stageBuild: '구현', stageIntegrate: '통합', stageQa: 'QA', stageGate: '최종 관문', stageReport: '보고',
86    nowFix: '결함 수정 중', nowFixnext: '결함 수정 대기', nowBuild: '구현 중', nowPlan: '계획 중', nowQa: 'QA 중', nowAnswer: '답변 대기 중',
87    nowIntegrate: '통합 중', nowGate: '최종 관문', nowReport: '보고서 작성 중', nowDone: '모두 끝남', nowIdle: '대기 중',
88    logPassed: '{s} 통과', logFailed: '{s} 실패', logFiled: '{s} 등록', logIntegrated: '{s} 반영',
89    logDispatched: '{s} 시작', logWaiting: '{s} 답변 대기', logFinished: '{s} 끝남',
90    noRun: '이 세션에 팀 실행이 없습니다.', loading: '불러오는 중...', noLog: '아직 기록이 없습니다.',
91    workMore: '+{n}건 더', cmdDesc: '팀 현황 창 열기/닫기', paneOpened: '창을 열었습니다',
92    asksYou: '{who}님이 묻습니다: {q}',
93    board: '보드', inboxOne: '질문 {n}건', inboxMany: '질문 {n}건', statusWaiting: '확인 필요: {n}건 대기 - /teams-status 열기',
94    pushRejected: '반려', pushNeedsYou: '확인 필요', pushEnded: '실행 종료', nodeFailed: '실패',
95    prev: '◀', next: '▶', keysHint: '[ ] 에픽 · j k 행 · 1-5 탭', openHint: 'g 실행 열기', noStories: '진행 중인 스토리가 없습니다.',
96  },
97}
98
99// a key the table lacks (a state or kind this mod does not know) formats to ''
100const fmt = (text: string | undefined, vars: Record<string, string | number> = {}) =>
101  (text ?? '').replace(/\{(\w+)\}/g, (_, k: string) => String(vars[k] ?? ''))
102
103const MARK: Record<Mark, string> = { done: '✔', running: '●', pending: '○', failed: '✘' }
104// the stage rail: a dot per stage, a solid rail up to where the run is, dotted after
105const DOT: Record<Mark, string> = { done: '●', running: '◉', pending: '○', failed: '✘' }
106const TINT: Record<Mark, string> = { done: 'success', running: 'claude', pending: 'inactive', failed: 'error' }
107const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1)
108
109const VERDICT_WORD: Record<string, keyof typeof en> = { accept: 'vAccept', sound: 'vSound', verified: 'vVerified', reject: 'vReject', judge_failed: 'vJudgeFailed' }
110
111const asRecord = (v: unknown): Record<string, unknown> | undefined =>
112  typeof v === 'object' && v !== null ? (v as Record<string, unknown>) : undefined
113
114// task_id of a tm_open/tm_run result: structuredContent first, then JSON in content[0].text
115function taskIdOf(r: { result?: unknown; text?: unknown }): string | undefined {
116  const res = asRecord(r.result)
117  const fromStructured = asRecord(res?.structuredContent)?.task_id
118  if (typeof fromStructured === 'string' && fromStructured !== '') return fromStructured
119  const content = res?.content
120  const first = Array.isArray(content) ? asRecord(content[0])?.text : r.text
121  if (typeof first !== 'string') return undefined
122  try {
123    const id = asRecord(JSON.parse(first))?.task_id
124    return typeof id === 'string' && id !== '' ? id : undefined
125  } catch {
126    return undefined
127  }
128}
129
130// the pane's task: the picked EPIC, else the last watched one, else this cwd's newest running one (from the tick's status)
131async function paneTask($: EngineInterface): Promise<string | undefined> {
132  return (await read($, epic)) ?? (await read($, watch)).at(-1) ?? (await read($, status))?.latest ?? undefined
133}
134
135// a person's words for the card the task is on now
136function nowSentence(s: (key: keyof typeof en) => string, task: SummaryTask): string {
137  const label = s(`now${cap(task.now.kind)}` as keyof typeof en) || s('nowIdle')
138  return task.now.subject ? `${label}: ${task.now.subject}` : label
139}
140
141// One report call for a task: the payload is stored under that task's id. A failed call or
142// unreadable output leaves what was stored.
143async function fetchReport($: EngineInterface, taskId: string, forCard = false): Promise<void> {
144  try {
145    const cwd = await $.session.cwd()
146    const r = await $.process.run(['node', `${$.plugin.root}/scripts/view.mjs`, '--once', '--format', 'report', '--task', taskId, '--cwd', cwd])
147    if (r.exitCode !== 0) return
148    const payload = JSON.parse(r.stdout.trim().split('\n').pop() ?? '') as ReportPayload
149    if (forCard) await update($, cardReport, () => ({ task_id: taskId, payload }))
150    else await update($, report, () => ({ task_id: taskId, payload }))
151  } catch {
152    // a failed call keeps the last payload
153  }
154}
155
156// One decisions call for a task (and the picked card); a failed call keeps what was stored.
157async function fetchDecisions($: EngineInterface, taskId: string): Promise<void> {
158  try {
159    const cwd = await $.session.cwd()
160    const card = await read($, selected)
161    const r = await $.process.run(['node', `${$.plugin.root}/scripts/view.mjs`, '--once', '--format', 'decisions', '--task', taskId, '--cwd', cwd, ...(card === null ? [] : ['--card', card])])
162    if (r.exitCode !== 0) return
163    const payload = JSON.parse(r.stdout.trim().split('\n').pop() ?? '') as DecisionsPayload
164    await update($, decisions, () => ({ task_id: taskId, card, payload }))
165  } catch {
166    // a failed call keeps the last payload
167  }
168}
169
170// the task whose card is shown now: the latest one still marked 'card'
171const cardTask = (m: Record<string, string>) => Object.keys(m).filter(k => m[k] === 'card').at(-1)
172
173// push kinds: a reject (a failed node or spent fix rounds), a person must act, the run ended
174const PUSH_KIND: Record<string, keyof typeof en> = {
175  node_finish: 'pushRejected', upstream_fix_rounds_exhausted: 'pushRejected',
176  waiting_human: 'pushNeedsYou', daemon_done: 'pushEnded', daemon_exhausted: 'pushEnded',
177}
178
179// A failed node_finish as view.mjs tells it (scripts/lib/view-events.mjs): the node worked out the run,
180// node, reason and next step; the mod only draws them. A line missing any of them is an old-shape line.
181// (A local extension: teams/types is not this change's to edit.)
182type FailedFinish = TeamsEvent & { run?: string; node?: string; reason?: string; next_step?: string | null; severity?: string }
183type Failure = { run: string; node: string; reason: string; next: string | null; severity: 'info' | 'failure' }
184
185function failureOf(one: FailedFinish): Failure | null {
186  const { run, node, reason, next_step: next, severity } = one
187  if (one.kind !== 'node_finish' || typeof run !== 'string' || typeof node !== 'string' || typeof reason !== 'string') return null
188  if (severity !== 'info' && severity !== 'failure') return null
189  if (next !== undefined && next !== null && typeof next !== 'string') return null
190  return { run, node, reason, next: next ?? null, severity }
191}
192
193// `<node> failed: <reason> → <next step>`, the arrow left out when there is no next step
194const failureWhat = (f: Failure, word: string) => `${f.node} ${word}: ${f.reason}${f.next === null ? '' : ` → ${f.next}`}`
195
196const FAIL_TOAST_MS = 10000
197const PUSH_MAX = 200
198
199// info (retry, reshape, nothing yet) is ↻ with the default timeout; a person must act ⚠, gave up ✗, both held longer
200function toastFailure($: EngineInterface, f: Failure, word: string): void {
201  if (f.severity === 'info') $.ui.toast(`↻ ${f.run} ${failureWhat(f, word)}`)
202  else $.ui.toast(`${f.next === 'needs you' ? '⚠' : '✗'} ${f.run} ${failureWhat(f, word)}`, { timeoutMs: FAIL_TOAST_MS })
203}
204
205// One push for an event, `teams <task>: <kind> - <what>`. The event's text already toasts, so a push not
206// sent (user at the terminal, off, throw) needs no second toast. Fail open: nothing here may throw.
207async function pushEvent($: EngineInterface, one: TeamsEvent, sent: Set<string>): Promise<void> {
208  try {
209    const kind = PUSH_KIND[one.kind]
210    // a failed node pushes only once it needs you or gave up; a retry or reshape is a toast
211    const failed = failureOf(one)
212    if (failed !== null && failed.severity !== 'failure') return
213    // once per (task, kind, package, attempt); the ts keeps two lines of one attempt apart
214    const key = `${one.task_id}|${one.kind}|${one.package ?? ''}|${one.attempt ?? ''}|${one.text}|${one.ts}`
215    if (kind === undefined || sent.has(key)) return
216    sent.add(key)
217    // the run outcome trophy counts, from the daemon's state field; any other state is no outcome
218    const outcome =
219      one.kind === 'daemon_exhausted' ? 'fail'
220        : one.kind !== 'daemon_done' ? undefined
221          : one.state === 'complete' ? 'pass'
222            : one.state === 'partial' ? 'reject'
223              : one.state === 'blocked' ? 'fail'
224                : undefined
225    if (outcome !== undefined) {
226      try {
227        await $.state.set({ plugin: 'teams', key: 'outcome' }, { system: 'teams', outcome, at: await $.clock.now() })
228      } catch {
229        // fail open: a lost outcome never costs the push
230      }
231    }
232    const words = STRINGS[await read($, lang)]
233    let message: string
234    if (failed !== null) {
235      message = `teams ${failed.run}: ${words[kind]} \u2014 ${failureWhat(failed, words.nodeFailed)}`
236      if (message.length > PUSH_MAX) message = message.slice(0, PUSH_MAX - 1) + '\u2026'
237    } else {
238      const m = /^(E-\S+) (.*)$/.exec(one.text)
239      message = `teams ${m?.[1] ?? one.task_id}: ${words[kind]} \u2014 ${m?.[2] ?? one.text}`.slice(0, 200)
240    }
241    // PushNotification's result: { pushSent?, localSent? }
242    await $.tool.call({ tool: 'PushNotification', message, status: 'proactive' } as never)
243  } catch {
244    // a failed push is a push not sent
245  }
246}
247
248const TICK_MS = 3000
249const SPIN_MS = 800
250const WORK_MAX = 6
251
252export const register: Register = on => {
253  let isRunning = false
254  const pushed = new Set<string>()
255  // the session.start tick, kept so a received ask can refresh the data once
256  let refresh: (() => Promise<void>) | null = null
257
258  on('session.start', async ($, e, next) => {
259    if ((await $.session.surfaces()).length === 0) return next(e)
260
261    const VIEW = `${$.plugin.root}/scripts/view.mjs`
262
263    // the spinner clock runs only while the pane is open and a worker of the shown EPIC acts
264    let spinner: { cancel: () => void } | null = null
265    async function wantsSpin() {
266      if ((await $.session.surfaces()).length === 0) return false
267      if (!(await $.ui.panes()).some(p => p.id === PANE)) return false
268      const id = await paneTask($)
269      return (await read($, tasks)).find(t => t.task_id === id)?.workers.some(w => w.state === 'acting') ?? false
270    }
271    async function syncSpinner() {
272      const go = await wantsSpin()
273      if (go && spinner === null) {
274        spinner = $.clock.every(SPIN_MS, async () => {
275          if (await wantsSpin()) await update($, frame, n => n + 1)
276          else {
277            spinner?.cancel()
278            spinner = null
279          }
280        })
281      } else if (!go && spinner !== null) {
282        spinner.cancel()
283        spinner = null
284      }
285    }
286
287    async function tick() {
288      if (isRunning) return
289      isRunning = true
290      try {
291        const cwd = await $.session.cwd()
292        const since = await read($, cursor)
293
294        const fetched = new Set<string>()
295        const cardFetched = new Set<string>()
296        const ev = await $.process.run([
297          'node', VIEW, '--once', '--format', 'events', '--since', String(since), '--cwd', cwd,
298        ])
299        if (ev.exitCode === 0) {
300          const fresh: TeamsEvent[] = []
301          for (const line of ev.stdout.split('\n')) {
302            if (!line.trim()) continue
303            try {
304              const one = JSON.parse(line) as TeamsEvent
305              if (one.ts > since) fresh.push(one)
306            } catch {
307              // a torn line: skip it
308            }
309          }
310          if (fresh.length > 0) {
311            for (const one of fresh) {
312              const failure = failureOf(one)
313              if (failure === null) $.ui.toast(one.text)
314              else toastFailure($, failure, STRINGS[await read($, lang)].nodeFailed)
315              await pushEvent($, one, pushed)
316            }
317            // a run that ended after this session began gets a card and one report call
318            for (const one of fresh.filter(f => f.kind === 'daemon_done')) {
319              await update($, ended, m => mark(m, one.task_id, 'card'))
320              cardFetched.add(one.task_id)
321              await fetchReport($, one.task_id, true)
322            }
323            const latest = Math.max(...fresh.map(one => one.ts))
324            await update($, cursor, () => latest)
325          }
326        }
327
328        // one data call: the teams rows while the pane is open, the summary while a task of this cwd
329        // is running, else the status
330        const isOpen = (await $.ui.panes()).some(p => p.id === PANE)
331        const isSummary = isOpen || (await read($, status))?.latest != null
332        const id = isOpen ? await paneTask($) : undefined
333        let sid: string | undefined
334        try {
335          sid = await $.session.id()
336        } catch {
337          // no session id: the call goes without --session
338        }
339        const data = await $.process.run([
340          'node', VIEW, '--once', '--format', isOpen ? 'teams' : isSummary ? 'summary' : 'status', '--cwd', cwd,
341          ...(id === undefined ? [] : ['--task', id]),
342          ...(sid === undefined ? [] : ['--session', sid]),
343        ])
344        if (data.exitCode === 0) {
345          const parsed = JSON.parse(data.stdout) as { status: StatusInfo; tasks?: SummaryTaskEntry[]; task: SummaryTask | null; teams?: TeamsView | null } & StatusInfo
346          const info: StatusInfo = isSummary ? parsed.status : parsed
347          await update($, status, () => info)
348          await update($, summary, () => (isSummary ? parsed.task ?? null : null))
349          await update($, teams, () => parsed.teams ?? null)
350          if (isSummary) {
351            // the listed EPICs; a selection that left the list moves to the nearest and the pane stays open
352            const list = parsed.tasks ?? []
353            const ids = list.map(t => t.task_id)
354            await update($, tasks, () => list)
355            if (ids.length > 0) {
356              const current = await read($, epic)
357              const chosen = fallbackSelection(await read($, taskIds), ids, (await paneTask($)) ?? null)
358              if (chosen !== null && chosen !== current) await update($, epic, () => chosen)
359              await update($, taskIds, () => ids)
360            }
361          }
362          // pinned only while a person must act (the engine draws it as a warning); the ask band already says so
363          // Known limits: (1) the poll cannot see e.props.hasSurvey, so while a survey hides the band the status
364          // line has no segment either. (2) The poll cannot see a dismissed band, so a dismissed band does not
365          // bring the segment back; it returns only when asks are empty or the end-of-run card replaces the band.
366          // With no asks (which includes no interactive surface) the segment is kept.
367          const cardId = cardTask(await read($, ended))
368          const held = await read($, cardReport)
369          const cardShown = cardId !== undefined && held?.task_id === cardId && held.payload.verdict !== 'running'
370          $.ui.status(info.waiting > 0 && !askBandShown(info.asks, cardShown) ? fmt(STRINGS[await read($, lang)].statusWaiting, { n: info.waiting }) : undefined)
371        }
372        // the Decisions tab refetches only while it is open, for the pane's task and picked card
373        if (id !== undefined && (await read($, view)) === 'decisions') await fetchDecisions($, id)
374        // the Report tab refetches only while it is open, for the pane's task
375        const isTab = id !== undefined && (await read($, view)) === 'report'
376        if (isTab && (await read($, ended))[id] === 'card') await update($, ended, m => mark(m, id, 'seen'))
377        if (isTab && !fetched.has(id)) {
378          fetched.add(id)
379          await fetchReport($, id)
380        }
381        // a card waits for its report (none yet, or another task's in the atom)
382        const waiting = cardTask(await read($, ended))
383        if (waiting !== undefined && !cardFetched.has(waiting)) {
384          const held = await read($, cardReport)
385          if (held?.task_id !== waiting || held.payload.report === null) await fetchReport($, waiting, true)
386        }
387        await syncSpinner()
388      } catch {
389        // a failed run or unreadable output leaves the last status as it was
390      } finally {
391        isRunning = false
392      }
393    }
394
395    // Claude Code's own language setting, read once per session
396    try {
397      const language = (await $.settings.read()).language
398      await update($, lang, () => (typeof language === 'string' && /^(ko|korean|한국어)/i.test(language) ? 'ko' : 'en'))
399    } catch {
400      // unreadable settings: English
401    }
402    await $.command.register({ name: 'teams-status', description: STRINGS[await read($, lang)].cmdDesc })
403    // events older than this session's start are not toasted
404    const now = await $.clock.now()
405    await update($, cursor, since => (since === 0 ? now : since))
406    refresh = tick
407    $.clock.every(TICK_MS, tick)
408
409    return next(e)
410  })
411
412  // asked for by the person: the pane seats at any width; the command again closes it
413  on('command.run', { command: 'teams-status' }, async $ => {
414    if ((await $.ui.panes()).some(p => p.id === PANE)) {
415      await $.ui.close({ id: PANE })
416      return { text: STRINGS[await read($, lang)].paneClosed }
417    }
418    await $.ui.open(OPEN)
419    const paneOpened = STRINGS[await read($, lang)].paneOpened
420    let run: { exitCode: number; stdout: string } | null = null
421    try {
422      run = await $.process.run(['node', `${$.plugin.root}/scripts/view.mjs`, '--once', '--cwd', await $.session.cwd()])
423    } catch {
424      // a run that cannot start answers with the pane text
425    }
426    return { text: statusAnswer(run, paneOpened) }
427  })
428
429  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
430    const ui = $.ui.resolve(e)
431    const { Box, Button, Input, Markdown, Text } = ui
432    const kind = await read($, view)
433    const lang$ = await read($, lang)
434    const s = (key: keyof typeof en, vars?: Record<string, string | number>) => fmt(STRINGS[lang$][key], vars)
435    // node's word_key (idle, done, stalled, failed) names a STRINGS entry; a pure lookup, no decision
436    const fixedWord = (key: string) => s(`word${key.charAt(0).toUpperCase()}${key.slice(1)}` as keyof typeof en)
437    const id = await paneTask($)
438    const listed = await read($, tasks)
439    const entry = listed.find(t => t.task_id === id)
440    // the summary is drawn only for the EPIC the pane shows; right after a switch it is the last one's until the next tick
441    const held = await read($, summary)
442    const task = held !== null && entry !== undefined && held.key !== entry.key ? null : held
443    const info = await read($, status)
444    const inner = Math.max(20, (e.props.bodyColumns ?? 80) - 4)
445
446    // said once, as the footer's last item
447    // (no Button hotkey: the pane's Input holds the focus and takes `q` and `1`-`5` as text, see onKey)
448    const close = <Button key="close" role="dismiss" plain dimColor label={s('close')} onPress={() => $.ui.close({ id: PANE })} />
449    // plain tabs on one line: the selected one in full strength with a dot, the rest dim; `1`-`5` pick them
450    const TABS = ['floor', 'stories', 'decisions', 'log', 'report'] as const
451    const pickTab = async (one: (typeof TABS)[number]) => {
452      await update($, view, () => one)
453      if (one === 'report' && id !== undefined) {
454        await update($, ended, m => (m[id] === 'card' ? mark(m, id, 'seen') : m))
455        await fetchReport($, id)
456      }
457      if (one === 'decisions' && id !== undefined) await fetchDecisions($, id)
458    }
459    const costText = task === null ? '' : s('costLine', { usd: `$${task.cost.usd.toFixed(2)}`, turns: task.cost.turns })
460    const tabPlan = tabRowPlan(TABS.map(one => `${kind === one ? '● ' : ''}${s(`tab${cap(one)}` as keyof typeof en)}`), costText, inner)
461    const tabs = (
462      <Box columnGap={tabPlan.gap}>
463        {TABS.map((one, i) => (
464          <Box key={`tab-${one}`} flexShrink={0}><Button key={one} plain dimColor={kind !== one} label={tabPlan.labels[i]!} onPress={() => pickTab(one)} /></Box>
465        ))}
466      </Box>
467    )
468    if (id === undefined || (task === null && entry === undefined && kind !== 'report' && kind !== 'stories')) {
469      return (
470        <Box flexDirection="column">
471          <Text>{id === undefined ? s('noRun') : s('loading')}</Text>
472          {/* the empty view has no tabs to pick: its Input takes `q` only, so the pane closes on the key as it does elsewhere */}
473          {id === undefined && carriesInput(e.surface) && (
474            <Box height={1} overflow="hidden">
475              <Input key="keys" autoFocus value="" placeholder="" onInput={async (text: string) => { if (paneKey(text)?.kind === 'close') await $.ui.close({ id: PANE }) }} onSubmit={async () => {}} />
476            </Box>
477          )}
478          {close}
479        </Box>
480      )
481    }
482    // the task's report, drawn only when it was fetched for the pane's task: its path first, then
483    // (when capped) the truncated notice, then the text
484    const rp = await read($, report)
485    const mine = rp !== null && rp.task_id === id ? rp.payload : null
486    const reportBody = mine === null ? <Text dimColor>{s('loading')}</Text>
487      : mine.report === null ? <Text>{s('reportMissing', { path: mine.path })}</Text>
488      : (
489        <Box flexDirection="column">
490          <Text>{mine.path}</Text>
491          {mine.report.truncated && <Text color="warning">{s('reportTruncated', { n: mine.report.more_lines })}</Text>}
492          <Markdown text={mine.report.text} />
493        </Box>
494      )
495
496    // the listed EPICs, one line each, are the title block
497    const now = await $.clock.now()
498    const epicWord = (t: SummaryTaskEntry) => (t.state === 'waiting_human' ? s('nodeWaiting') : s(`state${cap(t.state)}` as keyof typeof en) || t.state)
499    const epicOf = listed.map(t => epicCells(t, epicState(t), t.task_id === id, now, epicWord(t)))
500    const epicWidths = columnWidths(epicOf.map(r => r.cells), inner, 2, [3], 4, [6, 5], 12)
501    const epicLines: Line[] = epicOf.map(r => rowLine(r.cells, epicWidths, 2, r.tints))
502    const epics = epicLines.length === 0 ? null : renderLines(ui, epicLines, 'e')
503
504    // the STORYs tab: every listed task's STORYs at work, columns at the same offset on every row
505    const rows = storyRows(listed)
506    const pick = Math.min(Math.max(0, await read($, row)), Math.max(0, rows.length - 1))
507    const verdictText = (v: string | null) => (v === null ? '' : VERDICT_WORD[v] === undefined ? v : s(VERDICT_WORD[v]!))
508    const harnessText = (t: SummaryTaskEntry) => t.harness === null ? ''
509      : `${t.stages.map(g => `${MARK[g.state]}${s(`stage${cap(g.key)}` as keyof typeof en)}`).join(' ')}${t.harness.slug ? ` · ${t.harness.slug}` : ''}${t.harness.moving ? ' ▸' : ''}`
510    const storyOf = rows.map(({ entry: t, item }, i) => storyCells(item, verdictText(item.last_verdict), harnessText(t), i === pick, fixedWord))
511    const storyWidths = columnWidths(storyOf.map(r => r.cells), inner, 2, STORY_SHRINK)
512    const storiesBody = rows.length === 0 ? <Text dimColor>{s('noStories')}</Text>
513      : renderLines(ui, storyOf.map(r => rowLine(r.cells, storyWidths, 2, r.tints)), 's')
514
515    // `[` `]` step the EPIC and stop at the ends; `j` `k` move the STORY row; `g` opens its run. The Input takes the
516    // keys (a Button hotkey is one digit or lowercase letter), prev / next are Buttons for the pointer
517    const cycle = async (by: 1 | -1) => {
518      const ids = listed.map(t => t.task_id)
519      if (ids.length === 0) return
520      const to = ids[stepClamp(Math.max(0, ids.indexOf(id)), by, ids.length)]!
521      if (to === id) return
522      await update($, epic, () => to)
523      await update($, row, () => 0)
524    }
525    const target = kind === 'stories' ? rows[pick]?.item : undefined
526    const canOpen = target?.run_file != null
527    const onKey = async (text: string) => {
528      const key = paneKey(text)
529      if (key === null) return
530      if (key.kind === 'close') await $.ui.close({ id: PANE })
531      else if (key.kind === 'tab') await pickTab(key.tab)
532      else if (key.kind === 'step') await cycle(key.by)
533      else if (kind !== 'stories') return
534      else if (key.kind === 'row') await update($, row, () => stepClamp(pick, key.by, rows.length))
535      else if (target !== undefined && target.run_file != null) {
536        try {
537          await $.command.run({ command: 'graph-status', args: `open ${target.run_file} ${target.owner_key}` })
538        } catch {
539          // a hand-off that is not there leaves the pane as it was
540        }
541      }
542    }
543    // the same Input takes a typed `/command`, held until Enter (paneKey fires no key on text holding `/`): `/teams-status`
544    // closes the pane, `/name args` runs that command. Not awaited: awaited inside onSubmit the host cuts the hook at its budget.
545    const onSubmit = async (text: string) => {
546      const slash = paneSlash(text)
547      if (slash === null) return
548      if (slash.kind === 'close') await $.ui.close({ id: PANE })
549      else void $.command.run({ command: slash.command, args: slash.args }).catch(() => {})
550    }
551    const openHint = kind === 'stories' ? s('openHint') : ''
552    const footerHint = footerPlan({ steps: listed.length > 1 ? 2 : 0, open: openHint, close: s('close'), hint: s('keysHint') }, inner).hint
553    const footer = (
554      <Box columnGap={2}>
555        {listed.length > 1 && <Button key="prev" plain label={s('prev')} onPress={() => cycle(-1)} />}
556        {listed.length > 1 && <Button key="next" plain label={s('next')} onPress={() => cycle(1)} />}
557        {carriesInput(e.surface) && <Box flexShrink={1} height={1} overflow="hidden"><Input key="keys" autoFocus value="" placeholder={footerHint} onInput={onKey} onSubmit={onSubmit} /></Box>}
558        {openHint !== '' && <Text dimColor={!canOpen}>{openHint}</Text>}
559        <Box flexShrink={0}>{close}</Box>
560      </Box>
561    )
562    if (task === null) {
563      return (
564        <Box flexDirection="column" borderStyle="round" borderColor="claude" paddingX={1}>
565          <Box marginY={1}>{tabs}</Box>
566          {epics}
567          {kind === 'stories' ? storiesBody : kind === 'report' ? reportBody : <Text>{s('loading')}</Text>}
568          {footer}
569        </Box>
570      )
571    }
572
573    const stateWord = s(`state${cap(task.state)}` as keyof typeof en) || task.state
574    const card = (c: SummaryTask['work'][number], i: number) => (
575      <Box key={`c${i}`} flexDirection="column">
576        <Text wrap="truncate-end"><Text color={TINT[c.state]}>{MARK[c.state]}</Text>{` ${c.title}`}</Text>
577        {c.state === 'failed' && c.reason && <Text color="error" wrap="truncate-end">{`  ${c.reason}`}</Text>}
578      </Box>
579    )
580
581    // above the tabs only what waits on the person: each waiting card with its question, then the runs besides this one
582    const others = (info?.waiting ?? 0) - task.you.count
583    const tv = await read($, teams)
584    const teamWord = (t: string) => s(`team${cap(t)}` as keyof typeof en) || t
585    const nodeWord = (n: string) => (n === 'waiting' ? s('nodeWaiting') : n)
586    const waitCards = task.you.cards ?? []
587    const waitBox = waitCards.length === 0 && others <= 0 ? null : (
588      <Box flexDirection="column" marginTop={1}>
589        {waitCards.map((c, i) => (
590          <Text key={`w${i}`} color="warning" wrap="truncate-end">{`⚑ ${c.title}${c.question ? ` — ${c.question}` : ''}`}</Text>
591        ))}
592        {others > 0 && <Text color="warning">{s('youOthers', { n: others })}</Text>}
593      </Box>
594    )
595    const pickCard = async (cardId: string) => {
596      await update($, selected, () => cardId)
597      await update($, view, () => 'decisions')
598      await fetchDecisions($, id)
599    }
600
601    // the Floor: one line per worker of the shown EPIC, then the newest hand-offs; columns at one offset per block
602    const frameNo = await read($, frame)
603    const workerOf = workerCells(entry?.workers ?? [], frameNo, fixedWord)
604    const workerWidths = columnWidths(workerOf.map(r => r.cells), inner, 2, [3])
605    const handoffOf = handoffCells(entry?.handoffs ?? [])
606    const handoffWidths = columnWidths(handoffOf, inner, 2, [2, 3])
607    // asks addressed to this session, from node's status.asks: one warning line each, above the hand-offs
608    const askOf = ((await read($, status))?.asks ?? []).map(a => [`⚑ ${a.who} → you`, a.question])
609    const askWidths = columnWidths(askOf, inner, 2, [1])
610    const floorLines = (
611      <Box flexDirection="column">
612        {askOf.length > 0 && <Box marginBottom={1}>{renderLines(ui, askOf.map(r => rowLine(r, askWidths, 2, ['warning'])), 'a')}</Box>}
613        {renderLines(ui, workerOf.map(r => rowLine(r.cells, workerWidths, 2, r.tints)), 'w')}
614        {handoffOf.length > 0 && <Box marginTop={1}>{renderLines(ui, handoffOf.map(r => rowLine(r, handoffWidths, 2, ['dim'])), 'h')}</Box>}
615      </Box>
616    )
617
618    // the stage rail heads the STORYs tab
619    const rail = (
620      <Box flexWrap="wrap" marginBottom={1}>
621        {task.stages.map((g, i) => {
622          const next = task.stages[i + 1]
623          const solid = next !== undefined && next.state !== 'pending'
624          return (
625            <Box key={g.key}>
626              <Text color={TINT[g.state]} bold={g.state === 'running'}>{`${DOT[g.state]} ${s(`stage${cap(g.key)}` as keyof typeof en)}`}</Text>
627              {next !== undefined && <Text color={solid ? 'success' : 'inactive'}>{solid ? ' ━━ ' : ' ┄┄ '}</Text>}
628            </Box>
629          )
630        })}
631      </Box>
632    )
633    // the card list heads the Decisions tab, where a picked card's thread is read
634    const reasonOf = (title: string) => task.work.find(w => w.title === title && w.state === 'failed')?.reason ?? null
635    const picker = tv === null ? (
636      // before the first teams call: the summary's card list
637      <Box flexDirection="column" marginBottom={1}>
638        {task.work.slice(0, WORK_MAX).map(card)}
639        {task.work.length > WORK_MAX && <Text dimColor>{`  ${s('workMore', { n: task.work.length - WORK_MAX })}`}</Text>}
640      </Box>
641    ) : (
642      // one block per team; each card a button (↑↓ moves, Enter opens its decision thread)
643      <Box flexDirection="column" marginBottom={1}>
644        {tv.teams.map(t => (
645          <Box key={`t-${t.team}`} flexDirection="column">
646            <Text bold>{teamWord(t.team)}</Text>
647            {t.cards.map(c => (
648              <Box key={`k-${c.id}`} flexDirection="column">
649                {/* one line per card: a narrow pane clips the label instead of wrapping it */}
650                <Box height={1} overflow="hidden"><Button key={`card:${c.id}`} plain dimColor={c.mark === 'done'}
651                  label={`${MARK[c.mark]} ${c.title} · ${c.state ?? ''}${c.now ? ` · ${nodeWord(c.now.node)} ${c.now.agent ?? ''} ${since(c.now.elapsed_ms)}`.trimEnd() : ''}`}
652                  onPress={() => pickCard(c.id)} /></Box>
653                {c.mark === 'failed' && reasonOf(c.title) && <Text color="error" wrap="truncate-end">{`  ${reasonOf(c.title)}`}</Text>}
654              </Box>
655            ))}
656          </Box>
657        ))}
658      </Box>
659    )
660
661    let body
662    if (kind === 'floor') {
663      body = floorLines
664    } else if (kind === 'stories') {
665      body = <Box flexDirection="column">{rail}{storiesBody}</Box>
666    } else if (kind === 'decisions') {
667      const pickedId = await read($, selected)
668      const dp = await read($, decisions)
669      const mine = dp !== null && dp.task_id === id && dp.card === pickedId ? dp.payload.entries : null
670      const what = (d: Decision) => {
671        const label = d.kind === 'verdict' ? s(VERDICT_WORD[d.verdict ?? ''] ?? 'vReject') : s(`kind${cap(d.kind)}` as keyof typeof en) || d.kind
672        const score = d.score !== null && d.score !== undefined ? ` ${d.score}%` : ''
673        const why = d.reason ?? d.text ?? d.title ?? ''
674        return `${d.time ?? '     '} ${d.actor ?? '—'} · ${label}${score} · ${d.node ?? d.card ?? ''}${why ? ` — ${why}` : ''}`
675      }
676      const subs = (d: Decision) => [
677        ...(d.blocking ?? []).map(x => `${s('lineBlocking')}: ${x}`),
678        ...(d.problems ?? []).map(x => `${s('lineProblems')}: ${x}`),
679        ...(d.gaps ?? []).map(x => `${s('lineGaps')}: ${x}`),
680        ...(d.evidence ? [`${s('lineEvidence')}: ${d.evidence}`] : []),
681      ]
682      body = (
683        <Box flexDirection="column">
684          {picker}
685          {pickedId !== null && (
686            <Box columnGap={2}>
687              <Text bold>{s('decCard', { c: pickedId })}</Text>
688              <Button key="all" plain label={s('decAll')} onPress={async () => {
689                await update($, selected, () => null)
690                await fetchDecisions($, id)
691              }} />
692            </Box>
693          )}
694          {mine === null ? <Text dimColor>{s('loading')}</Text>
695            : mine.length === 0 ? <Text dimColor>{s('decNone')}</Text>
696            : mine.map((d, i) => (
697              <Box key={`d${i}`} flexDirection="column">
698                <Text color={d.verdict === 'reject' || d.kind === 'defect' ? 'error' : d.kind === 'answer' || d.kind === 'decision' ? 'warning' : undefined} wrap="truncate-end">{what(d)}</Text>
699                {subs(d).map((line, j) => <Text key={`d${i}-${j}`} dimColor wrap="truncate-end">{`      ${line}`}</Text>)}
700              </Box>
701            ))}
702        </Box>
703      )
704    } else if (kind === 'log') {
705      const lines = task.log.map(one => `${one.time} ${s(`log${cap(one.kind)}` as keyof typeof en, { s: one.subject ?? '' }).trim()}`)
706      body = (
707        <Box flexDirection="column">
708          {lines.length === 0 ? <Text dimColor>{s('noLog')}</Text> : lines.map((line, i) => <Text key={`l${i}`}>{line}</Text>)}
709        </Box>
710      )
711    } else {
712      body = reportBody
713    }
714    return (
715      <Box flexDirection="column" borderStyle="round" borderColor="claude" paddingX={1}>
716        {/* the EPIC rows are the title; a task that is not listed gets one row of its own */}
717        {entry === undefined && (
718          <Box>
719            <Box flexShrink={1}><Text bold wrap="truncate-end">{task.title}</Text></Box>
720            <Box flexShrink={0} marginLeft={2}>
721              <Text color="claude">{s('headLine', { state: stateWord, done: task.done, total: task.total })}</Text>
722            </Box>
723          </Box>
724        )}
725        {epics !== null && <Box marginTop={entry === undefined ? 1 : 0}>{epics}</Box>}
726        {waitBox}
727        {/* the tab row never wraps: tabRowPlan drops the cost text first, then shortens the labels */}
728        <Box marginY={1}>
729          <Box flexShrink={0}>{tabs}</Box>
730          {tabPlan.cost !== null && (
731            <Box flexGrow={1} flexShrink={1} justifyContent="flex-end" marginLeft={2}>
732              <Text dimColor wrap="truncate-end">{tabPlan.cost}</Text>
733            </Box>
734          )}
735        </Box>
736        {body}
737        {footer}
738      </Box>
739    )
740  })
741
742  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
743    const info = await read($, status)
744    const task = await read($, summary)
745    const lang$ = await read($, lang)
746    const s = (key: keyof typeof en, vars?: Record<string, string | number>) => fmt(STRINGS[lang$][key], vars)
747    const open = () => $.ui.open(OPEN)
748
749    // an ended run: one card in place of the running row, until the person opens the report or dismisses it
750    const cardId = cardTask(await read($, ended))
751    const held = await read($, cardReport)
752    if (!e.props.hasSurvey && cardId !== undefined && held?.task_id === cardId && held.payload.verdict !== 'running') {
753      const { Box, Button, Text } = $.ui.resolve(e)
754      const p = held.payload
755      const set = (state: 'seen' | 'dismissed') => update($, ended, m => mark(m, cardId, state))
756      return (
757        <Box flexDirection="column">
758          <Box>
759            <Box flexShrink={0}><Text bold color={p.verdict === 'finished' ? 'success' : 'warning'}>{`teams · ${s(p.verdict === 'finished' ? 'cardFinished' : 'cardBlocked')}`}</Text></Box>
760            {p.failed > 0 && <Box flexShrink={0} marginLeft={1}><Text color="error">{s('cardFailed', { n: p.failed })}</Text></Box>}
761            {p.needs.items.length > 0 && <Box flexShrink={1} marginLeft={1}><Text dimColor wrap="truncate-end">{`— ${p.needs.items.join('; ')}`}</Text></Box>}
762            {p.needs.more > 0 && <Box flexShrink={0} marginLeft={1}><Text dimColor>{s('cardMore', { n: p.needs.more })}</Text></Box>}
763            {p.report !== null && (
764              <Box flexShrink={0} marginLeft={1}>
765                <Button key="report" label={s('reportButton')} onPress={async () => {
766                  await update($, watch, l => [...l.filter(x => x !== cardId), cardId])
767                  await update($, summary, () => null)
768                  await update($, report, () => held)
769                  await update($, view, () => 'report')
770                  await set('seen')
771                  await open()
772                }} />
773              </Box>
774            )}
775            <Box flexShrink={0} marginLeft={1}><Button key="dismiss" label={s('dismiss')} onPress={() => set('dismissed')} /></Box>
776          </Box>
777          {await next(e)}
778        </Box>
779      )
780    }
781
782    // a card waits on a person: ⚑ leads the row, with or without a running task
783    // status.asks is not cwd-scoped like waiting: a card from another repo's task can address this session
784    const flagged = (info?.waiting ?? 0) > 0 || (task?.you.count ?? 0) > 0 || (info?.asks?.length ?? 0) > 0
785    const isRunning = info?.latest != null && task?.state === 'running'
786    if (e.props.hasSurvey || (!flagged && !isRunning)) return next(e)
787    const { Box, Button, Text } = $.ui.resolve(e)
788    const inboxLabel = (n: number) => s(n === 1 ? 'inboxOne' : 'inboxMany', { n })
789    const flag = flagged ? <Box flexShrink={0} marginRight={1}><Text color="warning" bold>⚑</Text></Box> : null
790    // a card addressed to this session: its question leads the ⚑ row (node's status.asks, newest first)
791    const asks = info?.asks ?? []
792    const first = asks[0]
793    const asked = first === undefined ? null : (
794      // one row Box, not a fragment: the host lays fragment children out on their own line
795      <Box flexDirection="row" flexShrink={1} marginRight={1}>
796        <Box flexShrink={1}><Text color="warning" wrap="truncate-end">{s('asksYou', { who: first.who, q: first.question })}</Text></Box>
797        {asks.length > 1 && <Box flexShrink={0} marginLeft={1}><Text dimColor>{`+${asks.length - 1}`}</Text></Box>}
798      </Box>
799    )
800    if (task === null || !isRunning) {
801      return (
802        <Box flexDirection="column">
803          <Box>
804            {flag}
805            {asked}
806            <Box flexShrink={0}><Button key="inbox" label={inboxLabel(Math.max(info?.waiting ?? 0, task?.you.count ?? 0, asks.length))} onPress={open} /></Box>
807          </Box>
808          {await next(e)}
809        </Box>
810      )
811    }
812    return (
813      <Box flexDirection="column">
814        <Box>
815          {flag}
816          {asked}
817          <Box flexShrink={1}><Text dimColor wrap="truncate-end">{`teams · ${task.title} — ${nowSentence(s, task)}`}</Text></Box>
818          <Box flexShrink={0} marginLeft={1}>
819            <Text color="success">{'━'.repeat(task.total > 0 ? Math.round((10 * task.done) / task.total) : 0)}</Text>
820            <Text color="inactive">{'─'.repeat(10 - (task.total > 0 ? Math.round((10 * task.done) / task.total) : 0))}</Text>
821            <Text dimColor>{` ${s('bandDone', { done: task.done, total: task.total })}`}</Text>
822          </Box>
823          {Math.max(info?.waiting ?? 0, asks.length) > 0
824            ? <Box flexShrink={0} marginLeft={1}><Button key="inbox" label={inboxLabel(Math.max(info?.waiting ?? 0, asks.length))} onPress={open} /></Box>
825            : <Box flexShrink={0} marginLeft={1}><Button key="board" label={s('board')} onPress={open} /></Box>}
826        </Box>
827        {await next(e)}
828      </Box>
829    )
830  })
831
832  // react only: the result goes back unchanged; interactive sessions only
833  on('tool.call', { tool: /__(tm_open|tm_run)$/ }, async ($, e, next) => {
834    const r = await next(e)
835    if ((await $.session.surfaces()).length === 0) return r
836    if (r.deny !== undefined) return r
837    const id = taskIdOf(r)
838    if (id !== undefined) await update($, watch, list => (list.includes(id) ? list : [...list, id]))
839    return r
840  }).catch(($, e, next) => next(e))
841
842  // receiver: a peer's message that node reads as a teams ask is taken here and the data refreshed once
843  on('session.receive', { origin: { kind: 'peer' } }, async ($, e, next) => {
844    const r = await $.process.run(['node', `${$.plugin.root}/scripts/ask-message.mjs`, '--received', '--session', await $.session.id()], { stdin: e.text })
845    if (r.exitCode !== 0 || r.stdout.trim() === '') return next(e)
846    if (refresh !== null) await refresh()
847    return { consumed: 'teams ask' }
848  }).catch(($, e, next) => next(e))
849
850  // guard: runs headless too
851  on('tool.call', { tool: /__team_status$/ }, ($, e, next) => {
852    const args = e as unknown as { full?: unknown; node_id?: unknown }
853    if (args.full === true && !args.node_id) {
854      return { deny: 'team_status full:true dumps every node; pass node_id or read detail_path (teams:orchestrate NEVER rule)' }
855    }
856    return next(e)
857  }).catch(($, e, next) => next(e))
858}
859
hooks/pane.ts 85 lines
1/*
2 * Pure helpers of the teams pane: which key does what, how a step moves, where the selection goes when
3 * its task leaves the list. No engine, no drawing: mod.tsx reads state and calls these.
4 */
5
6export type PaneTabKey = 'floor' | 'stories' | 'decisions' | 'log' | 'report'
7const KEY_TABS: Record<string, PaneTabKey> = { '1': 'floor', '2': 'stories', '3': 'decisions', '4': 'log', '5': 'report' }
8
9// `[` / `]` step the EPIC, `j` / `k` the STORY row, `g` opens the row's run, `1`-`5` pick a tab, `q` closes. The pane's
10// Input holds the focus, so these keys reach it as text, never a Button hotkey. Text holding a `/` is a slash command
11// being typed (`/teams-status`): held, no key fires until submit (paneSlash). Any other text, none, or a non-string is no key.
12export type PaneKey =
13  | { kind: 'step'; by: 1 | -1 } | { kind: 'row'; by: 1 | -1 } | { kind: 'open' } | { kind: 'tab'; tab: PaneTabKey } | { kind: 'close' } | null
14
15export function paneKey(text: unknown): PaneKey {
16  if (typeof text !== 'string' || text === '' || text.includes('/')) return null
17  const k = [...text].pop()!
18  if (k === 'q') return { kind: 'close' }
19  const tab = KEY_TABS[k]
20  if (tab !== undefined) return { kind: 'tab', tab }
21  if (k === ']') return { kind: 'step', by: 1 }
22  if (k === '[') return { kind: 'step', by: -1 }
23  if (k === 'j') return { kind: 'row', by: 1 }
24  if (k === 'k') return { kind: 'row', by: -1 }
25  if (k === 'g') return { kind: 'open' }
26  return null
27}
28
29// A slash command typed into the pane's Input and submitted. The buffer may start with earlier key presses, so the
30// command starts at the first `/`. `/teams-status` closes the pane (the command again toggles); `/name args` runs that
31// command; anything else is dropped.
32export type PaneSlash = { kind: 'close' } | { kind: 'run'; command: string; args: string } | null
33
34export function paneSlash(text: unknown): PaneSlash {
35  if (typeof text !== 'string') return null
36  const at = text.indexOf('/')
37  if (at < 0) return null
38  const m = /^\/([^\s/]+)\s*(.*)$/.exec(text.slice(at).trim())
39  if (m === null) return null
40  return m[1] === 'teams-status' ? { kind: 'close' } : { kind: 'run', command: m[1]!, args: m[2]! }
41}
42
43// the surfaces that carry an Input; the others (mobile) keep the footer's Buttons only
44export function carriesInput(surface: string): boolean {
45  return surface === 'terminal' || surface === 'desktop' || surface === 'vscode'
46}
47
48// the text the command answers with: the run's stdout, else `opened` when the run failed or printed nothing
49export function statusAnswer(run: { exitCode: number; stdout: string } | null, opened: string): string {
50  return run === null || run.exitCode !== 0 || run.stdout.trim() === '' ? opened : run.stdout
51}
52
53// one step inside 0..count-1: it stops at the ends, never wraps
54export function stepClamp(index: number, by: number, count: number): number {
55  if (count <= 0) return 0
56  return Math.min(count - 1, Math.max(0, index + by))
57}
58
59// The selected id after a new list arrives. Still listed: it stays. Gone: the nearest id of the previous list that
60// is still listed (the later one first on a tie), else the first listed. Nothing selected yet: the first listed.
61export function fallbackSelection(previous: readonly string[], ids: readonly string[], selected: string | null): string | null {
62  if (ids.length === 0) return selected
63  if (selected !== null && ids.includes(selected)) return selected
64  const at = selected === null ? -1 : previous.indexOf(selected)
65  if (at >= 0) {
66    for (let d = 1; d < previous.length; d += 1) {
67      for (const i of [at + d, at - d]) {
68        const id = previous[i]
69        if (id !== undefined && ids.includes(id)) return id
70      }
71    }
72  }
73  return ids[0]!
74}
75
76// the ⚑ ask band is drawn while an ask is addressed to this session and no end-of-run card replaces it
77export function askBandShown(asks: readonly unknown[] | undefined, cardShown: boolean): boolean {
78  return (asks?.length ?? 0) > 0 && !cardShown
79}
80
81// the STORY rows of every listed task, in list order, each with the task it belongs to
82export function storyRows<T extends { items: readonly I[] }, I>(tasks: readonly T[]): { entry: T; item: I }[] {
83  return tasks.flatMap(entry => entry.items.map(item => ({ entry, item })))
84}
85
hooks/teams-draw.tsx 206 lines
1/*
2 * Teams-only drawing: icons and tints per state, text that is cut with `…`, columns that start at the same
3 * character on every row, and the one place lines of segments become Ink Text. Pure: every function takes
4 * strings and a width; mod.tsx decides what to show. Width is counted in display cells (Hangul, CJK and emoji
5 * take two; combining marks, ZWJ and variation selectors none; the icons and the spinner one).
6 */
7import type { Handoff, SummaryItem, SummaryTaskEntry, SummaryWorker, WorkState } from '../types'
8
9export type Tint = 'success' | 'claude' | 'inactive' | 'error' | 'warning'
10export type Seg = { t: string; tint?: Tint; dim?: boolean; bold?: boolean }
11export type Line = Seg[]
12// the resolved components from $.ui.resolve(e)
13export type Ui = { Box: any; Text: any }
14
15// display cells of one code point: wide glyphs 2, combining marks / ZWJ / variation selectors 0, the rest 1
16function cellsOf(ch: string): number {
17  const c = ch.codePointAt(0)!
18  if ((c >= 0x300 && c <= 0x36f) || c === 0x200d || (c >= 0xfe00 && c <= 0xfe0f)) return 0
19  if (
20    (c >= 0x1100 && c <= 0x115f) || (c >= 0x2e80 && c <= 0xa4cf) || (c >= 0xac00 && c <= 0xd7a3) || (c >= 0xf900 && c <= 0xfaff) ||
21    (c >= 0xfe30 && c <= 0xfe6f) || (c >= 0xff00 && c <= 0xff60) || (c >= 0xffe0 && c <= 0xffe6) || (c >= 0x1f300 && c <= 0x1faff)
22  ) return 2
23  return 1
24}
25
26export const width = (s: string) => Array.from(s).reduce((n, ch) => n + cellsOf(ch), 0)
27export const padText = (s: string, w: number) => s + ' '.repeat(Math.max(0, w - width(s)))
28
29// cut to w display cells; the cut ends in … and never splits a glyph (a mark or a ZWJ join stays with its base)
30export function clipText(s: string, w: number): string {
31  if (width(s) <= w) return s
32  if (w <= 0) return ''
33  const clusters: string[] = []
34  let joined = false
35  for (const ch of Array.from(s)) {
36    if (clusters.length > 0 && (cellsOf(ch) === 0 || joined)) clusters[clusters.length - 1] += ch
37    else clusters.push(ch)
38    joined = ch === '‍'
39  }
40  let out = ''
41  let used = 0
42  for (const cl of clusters) {
43    const n = width(cl)
44    if (used + n > w - 1) break
45    out += cl
46    used += n
47  }
48  return `${out.trimEnd()}…`
49}
50
51/* --- icons and tints: one glyph and one colour per state, no faces --- */
52
53export const ICON: Record<WorkState | 'failed', string> = { acting: '●', idle: '◌', you: '⚑', done: '✔', stalled: '⊘', failed: '✘' }
54export const TINT: Record<WorkState | 'failed', Tint> = { acting: 'claude', idle: 'inactive', you: 'warning', done: 'success', stalled: 'inactive', failed: 'error' }
55
56// the EPIC list: ● running, ⚑ waits on a person, ⊘ stalled
57export const epicState = (t: Pick<SummaryTaskEntry, 'live' | 'state'>): WorkState => (t.state === 'waiting_human' ? 'you' : t.live ? 'acting' : 'stalled')
58
59/* --- numbers and words in a cell --- */
60
61// 35s, 4m, 1h 2m; null is blank
62export function since(ms: number | null): string {
63  if (ms === null) return ''
64  const m = Math.floor(ms / 60000)
65  return ms < 60000 ? `${Math.floor(ms / 1000)}s` : m < 60 ? `${m}m` : `${Math.floor(m / 60)}h ${m % 60}m`
66}
67
68// `$0.42`, `~$0.42` when estimated, blank when unknown
69export const costText = (usd: number | null, estimated: boolean) => (usd === null ? '' : `${estimated ? '~' : ''}$${usd.toFixed(2)}`)
70
71// `2/3`; a known try with no limit is `2/-`; neither is blank
72export const tryText = (n: number | null, max: number | null) => (n === null ? '' : `${n}/${max ?? '-'}`)
73
74/* --- columns --- */
75
76// Widths of the columns of `rows` so that they, with `gap` between the non-empty ones, fit `total`. A column with no
77// text takes no room. Columns give way in `shrink` order, each down to `min`; whatever is left over is cut by the caller.
78// With a `drop` list, a row still too wide after shrinking loses the next listed column whole (width 0, its gap goes with
79// it) and shrinks again with the freed room; the first shrink column (the title) keeps `titleMin` until every drop is
80// spent, and only then gives way toward `min`. A column cut to 1 cell would be a bare … and becomes 0.
81export function columnWidths(
82  rows: readonly (readonly string[])[], total: number, gap: number, shrink: readonly number[], min = 4,
83  drop: readonly number[] = [], titleMin = min,
84): number[] {
85  const count = rows.reduce((n, r) => Math.max(n, r.length), 0)
86  const natural = Array.from({ length: count }, (_, c) => rows.reduce((n, r) => Math.max(n, width(r[c] ?? '')), 0))
87  const plan = (dropped: number, titleFloor: number): number[] => {
88    const widths = [...natural]
89    for (const c of drop.slice(0, dropped)) if (c < widths.length) widths[c] = 0
90    const spent = () => widths.reduce((n, w) => n + w, 0) + gap * Math.max(0, widths.filter(w => w > 0).length - 1)
91    shrink.forEach((c, i) => {
92      const over = spent() - total
93      if (over <= 0) return
94      const w = widths[c]
95      const floor = i === 0 ? titleFloor : min
96      if (w !== undefined && w > floor) widths[c] = Math.max(floor, w - over)
97    })
98    return widths
99  }
100  const fits = (ws: readonly number[]) => ws.reduce((n, w) => n + w, 0) + gap * Math.max(0, ws.filter(w => w > 0).length - 1) <= total
101  let widths = plan(0, titleMin)
102  for (let k = 1; k <= drop.length && !fits(widths); k++) widths = plan(k, titleMin)
103  if (!fits(widths)) widths = plan(drop.length, min)
104  return widths.map((w, c) => (w === 1 && (natural[c] ?? 0) > 1 ? 0 : w))
105}
106
107// one row cut and padded to its column widths; `tints` colour a column, the rest is plain
108export function rowLine(cells: readonly string[], widths: readonly number[], gap: number, tints: readonly (Tint | 'dim' | undefined)[] = []): Line {
109  const out: Line = []
110  widths.forEach((w, c) => {
111    if (w <= 0) return
112    if (out.length > 0) out.push({ t: ' '.repeat(gap) })
113    const tint = tints[c]
114    out.push({ t: padText(clipText(cells[c] ?? '', w), w), tint: tint === 'dim' ? undefined : tint, dim: tint === 'dim' })
115  })
116  return out
117}
118
119export const plain = (l: Line) => l.map(s => s.t).join('')
120
121// the one place Ink is touched: lines of segments as Text; a line wider than the pane is cut by the pane
122export function renderLines(ui: Ui, lines: readonly Line[], keyOf = 'l') {
123  const { Box, Text } = ui
124  return (
125    <Box flexDirection="column">
126      {lines.map((l, i) => (
127        <Text key={`${keyOf}${i}`} wrap="truncate-end">
128          {l.length === 0 ? ' ' : l.map((s, j) => <Text key={j} color={s.tint} bold={s.bold} dimColor={s.dim}>{s.t}</Text>)}
129        </Text>
130      ))}
131    </Box>
132  )
133}
134
135/* --- the Floor: worker lines and the hand-off feed --- */
136
137export const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] as const
138
139// icon · spinner (acting only) · worker · word (node's icon and word; `fixed` localizes a fixed word by its word_key)
140export function workerCells(workers: readonly SummaryWorker[], frameNo: number, fixed: (key: string) => string): StoryCells[] {
141  return workers.map(w => ({
142    cells: [w.icon, w.state === 'acting' ? SPINNER[frameNo % SPINNER.length]! : '', w.id, w.word_key ? fixed(w.word_key) : w.word],
143    tints: [TINT[w.state], TINT[w.state], undefined, 'dim'],
144  }))
145}
146
147// time · who · what · to whom
148export const handoffCells = (feed: readonly Handoff[]): string[][] => feed.slice(0, 5).map(h => [h.time, h.from, h.what, h.to ? `→ ${h.to}` : ''])
149
150/* --- the STORY rows --- */
151
152export type StoryCells = { cells: string[]; tints: (Tint | 'dim' | undefined)[] }
153
154// icon · title · doing · verdict · try/max · elapsed · cost · harness (an S task's stages and run)
155export function storyCells(item: SummaryItem, verdict: string, harness: string, selected: boolean, fixed: (key: string) => string): StoryCells {
156  return {
157    cells: [
158      selected ? '▸' : '', item.icon, item.title, item.word_key ? fixed(item.word_key) : item.word, verdict, tryText(item.try, item.max),
159      since(item.elapsed_ms), costText(item.cost_usd, item.cost_estimated), harness,
160    ],
161    tints: [undefined, TINT[item.state], undefined, undefined, undefined, 'dim', 'dim', 'dim', 'dim'],
162  }
163}
164// the harness text gives way first, then doing, then the title
165export const STORY_SHRINK = [8, 3, 2] as const
166
167// The EPIC row is the title block: marker · icon · key · title · state word · done/total · age. The slug is not a pane
168// column (the Report header and view.mjs show it). A live task's age runs
169// from its creation, a stalled one's is how long it has stood; a stalled row is dim throughout.
170export function epicCells(t: SummaryTaskEntry, state: WorkState, selected: boolean, now: number, stateWord: string): StoryCells {
171  const cells = [
172    selected ? '▸' : '', ICON[state], t.key, t.title, stateWord, `${t.done}/${t.total}`,
173    since(t.live ? (t.created_at === null ? null : Math.max(0, now - t.created_at)) : t.age_ms),
174  ]
175  return { cells, tints: t.live ? [undefined, TINT[state], undefined, undefined, 'dim', undefined, 'dim'] : cells.map(() => 'dim' as const) }
176}
177
178/* --- the tab row and the footer, planned against the pane's inner width --- */
179
180// The tab row on one line of `inner` columns. The cost text goes first (shown only when tabs and cost fit), then the
181// gap between tabs closes from 2 to 1, then the longest label is cut with … until the row fits.
182export function tabRowPlan(labels: readonly string[], cost: string, inner: number): { labels: string[]; gap: number; cost: string | null } {
183  const total = (ls: readonly string[], gap: number) => ls.reduce((n, l) => n + width(l), 0) + gap * Math.max(0, ls.length - 1)
184  if (cost !== '' && total(labels, 2) + 2 + width(cost) <= inner) return { labels: [...labels], gap: 2, cost }
185  if (total(labels, 2) <= inner) return { labels: [...labels], gap: 2, cost: null }
186  const out = [...labels]
187  while (total(out, 1) > inner) {
188    let at = 0
189    out.forEach((l, i) => { if (width(l) > width(out[at]!)) at = i })
190    if (width(out[at]!) <= 4) break
191    out[at] = clipText(labels[at]!, width(out[at]!) - 1)
192  }
193  return { labels: out, gap: 1, cost: null }
194}
195
196// The Input draws its own `⏎ submit` (9 columns and a gap) beside the hint while focused.
197const INPUT_CHROME = 10
198
199// The footer on one line: close stays whole; prev/next and the open hint stay when they fit; the key hint takes what is
200// left and ends in … when cut, or is dropped when under 6 columns remain.
201export function footerPlan(parts: { steps: number; open: string; close: string; hint: string }, inner: number): { hint: string } {
202  const fixed = [parts.steps > 0 ? parts.steps + 2 * (parts.steps - 1) : 0, width(parts.open), width(parts.close)].filter(n => n > 0)
203  const room = inner - INPUT_CHROME - fixed.reduce((n, w) => n + w, 0) - 2 * fixed.length
204  return { hint: room >= 6 ? clipText(parts.hint, room) : '' }
205}
206
types/index.d.ts 106 lines
1// `state` is the daemon's final state on a daemon_done line (complete, partial, blocked, ...)
2export type TeamsEvent = { ts: number; task_id: string; kind: string; text: string; state?: string; package?: string; attempt?: number }
3
4// `view.mjs --once --format status`: the one-line status of this cwd
5// a question waiting on one interactive session (lib/view-asks.mjs asksFor); `via` is 'send' once the driver's message arrived
6export type AskNotice = { task_id: string; key: string; who: string; question: string; since: number | null; via: 'send' | 'poll' }
7export type StatusInfo = { line: string; waiting: number; latest?: string | null; asks?: AskNotice[] }
8
9// `view.mjs --once --format summary` task part (teams/scripts/lib/view-summary.mjs)
10export type Mark = 'done' | 'running' | 'pending' | 'failed'
11export type SummaryTask = {
12  key: string
13  slug: string | null
14  title: string
15  state: string
16  day: number
17  done: number
18  total: number
19  now: { kind: string; subject: string | null; detail: string | null }
20  you: { count: number; items: string[]; cards?: { key: string; title: string; question: string; who: string; since: number | null }[] }
21  stages: { key: string; state: Mark }[]
22  work: { title: string; kind: string; id: string | null; state: Mark; filed_by: string | null; reason: string | null }[]
23  cost: { usd: number; turns: number }
24  log: { time: string; kind: string; subject: string | null }[]
25}
26
27// `view.mjs --once --format summary` floor part (teams/scripts/lib/view-floor.mjs): per listed task
28export type WorkState = 'acting' | 'idle' | 'you' | 'done' | 'stalled'
29export type SummaryItem = {
30  key: string; title: string; state: WorkState | 'failed'; doing: string; icon: string; word: string; word_key: string; last_verdict: string | null
31  cost_usd: number | null; cost_estimated: boolean; try: number | null; max: number | null
32  live: boolean; elapsed_ms: number | null; run_file: string | null; owner_key: string
33}
34// icon, word, word_key: node's one state -> mark (view-floor.mjs markOf); word_key is '' for a live word, else the state to localize
35export type SummaryWorker = { id: string; state: WorkState; doing: string; icon: string; word: string; word_key: string }
36export type Handoff = { time: string; from: string; what: string; to: string }
37export type SummaryTaskEntry = SummaryTask & {
38  task_id: string; created_at: number | null
39  live: boolean; age_ms: number | null // age_ms: stalled tasks only, under 24 h
40  items: SummaryItem[]; workers: SummaryWorker[]; handoffs: Handoff[]
41  // an S task's harness run (slug, moved lately); null for a package EPIC
42  harness: { slug: string | null; moving: boolean } | null
43}
44// `task` (the running task, or --task) stays as before; `tasks` is live newest-created first, then stalled
45export type SummaryOutput = { status: StatusInfo; tasks: SummaryTaskEntry[]; task: SummaryTask | null }
46
47// the pane's tabs, in key order
48export type PaneView = 'floor' | 'stories' | 'decisions' | 'log' | 'report'
49
50// `view.mjs --once --format teams` teams part (teams/scripts/lib/view-status.mjs teamsView)
51export type NowLine = { team: string; key: string; node: string; agent: string | null; elapsed_ms: number | null }
52export type TeamsView = {
53  now: NowLine[]
54  teams: { team: string; cards: { id: string; key: string; title: string; state: string | null; mark: Mark; now: { node: string; agent: string | null; elapsed_ms: number | null } | null }[] }[]
55}
56
57// `view.mjs --once --format decisions --task <id> [--card <id>]` (view-status.mjs decisionsView)
58export type Decision = {
59  ts: number | null; time: string | null; card: string | null; node: string | null; kind: string
60  actor?: string | null; verdict?: string | null; score?: number | null; reason?: string | null; text?: string | null
61  blocking?: string[]; problems?: string[]; gaps?: string[]; title?: string; evidence?: string | null; filed_by?: string | null
62}
63export type DecisionsPayload = { card: string | null; entries: Decision[] }
64
65// `view.mjs --once --format report --task <id>` (teams/scripts/lib/view-report.mjs)
66export type ReportPayload = {
67  task_id: string
68  verdict: 'finished' | 'blocked' | 'running'
69  failed: number
70  needs: { items: string[]; more: number }
71  path: string
72  report: { text: string; truncated: boolean; more_lines: number; mtime: number } | null
73  retro: object | null
74}
75
76declare module 'claude-code' {
77  interface PluginState {
78    teams: {
79      cursor: number
80      watch: string[]
81      status: StatusInfo | null
82      summary: SummaryTask | null
83      view: PaneView
84      // every listed EPIC (live first, then stalled), as the last tick saw them, and the ids of the tick before
85      tasks: SummaryTaskEntry[]
86      taskIds: string[]
87      // the EPIC the pane shows (task_id); null until the first list arrives
88      epic: string | null
89      // the STORYs tab: the row `g` opens and `j`/`k` move, an index into every listed task's rows
90      row: number
91      // the Floor spinner frame, advanced every ~800 ms while a worker acts
92      frame: number
93      teams: TeamsView | null
94      // the Decisions tab: fetched for one task, and one card when one was picked
95      decisions: { task_id: string; card: string | null; payload: DecisionsPayload } | null
96      selected: string | null
97      report: { task_id: string; payload: ReportPayload } | null
98      cardReport: { task_id: string; payload: ReportPayload } | null
99      ended: Record<string, 'card' | 'seen' | 'dismissed'>
100      lang: 'en' | 'ko'
101      // the run outcome this mod publishes for trophy: labels only, never an id (same type in graph and harness)
102      outcome: { system: 'graph' | 'teams' | 'harness'; outcome: 'pass' | 'reject' | 'fail'; at: number } | null
103    }
104  }
105}
106