Merge build/105-hints-and-generation: read-only contracts are listed as read-only, and docs/reference is generated
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents d3416aa, 835c8dd · Browse files · 12 files·+2903 added−32 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+2903 added−32 removed
- tests:+491 added−3 removed
- other:+2412 added−29 removed
Provenance
- Commit
e30ceed- Tree
435efdd- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
d3416aa- Parent 2
835c8dd
12 files changed+2903 added−32 removed
added:docs/reference/cli.md+45 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445<!-- Generated by `bun run gen` from packages/protocol/src/contracts.ts through commands.json. Edit the contracts, not this file: `bun run gen:check` fails when they differ. -->
# CLI
Each command below is a contract projected onto the `myr` CLI: the payload's fields become flags, or positional arguments where the contract names them. Every command also takes `--json`, which prints the encoded result, or the refusal, as JSON. [commands.json](commands.json) holds the same catalog as data.
## `myr asks`
List a project's open asks.
```shmyr asks --project <project>```
- Contract: `listAsks`- Reads only: yes- Idempotent: yes- Destructive: no- Needs approval: no- Surfaces: rpc, mcp, cli, web
| Argument | Takes | Required || --- | --- | --- || `--project` | text | yes |
## `myr submit`
Offer the commit `head`, built on `base`, as an answer to an ask; once it lands, `main` is the new tip.
```shmyr submit --ask <ask> --base <base> --head <head>```
- Contract: `submitAnswer`- Reads only: no- Idempotent: yes- Destructive: no- Needs approval: no- Surfaces: rpc, mcp, cli, web
| Argument | Takes | Required || --- | --- | --- || `--ask` | text | yes || `--base` | text | yes || `--head` | text | yes |added:docs/reference/commands.json+81 added
1+{2+ "commands": [3+ {4+ "contract": "listAsks",5+ "description": "List a project's open asks.",6+ "destructive": false,7+ "idempotent": true,8+ "name": "asks",9+ "needsApproval": false,10+ "path": [11+ "asks"12+ ],13+ "payloadSchema": {14+ "additionalProperties": true,15+ "properties": {16+ "project": {17+ "pattern": "^[a-z0-9][a-z0-9-]*$",18+ "type": "string"19+ }20+ },21+ "required": [22+ "project"23+ ],24+ "type": "object"25+ },26+ "positional": [],27+ "readOnly": true,28+ "source": "projected",29+ "surfaces": [30+ "rpc",31+ "mcp",32+ "cli",33+ "web"34+ ]35+ },36+ {37+ "contract": "submitAnswer",38+ "description": "Offer the commit `head`, built on `base`, as an answer to an ask; once it lands, `main` is the new tip.",39+ "destructive": false,40+ "idempotent": true,41+ "name": "submit",42+ "needsApproval": false,43+ "path": [44+ "submit"45+ ],46+ "payloadSchema": {47+ "additionalProperties": true,48+ "properties": {49+ "ask": {50+ "pattern": "^[a-z0-9][a-z0-9-]*$",51+ "type": "string"52+ },53+ "base": {54+ "pattern": "^[0-9a-f]{40}$",55+ "type": "string"56+ },57+ "head": {58+ "pattern": "^[0-9a-f]{40}$",59+ "type": "string"60+ }61+ },62+ "required": [63+ "ask",64+ "base",65+ "head"66+ ],67+ "type": "object"68+ },69+ "positional": [],70+ "readOnly": false,71+ "source": "projected",72+ "surfaces": [73+ "rpc",74+ "mcp",75+ "cli",76+ "web"77+ ]78+ }79+ ],80+ "version": 181+}added:docs/reference/mcp-tools.md+137 added
1+<!-- Generated by `bun run gen` from packages/protocol/src/contracts.ts through `toToolkit` in packages/protocol/src/mcp.ts. Edit the contracts, not this file: `bun run gen:check` fails when they differ. -->2+3+# MCP tools4+5+Each contract is one MCP tool, named by its tag, as `tools/list` shows it over `/mcp` and over stdio from `myr mcp`. A tool's input is the contract's payload and its output is the contract's success. A refusal comes back as the tool's error result: the refusal as JSON, `_tag` and all (see [refusals.md](refusals.md)).6+7+The hints come from each contract's own annotations. No tool reaches anything outside the platform, so `openWorldHint` is always false.8+9+## listAsks10+11+List a project's open asks.12+13+| Hint | Value |14+| --- | --- |15+| `destructiveHint` | `false` |16+| `idempotentHint` | `true` |17+| `openWorldHint` | `false` |18+| `readOnlyHint` | `true` |19+20+### Input21+22+```json23+{24+ "additionalProperties": true,25+ "properties": {26+ "project": {27+ "pattern": "^[a-z0-9][a-z0-9-]*$",28+ "type": "string"29+ }30+ },31+ "required": [32+ "project"33+ ],34+ "type": "object"35+}36+```37+38+### Output39+40+```json41+{42+ "additionalProperties": true,43+ "properties": {44+ "asks": {45+ "items": {46+ "additionalProperties": true,47+ "properties": {48+ "ask": {49+ "pattern": "^[a-z0-9][a-z0-9-]*$",50+ "type": "string"51+ },52+ "claimed": {53+ "type": "boolean"54+ },55+ "territory": {56+ "minLength": 1,57+ "type": "string"58+ },59+ "want": {60+ "minLength": 1,61+ "type": "string"62+ }63+ },64+ "required": [65+ "ask",66+ "claimed",67+ "territory",68+ "want"69+ ],70+ "type": "object"71+ },72+ "type": "array"73+ }74+ },75+ "required": [76+ "asks"77+ ],78+ "type": "object"79+}80+```81+82+## submitAnswer83+84+Offer the commit `head`, built on `base`, as an answer to an ask; once it lands, `main` is the new tip.85+86+| Hint | Value |87+| --- | --- |88+| `destructiveHint` | `false` |89+| `idempotentHint` | `true` |90+| `openWorldHint` | `false` |91+| `readOnlyHint` | `false` |92+93+### Input94+95+```json96+{97+ "additionalProperties": true,98+ "properties": {99+ "ask": {100+ "pattern": "^[a-z0-9][a-z0-9-]*$",101+ "type": "string"102+ },103+ "base": {104+ "pattern": "^[0-9a-f]{40}$",105+ "type": "string"106+ },107+ "head": {108+ "pattern": "^[0-9a-f]{40}$",109+ "type": "string"110+ }111+ },112+ "required": [113+ "ask",114+ "base",115+ "head"116+ ],117+ "type": "object"118+}119+```120+121+### Output122+123+```json124+{125+ "additionalProperties": true,126+ "properties": {127+ "main": {128+ "pattern": "^[0-9a-f]{40}$",129+ "type": "string"130+ }131+ },132+ "required": [133+ "main"134+ ],135+ "type": "object"136+}137+```added:docs/reference/protocol.schema.json+1456 added
1+{2+ "$comment": "Generated by `bun run gen` from packages/protocol. Edit the contracts, not this file.",3+ "$defs": {4+ "AskFullEncoded": {5+ "additionalProperties": true,6+ "properties": {7+ "_tag": {8+ "enum": [9+ "AskFull"10+ ],11+ "type": "string"12+ },13+ "ask": {14+ "pattern": "^[a-z0-9][a-z0-9-]*$",15+ "type": "string"16+ },17+ "at": {18+ "additionalProperties": true,19+ "properties": {20+ "line": {21+ "minimum": 1,22+ "type": "integer"23+ },24+ "path": {25+ "minLength": 1,26+ "type": "string"27+ }28+ },29+ "required": [30+ "line",31+ "path"32+ ],33+ "type": "object"34+ },35+ "next": {36+ "minLength": 1,37+ "type": "string"38+ },39+ "retryable": {40+ "enum": [41+ true42+ ],43+ "type": "boolean"44+ }45+ },46+ "required": [47+ "_tag",48+ "next",49+ "retryable",50+ "ask"51+ ],52+ "type": "object"53+ },54+ "AttemptsExhaustedEncoded": {55+ "additionalProperties": true,56+ "properties": {57+ "_tag": {58+ "enum": [59+ "AttemptsExhausted"60+ ],61+ "type": "string"62+ },63+ "area": {64+ "minLength": 1,65+ "type": "string"66+ },67+ "at": {68+ "additionalProperties": true,69+ "properties": {70+ "line": {71+ "minimum": 1,72+ "type": "integer"73+ },74+ "path": {75+ "minLength": 1,76+ "type": "string"77+ }78+ },79+ "required": [80+ "line",81+ "path"82+ ],83+ "type": "object"84+ },85+ "next": {86+ "minLength": 1,87+ "type": "string"88+ },89+ "resetsAt": {90+ "type": "string"91+ },92+ "retryable": {93+ "enum": [94+ true95+ ],96+ "type": "boolean"97+ }98+ },99+ "required": [100+ "_tag",101+ "next",102+ "retryable",103+ "area",104+ "resetsAt"105+ ],106+ "type": "object"107+ },108+ "CapReachedEncoded": {109+ "additionalProperties": true,110+ "properties": {111+ "_tag": {112+ "enum": [113+ "CapReached"114+ ],115+ "type": "string"116+ },117+ "at": {118+ "additionalProperties": true,119+ "properties": {120+ "line": {121+ "minimum": 1,122+ "type": "integer"123+ },124+ "path": {125+ "minLength": 1,126+ "type": "string"127+ }128+ },129+ "required": [130+ "line",131+ "path"132+ ],133+ "type": "object"134+ },135+ "cap": {136+ "type": "integer"137+ },138+ "next": {139+ "minLength": 1,140+ "type": "string"141+ },142+ "retryable": {143+ "enum": [144+ true145+ ],146+ "type": "boolean"147+ }148+ },149+ "required": [150+ "_tag",151+ "next",152+ "retryable",153+ "cap"154+ ],155+ "type": "object"156+ },157+ "ChecksFailedEncoded": {158+ "additionalProperties": true,159+ "properties": {160+ "_tag": {161+ "enum": [162+ "ChecksFailed"163+ ],164+ "type": "string"165+ },166+ "at": {167+ "additionalProperties": true,168+ "properties": {169+ "line": {170+ "minimum": 1,171+ "type": "integer"172+ },173+ "path": {174+ "minLength": 1,175+ "type": "string"176+ }177+ },178+ "required": [179+ "line",180+ "path"181+ ],182+ "type": "object"183+ },184+ "lane": {185+ "minLength": 1,186+ "type": "string"187+ },188+ "logRef": {189+ "minLength": 1,190+ "type": "string"191+ },192+ "next": {193+ "minLength": 1,194+ "type": "string"195+ },196+ "retryable": {197+ "enum": [198+ false199+ ],200+ "type": "boolean"201+ }202+ },203+ "required": [204+ "_tag",205+ "next",206+ "retryable",207+ "lane",208+ "logRef"209+ ],210+ "type": "object"211+ },212+ "ClaimLapsedEncoded": {213+ "additionalProperties": true,214+ "properties": {215+ "_tag": {216+ "enum": [217+ "ClaimLapsed"218+ ],219+ "type": "string"220+ },221+ "ask": {222+ "pattern": "^[a-z0-9][a-z0-9-]*$",223+ "type": "string"224+ },225+ "at": {226+ "additionalProperties": true,227+ "properties": {228+ "line": {229+ "minimum": 1,230+ "type": "integer"231+ },232+ "path": {233+ "minLength": 1,234+ "type": "string"235+ }236+ },237+ "required": [238+ "line",239+ "path"240+ ],241+ "type": "object"242+ },243+ "next": {244+ "minLength": 1,245+ "type": "string"246+ },247+ "retryable": {248+ "enum": [249+ true250+ ],251+ "type": "boolean"252+ }253+ },254+ "required": [255+ "_tag",256+ "next",257+ "retryable",258+ "ask"259+ ],260+ "type": "object"261+ },262+ "FlakeEncoded": {263+ "additionalProperties": true,264+ "properties": {265+ "_tag": {266+ "enum": [267+ "Flake"268+ ],269+ "type": "string"270+ },271+ "at": {272+ "additionalProperties": true,273+ "properties": {274+ "line": {275+ "minimum": 1,276+ "type": "integer"277+ },278+ "path": {279+ "minLength": 1,280+ "type": "string"281+ }282+ },283+ "required": [284+ "line",285+ "path"286+ ],287+ "type": "object"288+ },289+ "lane": {290+ "minLength": 1,291+ "type": "string"292+ },293+ "next": {294+ "minLength": 1,295+ "type": "string"296+ },297+ "retryable": {298+ "enum": [299+ true300+ ],301+ "type": "boolean"302+ }303+ },304+ "required": [305+ "_tag",306+ "next",307+ "retryable",308+ "lane"309+ ],310+ "type": "object"311+ },312+ "HeldBackFailedEncoded": {313+ "additionalProperties": true,314+ "properties": {315+ "_tag": {316+ "enum": [317+ "HeldBackFailed"318+ ],319+ "type": "string"320+ },321+ "area": {322+ "minLength": 1,323+ "type": "string"324+ },325+ "at": {326+ "additionalProperties": true,327+ "properties": {328+ "line": {329+ "minimum": 1,330+ "type": "integer"331+ },332+ "path": {333+ "minLength": 1,334+ "type": "string"335+ }336+ },337+ "required": [338+ "line",339+ "path"340+ ],341+ "type": "object"342+ },343+ "next": {344+ "minLength": 1,345+ "type": "string"346+ },347+ "retryable": {348+ "enum": [349+ false350+ ],351+ "type": "boolean"352+ },353+ "suite": {354+ "minLength": 1,355+ "type": "string"356+ }357+ },358+ "required": [359+ "_tag",360+ "next",361+ "retryable",362+ "area",363+ "suite"364+ ],365+ "type": "object"366+ },367+ "IncompleteBriefEncoded": {368+ "additionalProperties": true,369+ "properties": {370+ "_tag": {371+ "enum": [372+ "IncompleteBrief"373+ ],374+ "type": "string"375+ },376+ "at": {377+ "additionalProperties": true,378+ "properties": {379+ "line": {380+ "minimum": 1,381+ "type": "integer"382+ },383+ "path": {384+ "minLength": 1,385+ "type": "string"386+ }387+ },388+ "required": [389+ "line",390+ "path"391+ ],392+ "type": "object"393+ },394+ "missing": {395+ "items": {396+ "minLength": 1,397+ "type": "string"398+ },399+ "minItems": 1,400+ "prefixItems": [401+ {402+ "minLength": 1,403+ "type": "string"404+ }405+ ],406+ "type": "array"407+ },408+ "next": {409+ "minLength": 1,410+ "type": "string"411+ },412+ "retryable": {413+ "enum": [414+ false415+ ],416+ "type": "boolean"417+ }418+ },419+ "required": [420+ "_tag",421+ "next",422+ "retryable",423+ "missing"424+ ],425+ "type": "object"426+ },427+ "LayerContentInPublicTreeEncoded": {428+ "additionalProperties": true,429+ "properties": {430+ "_tag": {431+ "enum": [432+ "LayerContentInPublicTree"433+ ],434+ "type": "string"435+ },436+ "at": {437+ "additionalProperties": true,438+ "properties": {439+ "line": {440+ "minimum": 1,441+ "type": "integer"442+ },443+ "path": {444+ "minLength": 1,445+ "type": "string"446+ }447+ },448+ "required": [449+ "line",450+ "path"451+ ],452+ "type": "object"453+ },454+ "next": {455+ "minLength": 1,456+ "type": "string"457+ },458+ "paths": {459+ "items": {460+ "minLength": 1,461+ "type": "string"462+ },463+ "minItems": 1,464+ "prefixItems": [465+ {466+ "minLength": 1,467+ "type": "string"468+ }469+ ],470+ "type": "array"471+ },472+ "retryable": {473+ "enum": [474+ false475+ ],476+ "type": "boolean"477+ }478+ },479+ "required": [480+ "_tag",481+ "next",482+ "retryable",483+ "paths"484+ ],485+ "type": "object"486+ },487+ "NoAskEncoded": {488+ "additionalProperties": true,489+ "properties": {490+ "_tag": {491+ "enum": [492+ "NoAsk"493+ ],494+ "type": "string"495+ },496+ "at": {497+ "additionalProperties": true,498+ "properties": {499+ "line": {500+ "minimum": 1,501+ "type": "integer"502+ },503+ "path": {504+ "minLength": 1,505+ "type": "string"506+ }507+ },508+ "required": [509+ "line",510+ "path"511+ ],512+ "type": "object"513+ },514+ "next": {515+ "minLength": 1,516+ "type": "string"517+ },518+ "retryable": {519+ "enum": [520+ false521+ ],522+ "type": "boolean"523+ }524+ },525+ "required": [526+ "_tag",527+ "next",528+ "retryable"529+ ],530+ "type": "object"531+ },532+ "NotClaimedEncoded": {533+ "additionalProperties": true,534+ "properties": {535+ "_tag": {536+ "enum": [537+ "NotClaimed"538+ ],539+ "type": "string"540+ },541+ "ask": {542+ "pattern": "^[a-z0-9][a-z0-9-]*$",543+ "type": "string"544+ },545+ "at": {546+ "additionalProperties": true,547+ "properties": {548+ "line": {549+ "minimum": 1,550+ "type": "integer"551+ },552+ "path": {553+ "minLength": 1,554+ "type": "string"555+ }556+ },557+ "required": [558+ "line",559+ "path"560+ ],561+ "type": "object"562+ },563+ "next": {564+ "minLength": 1,565+ "type": "string"566+ },567+ "retryable": {568+ "enum": [569+ true570+ ],571+ "type": "boolean"572+ }573+ },574+ "required": [575+ "_tag",576+ "next",577+ "retryable",578+ "ask"579+ ],580+ "type": "object"581+ },582+ "NotRedFirstEncoded": {583+ "additionalProperties": true,584+ "properties": {585+ "_tag": {586+ "enum": [587+ "NotRedFirst"588+ ],589+ "type": "string"590+ },591+ "at": {592+ "additionalProperties": true,593+ "properties": {594+ "line": {595+ "minimum": 1,596+ "type": "integer"597+ },598+ "path": {599+ "minLength": 1,600+ "type": "string"601+ }602+ },603+ "required": [604+ "line",605+ "path"606+ ],607+ "type": "object"608+ },609+ "next": {610+ "minLength": 1,611+ "type": "string"612+ },613+ "retryable": {614+ "enum": [615+ false616+ ],617+ "type": "boolean"618+ }619+ },620+ "required": [621+ "_tag",622+ "next",623+ "retryable"624+ ],625+ "type": "object"626+ },627+ "NotVouchedEncoded": {628+ "additionalProperties": true,629+ "properties": {630+ "_tag": {631+ "enum": [632+ "NotVouched"633+ ],634+ "type": "string"635+ },636+ "at": {637+ "additionalProperties": true,638+ "properties": {639+ "line": {640+ "minimum": 1,641+ "type": "integer"642+ },643+ "path": {644+ "minLength": 1,645+ "type": "string"646+ }647+ },648+ "required": [649+ "line",650+ "path"651+ ],652+ "type": "object"653+ },654+ "next": {655+ "minLength": 1,656+ "type": "string"657+ },658+ "retryable": {659+ "enum": [660+ false661+ ],662+ "type": "boolean"663+ }664+ },665+ "required": [666+ "_tag",667+ "next",668+ "retryable"669+ ],670+ "type": "object"671+ },672+ "OutOfScopeEncoded": {673+ "additionalProperties": true,674+ "properties": {675+ "_tag": {676+ "enum": [677+ "OutOfScope"678+ ],679+ "type": "string"680+ },681+ "at": {682+ "additionalProperties": true,683+ "properties": {684+ "line": {685+ "minimum": 1,686+ "type": "integer"687+ },688+ "path": {689+ "minLength": 1,690+ "type": "string"691+ }692+ },693+ "required": [694+ "line",695+ "path"696+ ],697+ "type": "object"698+ },699+ "next": {700+ "minLength": 1,701+ "type": "string"702+ },703+ "paths": {704+ "items": {705+ "minLength": 1,706+ "type": "string"707+ },708+ "minItems": 1,709+ "prefixItems": [710+ {711+ "minLength": 1,712+ "type": "string"713+ }714+ ],715+ "type": "array"716+ },717+ "retryable": {718+ "enum": [719+ false720+ ],721+ "type": "boolean"722+ }723+ },724+ "required": [725+ "_tag",726+ "next",727+ "retryable",728+ "paths"729+ ],730+ "type": "object"731+ },732+ "PostureChangeEncoded": {733+ "additionalProperties": true,734+ "properties": {735+ "_tag": {736+ "enum": [737+ "PostureChange"738+ ],739+ "type": "string"740+ },741+ "at": {742+ "additionalProperties": true,743+ "properties": {744+ "line": {745+ "minimum": 1,746+ "type": "integer"747+ },748+ "path": {749+ "minLength": 1,750+ "type": "string"751+ }752+ },753+ "required": [754+ "line",755+ "path"756+ ],757+ "type": "object"758+ },759+ "from": {760+ "enum": [761+ "open",762+ "openWithSealedEvidence",763+ "openOnSchedule",764+ "openCore",765+ "sourceAvailable"766+ ],767+ "type": "string"768+ },769+ "next": {770+ "minLength": 1,771+ "type": "string"772+ },773+ "retryable": {774+ "enum": [775+ false776+ ],777+ "type": "boolean"778+ },779+ "to": {780+ "enum": [781+ "open",782+ "openWithSealedEvidence",783+ "openOnSchedule",784+ "openCore",785+ "sourceAvailable"786+ ],787+ "type": "string"788+ }789+ },790+ "required": [791+ "_tag",792+ "next",793+ "retryable",794+ "from",795+ "to"796+ ],797+ "type": "object"798+ },799+ "PrivatePathInPublicTreeEncoded": {800+ "additionalProperties": true,801+ "properties": {802+ "_tag": {803+ "enum": [804+ "PrivatePathInPublicTree"805+ ],806+ "type": "string"807+ },808+ "at": {809+ "additionalProperties": true,810+ "properties": {811+ "line": {812+ "minimum": 1,813+ "type": "integer"814+ },815+ "path": {816+ "minLength": 1,817+ "type": "string"818+ }819+ },820+ "required": [821+ "line",822+ "path"823+ ],824+ "type": "object"825+ },826+ "next": {827+ "minLength": 1,828+ "type": "string"829+ },830+ "paths": {831+ "items": {832+ "minLength": 1,833+ "type": "string"834+ },835+ "minItems": 1,836+ "prefixItems": [837+ {838+ "minLength": 1,839+ "type": "string"840+ }841+ ],842+ "type": "array"843+ },844+ "retryable": {845+ "enum": [846+ false847+ ],848+ "type": "boolean"849+ }850+ },851+ "required": [852+ "_tag",853+ "next",854+ "retryable",855+ "paths"856+ ],857+ "type": "object"858+ },859+ "Refusal": {860+ "anyOf": [861+ {862+ "$ref": "#/$defs/NotClaimedEncoded"863+ },864+ {865+ "$ref": "#/$defs/ClaimLapsedEncoded"866+ },867+ {868+ "$ref": "#/$defs/NotVouchedEncoded"869+ },870+ {871+ "$ref": "#/$defs/CapReachedEncoded"872+ },873+ {874+ "$ref": "#/$defs/AskFullEncoded"875+ },876+ {877+ "$ref": "#/$defs/NoAskEncoded"878+ },879+ {880+ "$ref": "#/$defs/RepoBusyEncoded"881+ },882+ {883+ "$ref": "#/$defs/OutOfScopeEncoded"884+ },885+ {886+ "$ref": "#/$defs/TouchedJudgeEncoded"887+ },888+ {889+ "$ref": "#/$defs/WeakenedEncoded"890+ },891+ {892+ "$ref": "#/$defs/PrivatePathInPublicTreeEncoded"893+ },894+ {895+ "$ref": "#/$defs/StaleBaseEncoded"896+ },897+ {898+ "$ref": "#/$defs/ChecksFailedEncoded"899+ },900+ {901+ "$ref": "#/$defs/HeldBackFailedEncoded"902+ },903+ {904+ "$ref": "#/$defs/AttemptsExhaustedEncoded"905+ },906+ {907+ "$ref": "#/$defs/FlakeEncoded"908+ },909+ {910+ "$ref": "#/$defs/VerifierBlockedEncoded"911+ },912+ {913+ "$ref": "#/$defs/NotRedFirstEncoded"914+ },915+ {916+ "$ref": "#/$defs/WeakCheckEncoded"917+ },918+ {919+ "$ref": "#/$defs/IncompleteBriefEncoded"920+ },921+ {922+ "$ref": "#/$defs/LayerContentInPublicTreeEncoded"923+ },924+ {925+ "$ref": "#/$defs/SecretInOutputEncoded"926+ },927+ {928+ "$ref": "#/$defs/PostureChangeEncoded"929+ }930+ ]931+ },932+ "RepoBusyEncoded": {933+ "additionalProperties": true,934+ "properties": {935+ "_tag": {936+ "enum": [937+ "RepoBusy"938+ ],939+ "type": "string"940+ },941+ "at": {942+ "additionalProperties": true,943+ "properties": {944+ "line": {945+ "minimum": 1,946+ "type": "integer"947+ },948+ "path": {949+ "minLength": 1,950+ "type": "string"951+ }952+ },953+ "required": [954+ "line",955+ "path"956+ ],957+ "type": "object"958+ },959+ "next": {960+ "minLength": 1,961+ "type": "string"962+ },963+ "retryable": {964+ "enum": [965+ true966+ ],967+ "type": "boolean"968+ }969+ },970+ "required": [971+ "_tag",972+ "next",973+ "retryable"974+ ],975+ "type": "object"976+ },977+ "SecretInOutputEncoded": {978+ "additionalProperties": true,979+ "properties": {980+ "_tag": {981+ "enum": [982+ "SecretInOutput"983+ ],984+ "type": "string"985+ },986+ "at": {987+ "additionalProperties": true,988+ "properties": {989+ "line": {990+ "minimum": 1,991+ "type": "integer"992+ },993+ "path": {994+ "minLength": 1,995+ "type": "string"996+ }997+ },998+ "required": [999+ "line",1000+ "path"1001+ ],1002+ "type": "object"1003+ },1004+ "item": {1005+ "minLength": 1,1006+ "type": "string"1007+ },1008+ "next": {1009+ "minLength": 1,1010+ "type": "string"1011+ },1012+ "retryable": {1013+ "enum": [1014+ false1015+ ],1016+ "type": "boolean"1017+ },1018+ "where": {1019+ "enum": [1020+ "output",1021+ "tree"1022+ ],1023+ "type": "string"1024+ }1025+ },1026+ "required": [1027+ "_tag",1028+ "next",1029+ "retryable",1030+ "item",1031+ "where"1032+ ],1033+ "type": "object"1034+ },1035+ "StaleBaseEncoded": {1036+ "additionalProperties": true,1037+ "properties": {1038+ "_tag": {1039+ "enum": [1040+ "StaleBase"1041+ ],1042+ "type": "string"1043+ },1044+ "at": {1045+ "additionalProperties": true,1046+ "properties": {1047+ "line": {1048+ "minimum": 1,1049+ "type": "integer"1050+ },1051+ "path": {1052+ "minLength": 1,1053+ "type": "string"1054+ }1055+ },1056+ "required": [1057+ "line",1058+ "path"1059+ ],1060+ "type": "object"1061+ },1062+ "base": {1063+ "pattern": "^[0-9a-f]{40}$",1064+ "type": "string"1065+ },1066+ "conflicts": {1067+ "items": {1068+ "minLength": 1,1069+ "type": "string"1070+ },1071+ "type": "array"1072+ },1073+ "main": {1074+ "pattern": "^[0-9a-f]{40}$",1075+ "type": "string"1076+ },1077+ "next": {1078+ "minLength": 1,1079+ "type": "string"1080+ },1081+ "retryable": {1082+ "enum": [1083+ true1084+ ],1085+ "type": "boolean"1086+ }1087+ },1088+ "required": [1089+ "_tag",1090+ "next",1091+ "retryable",1092+ "base",1093+ "conflicts",1094+ "main"1095+ ],1096+ "type": "object"1097+ },1098+ "TouchedJudgeEncoded": {1099+ "additionalProperties": true,1100+ "properties": {1101+ "_tag": {1102+ "enum": [1103+ "TouchedJudge"1104+ ],1105+ "type": "string"1106+ },1107+ "at": {1108+ "additionalProperties": true,1109+ "properties": {1110+ "line": {1111+ "minimum": 1,1112+ "type": "integer"1113+ },1114+ "path": {1115+ "minLength": 1,1116+ "type": "string"1117+ }1118+ },1119+ "required": [1120+ "line",1121+ "path"1122+ ],1123+ "type": "object"1124+ },1125+ "next": {1126+ "minLength": 1,1127+ "type": "string"1128+ },1129+ "paths": {1130+ "items": {1131+ "minLength": 1,1132+ "type": "string"1133+ },1134+ "minItems": 1,1135+ "prefixItems": [1136+ {1137+ "minLength": 1,1138+ "type": "string"1139+ }1140+ ],1141+ "type": "array"1142+ },1143+ "retryable": {1144+ "enum": [1145+ false1146+ ],1147+ "type": "boolean"1148+ }1149+ },1150+ "required": [1151+ "_tag",1152+ "next",1153+ "retryable",1154+ "paths"1155+ ],1156+ "type": "object"1157+ },1158+ "VerifierBlockedEncoded": {1159+ "additionalProperties": true,1160+ "properties": {1161+ "_tag": {1162+ "enum": [1163+ "VerifierBlocked"1164+ ],1165+ "type": "string"1166+ },1167+ "at": {1168+ "additionalProperties": true,1169+ "properties": {1170+ "line": {1171+ "minimum": 1,1172+ "type": "integer"1173+ },1174+ "path": {1175+ "minLength": 1,1176+ "type": "string"1177+ }1178+ },1179+ "required": [1180+ "line",1181+ "path"1182+ ],1183+ "type": "object"1184+ },1185+ "next": {1186+ "minLength": 1,1187+ "type": "string"1188+ },1189+ "retryable": {1190+ "enum": [1191+ true1192+ ],1193+ "type": "boolean"1194+ }1195+ },1196+ "required": [1197+ "_tag",1198+ "next",1199+ "retryable"1200+ ],1201+ "type": "object"1202+ },1203+ "WeakCheckEncoded": {1204+ "additionalProperties": true,1205+ "properties": {1206+ "_tag": {1207+ "enum": [1208+ "WeakCheck"1209+ ],1210+ "type": "string"1211+ },1212+ "at": {1213+ "additionalProperties": true,1214+ "properties": {1215+ "line": {1216+ "minimum": 1,1217+ "type": "integer"1218+ },1219+ "path": {1220+ "minLength": 1,1221+ "type": "string"1222+ }1223+ },1224+ "required": [1225+ "line",1226+ "path"1227+ ],1228+ "type": "object"1229+ },1230+ "next": {1231+ "minLength": 1,1232+ "type": "string"1233+ },1234+ "retryable": {1235+ "enum": [1236+ false1237+ ],1238+ "type": "boolean"1239+ },1240+ "weakness": {1241+ "minLength": 1,1242+ "type": "string"1243+ }1244+ },1245+ "required": [1246+ "_tag",1247+ "next",1248+ "retryable",1249+ "weakness"1250+ ],1251+ "type": "object"1252+ },1253+ "WeakenedEncoded": {1254+ "additionalProperties": true,1255+ "properties": {1256+ "_tag": {1257+ "enum": [1258+ "Weakened"1259+ ],1260+ "type": "string"1261+ },1262+ "at": {1263+ "additionalProperties": true,1264+ "properties": {1265+ "line": {1266+ "minimum": 1,1267+ "type": "integer"1268+ },1269+ "path": {1270+ "minLength": 1,1271+ "type": "string"1272+ }1273+ },1274+ "required": [1275+ "line",1276+ "path"1277+ ],1278+ "type": "object"1279+ },1280+ "next": {1281+ "minLength": 1,1282+ "type": "string"1283+ },1284+ "retryable": {1285+ "enum": [1286+ false1287+ ],1288+ "type": "boolean"1289+ },1290+ "weakening": {1291+ "anyOf": [1292+ {1293+ "additionalProperties": true,1294+ "properties": {1295+ "marker": {1296+ "minLength": 1,1297+ "type": "string"1298+ },1299+ "reason": {1300+ "minLength": 1,1301+ "type": "string"1302+ }1303+ },1304+ "required": [1305+ "marker"1306+ ],1307+ "type": "object"1308+ },1309+ {1310+ "additionalProperties": true,1311+ "properties": {1312+ "after": {1313+ "type": "integer"1314+ },1315+ "before": {1316+ "type": "integer"1317+ },1318+ "ratchet": {1319+ "minLength": 1,1320+ "type": "string"1321+ },1322+ "territory": {1323+ "minLength": 1,1324+ "type": "string"1325+ }1326+ },1327+ "required": [1328+ "after",1329+ "before",1330+ "ratchet",1331+ "territory"1332+ ],1333+ "type": "object"1334+ }1335+ ]1336+ }1337+ },1338+ "required": [1339+ "_tag",1340+ "next",1341+ "retryable",1342+ "weakening"1343+ ],1344+ "type": "object"1345+ },1346+ "listAsks.error": {1347+ "not": {}1348+ },1349+ "listAsks.payload": {1350+ "additionalProperties": true,1351+ "properties": {1352+ "project": {1353+ "pattern": "^[a-z0-9][a-z0-9-]*$",1354+ "type": "string"1355+ }1356+ },1357+ "required": [1358+ "project"1359+ ],1360+ "type": "object"1361+ },1362+ "listAsks.success": {1363+ "additionalProperties": true,1364+ "properties": {1365+ "asks": {1366+ "items": {1367+ "additionalProperties": true,1368+ "properties": {1369+ "ask": {1370+ "pattern": "^[a-z0-9][a-z0-9-]*$",1371+ "type": "string"1372+ },1373+ "claimed": {1374+ "type": "boolean"1375+ },1376+ "territory": {1377+ "minLength": 1,1378+ "type": "string"1379+ },1380+ "want": {1381+ "minLength": 1,1382+ "type": "string"1383+ }1384+ },1385+ "required": [1386+ "ask",1387+ "claimed",1388+ "territory",1389+ "want"1390+ ],1391+ "type": "object"1392+ },1393+ "type": "array"1394+ }1395+ },1396+ "required": [1397+ "asks"1398+ ],1399+ "type": "object"1400+ },1401+ "submitAnswer.error": {1402+ "anyOf": [1403+ {1404+ "$ref": "#/$defs/NotClaimedEncoded"1405+ },1406+ {1407+ "$ref": "#/$defs/ClaimLapsedEncoded"1408+ },1409+ {1410+ "$ref": "#/$defs/StaleBaseEncoded"1411+ },1412+ {1413+ "$ref": "#/$defs/RepoBusyEncoded"1414+ }1415+ ]1416+ },1417+ "submitAnswer.payload": {1418+ "additionalProperties": true,1419+ "properties": {1420+ "ask": {1421+ "pattern": "^[a-z0-9][a-z0-9-]*$",1422+ "type": "string"1423+ },1424+ "base": {1425+ "pattern": "^[0-9a-f]{40}$",1426+ "type": "string"1427+ },1428+ "head": {1429+ "pattern": "^[0-9a-f]{40}$",1430+ "type": "string"1431+ }1432+ },1433+ "required": [1434+ "ask",1435+ "base",1436+ "head"1437+ ],1438+ "type": "object"1439+ },1440+ "submitAnswer.success": {1441+ "additionalProperties": true,1442+ "properties": {1443+ "main": {1444+ "pattern": "^[0-9a-f]{40}$",1445+ "type": "string"1446+ }1447+ },1448+ "required": [1449+ "main"1450+ ],1451+ "type": "object"1452+ }1453+ },1454+ "$schema": "https://json-schema.org/draft/2020-12/schema",1455+ "title": "The Myr protocol"1456+}modified:docs/reference/refusals.md+24 added-1 removed
7 unmodified lines8 - `retryable`: whether trying again can help, fixed for each refusal.9 - `next`: the command to run next.10 - `at` (optional): the `path` and `line` it points at.11 12-No refusal has a message. Shape refusals accumulate, so one push hears about every one at once. Field types are given as they travel on the wire.12+No refusal has a message. Shape refusals accumulate, so one push hears about every one at once. Field types are given as they travel on the wire. Each reason is what the renderer says for one example of that refusal.13 14 ## Push and claim15 16 ### NotClaimed1 unmodified line18 - Retryable: yes19 - Next: set when it is raised20 - Fields:21 - `ask`: `string`22+- Reason, for example: you hold no claim on fix-parser23 24 ### ClaimLapsed25 26 - Retryable: yes27 - Next: set when it is raised28 - Fields:29 - `ask`: `string`30+- Reason, for example: your claim on fix-parser lapsed31 32 ### NotVouched33 34 - Retryable: no35 - Next: `myr status`36 - Fields: none37+- Reason, for example: no member of this project has vouched for you38 39 ### CapReached40 41 - Retryable: yes42 - Next: `myr status`43 - Fields:44 - `cap`: `number`45+- Reason, for example: you already hold 3 claims, the most this project allows46 47 ### AskFull48 49 - Retryable: yes50 - Next: `myr asks`51 - Fields:52 - `ask`: `string`53+- Reason, for example: someone else holds the claim on fix-parser54 55 ### NoAsk56 57 - Retryable: no58 - Next: `myr asks`59 - Fields: none60+- Reason, for example: this push names no open ask61 62 ### RepoBusy63 64 - Retryable: yes65 - Next: `git push`66 - Fields: none67+- Reason, for example: the repo was busy with another push68 69 ## Shape70 71 ### OutOfScope1 unmodified line73 - Retryable: no74 - Next: `myr check`75 - Fields:76 - `paths`: `readonly [string, ...Array<string>]`77+- Reason, for example: changes paths outside the ask's territory: src/a.ts78 79 ### TouchedJudge80 81 - Retryable: no82 - Next: `myr check`83 - Fields:84 - `paths`: `readonly [string, ...Array<string>]`85+- Reason, for example: changes files that decide what the checks do: src/a.ts86 87 ### Weakened88 89 - Retryable: no90 - Next: `myr check`91 - Fields:92 - `weakening`: `{ readonly "marker": string, readonly "reason"?: string } | { readonly "after": number, readonly "before": number, readonly "ratchet": string, readonly "territory": string }`93+- Reason, for example: adds it.skip, with the reason "flaky on CI"94 95 ### PrivatePathInPublicTree96 97 - Retryable: no98 - Next: `myr check`99 - Fields:100 - `paths`: `readonly [string, ...Array<string>]`101+- Reason, for example: would put held-back paths in a public tree: src/a.ts102 103 ## Merge104 105 ### StaleBase3 unmodified lines109 - Fields:110 - `base`: `string`111 - `conflicts`: `ReadonlyArray<string>`112 - `main`: `string`113+- Reason, for example: main moved to 2222222, past your base 1111111; conflicts in src/a.ts114 115 ## Checks116 117 ### ChecksFailed2 unmodified lines120 - Next: set when it is raised121 - Fields:122 - `lane`: `string`123 - `logRef`: `string`124+- Reason, for example: the test checks failed; the log is at logs/7125 126 ### HeldBackFailed127 128 - Retryable: no129 - Next: `myr status`130 - Fields:131 - `area`: `string`132 - `suite`: `string`133+- Reason, for example: a held-back check failed in parser, suite edge-cases134 135 ### AttemptsExhausted136 137 - Retryable: yes138 - Next: `myr status`139 - Fields:140 - `area`: `string`141 - `resetsAt`: `string`142+- Reason, for example: no attempts left on parser until 2026-10-07T00:00:00.000Z143 144 ## Never counted against the answerer145 146 ### Flake1 unmodified line148 - Retryable: yes149 - Next: `myr status`150 - Fields:151 - `lane`: `string`152+- Reason, for example: the test checks failed, then passed on the same tree; the platform will run them again153 154 ### VerifierBlocked155 156 - Retryable: yes157 - Next: `myr status`158 - Fields: none159+- Reason, for example: the platform could not run the checks; it will run them again160 161 ## At ask open162 163 ### NotRedFirst164 165 - Retryable: no166 - Next: `myr check`167 - Fields: none168+- Reason, for example: the ask's check must fail on main twice in the same way, by an assertion169 170 ### WeakCheck171 172 - Retryable: no173 - Next: `myr check`174 - Fields:175 - `weakness`: `string`176+- Reason, for example: the ask's check is weak: no assertion177 178 ### IncompleteBrief179 180 - Retryable: no181 - Next: `myr check`182 - Fields:183 - `missing`: `readonly [string, ...Array<string>]`184+- Reason, for example: the brief is missing territory185 186 ## Maintainers only187 188 ### LayerContentInPublicTree1 unmodified line190 - Retryable: no191 - Next: `myr check`192 - Fields:193 - `paths`: `readonly [string, ...Array<string>]`194+- Reason, for example: a layer's files would enter a public tree: src/a.ts195 196 ### SecretInOutput197 198 - Retryable: no199 - Next: `myr check`200 - Fields:201 - `item`: `string`202 - `where`: `"output" | "tree"`203+- Reason, for example: the write-only value PAYMENTS_KEY appeared in the output204 205 ## Decision206 207 ### PostureChange2 unmodified lines210 - Next: `myr today`211 - Fields:212 - `from`: `"open" | "openWithSealedEvidence" | "openOnSchedule" | "openCore" | "sourceAvailable"`213 - `to`: `"open" | "openWithSealedEvidence" | "openOnSchedule" | "openCore" | "sourceAvailable"`214+- Reason, for example: landing would change the posture from open to openCore, which takes a decideradded:packages/config/test/gen.test.ts+339 added
1+import { describe, expect, it } from "@effect/vitest";2+import { Predicate, Schema, SchemaAST } from "effect";3+4+import {5+ CommandCatalog,6+ Contracts,7+ generate,8+ Refusal,9+} from "../../../scripts/lib/gen.ts";10+11+const NON_FINITE = new Set(["Infinity", "-Infinity", "NaN"]);12+13+/** A generated JSON file, or a JSON block, decoded where the test reads it. */14+const parseJson = Schema.decodeSync(Schema.fromJsonString(Schema.Json));15+16+const isJsonArray = (value: Schema.Json): value is Schema.JsonArray =>17+ Array.isArray(value);18+19+const isJsonObject = (value: Schema.Json): value is Schema.JsonObject =>20+ Predicate.isObject(value);21+22+const children = (value: Schema.Json): readonly Schema.Json[] => {23+ if (isJsonArray(value)) {24+ return value;25+ }26+27+ return isJsonObject(value) ? Object.values(value) : [];28+};29+30+/** Every value nested anywhere in a JSON value, itself included. */31+const nested = (value: Schema.Json): readonly Schema.Json[] => [32+ value,33+ ...children(value).flatMap(nested),34+];35+36+/** Whether a JSON Schema admits `null`, directly or through a union member. */37+const admitsNull = (schema: Schema.Json): boolean => {38+ if (!isJsonObject(schema)) {39+ return false;40+ }41+42+ const { anyOf = [], oneOf = [], type = [] } = schema;43+44+ const members = [anyOf, oneOf].flatMap((list) =>45+ isJsonArray(list) ? list : []46+ );47+48+ return (49+ type === "null" ||50+ (isJsonArray(type) && type.includes("null")) ||51+ members.some(admitsNull)52+ );53+};54+55+/**56+ * The two ways Effect's JSON Schema leaks a non-JSON value (AGENTS.md "Effect57+ * traps"): a number that admits the strings "Infinity", "-Infinity" and58+ * "NaN", and an optional key whose value may be `null`.59+ */60+const leaks = (schema: Schema.Json): readonly string[] =>61+ nested(schema).flatMap((value) => {62+ if (Predicate.isString(value) && NON_FINITE.has(value)) {63+ return [`non-finite string ${value}`];64+ }65+66+ if (!isJsonObject(value)) {67+ return [];68+ }69+70+ const { properties = {}, required = [] } = value;71+72+ if (!isJsonObject(properties)) {73+ return [];74+ }75+76+ const needed = new Set(isJsonArray(required) ? required : []);77+78+ return Object.entries(properties).flatMap(([key, property]) =>79+ !needed.has(key) && admitsNull(property)80+ ? [`null under optional key ${key}`]81+ : []82+ );83+ });84+85+/** A pointer to a refusal's one definition, named for its encoded side. */86+const ref = (tag: string) => ({ $ref: `#/$defs/${tag}Encoded` });87+88+const content = (path: string) =>89+ generate().find((file) => file.path === path)?.content ?? "";90+91+/** The JSON blocks in a Markdown page: here, each tool's schemas. */92+const jsonBlocks = (markdown: string): readonly Schema.Json[] =>93+ [...markdown.matchAll(/```json\n(?<body>[\s\S]*?)\n```/gu)].map((match) =>94+ parseJson(match.groups?.body ?? "null")95+ );96+97+/** A Markdown page's `## ` sections, keyed by their heading. */98+const sections = (markdown: string): ReadonlyMap<string, string> =>99+ new Map(100+ [101+ ...markdown.matchAll(102+ /^## (?<heading>.+)\n(?<body>[\s\S]*?)(?=^## |(?![\s\S]))/gmu103+ ),104+ ].map((match) => [match.groups?.heading ?? "", match.groups?.body ?? ""])105+ );106+107+/** The definitions in protocol.schema.json, by name. */108+const definitions = () =>109+ Schema.decodeSync(110+ Schema.fromJsonString(111+ Schema.Struct({ $defs: Schema.Record(Schema.String, Schema.Json) })112+ )113+ )(content("docs/reference/protocol.schema.json")).$defs;114+115+const catalog = () =>116+ Schema.decodeSync(Schema.fromJsonString(CommandCatalog))(117+ content("docs/reference/commands.json")118+ );119+120+/** The fields a command's payload schema names. */121+const payloadFields = Schema.decodeUnknownSync(122+ Schema.Struct({ properties: Schema.Record(Schema.String, Schema.Json) })123+);124+125+/** A union of pointers, as a contract's error is written. */126+const decodeUnion = Schema.decodeUnknownSync(127+ Schema.Struct({ anyOf: Schema.Array(Schema.Struct({ $ref: Schema.String })) })128+);129+130+/** An object schema's required keys. */131+const decodeObject = Schema.decodeUnknownSync(132+ Schema.Struct({ required: Schema.Array(Schema.String) })133+);134+135+const contracts = [...Contracts.requests.values()];136+137+describe("generation", () => {138+ it("writes exactly the five reference files, sorted by path", () => {139+ expect(generate().map((file) => file.path)).toStrictEqual([140+ "docs/reference/cli.md",141+ "docs/reference/commands.json",142+ "docs/reference/mcp-tools.md",143+ "docs/reference/protocol.schema.json",144+ "docs/reference/refusals.md",145+ ]);146+ });147+148+ it("writes the same bytes every time", () => {149+ expect(generate()).toStrictEqual(generate());150+ });151+152+ it("ends every file with one newline", () => {153+ for (const file of generate()) {154+ expect(file.content.endsWith("\n")).toBeTruthy();155+ expect(file.content.endsWith("\n\n")).toBeFalsy();156+ }157+ });158+});159+160+describe("the leak finder", () => {161+ it("flags both of Effect's known leaks", () => {162+ const leaky = Schema.toJsonSchemaDocument(163+ Schema.Struct({164+ count: Schema.Number,165+ note: Schema.optional(Schema.String),166+ })167+ );168+169+ expect(170+ leaks(Schema.decodeUnknownSync(Schema.Json)(leaky.schema))171+ ).toStrictEqual([172+ "null under optional key note",173+ "non-finite string Infinity",174+ "non-finite string -Infinity",175+ "non-finite string NaN",176+ ]);177+ });178+});179+180+describe("the generated JSON Schema", () => {181+ it("defines each contract's payload, success and error", () => {182+ const defined = new Set(Object.keys(definitions()));183+184+ const missing = contracts185+ .flatMap((rpc) =>186+ ["payload", "success", "error"].map((part) => `${rpc._tag}.${part}`)187+ )188+ .filter((name) => !defined.has(name));189+190+ expect(contracts).not.toHaveLength(0);191+ expect(missing).toStrictEqual([]);192+ });193+194+ it("defines each refusal once, and points the union and a contract's errors at it", () => {195+ const document = parseJson(content("docs/reference/protocol.schema.json"));196+ const $defs = definitions();197+ const { anyOf } = decodeUnion($defs["submitAnswer.error"]);198+ const { required } = decodeObject($defs["submitAnswer.payload"]);199+200+ const pointedAt = new Set(anyOf.map((member) => member.$ref));201+ const fields = new Set(required);202+203+ expect(document).toMatchObject({204+ $defs: {205+ Refusal: {206+ anyOf: Refusal.members.map((member) => ref(member.identifier)),207+ },208+ "listAsks.payload": { required: ["project"] },209+ "listAsks.success": { required: ["asks"] },210+ },211+ $schema: "https://json-schema.org/draft/2020-12/schema",212+ });213+ // Later contracts may widen submitAnswer; what it has now must stay.214+ expect(215+ ["NotClaimed", "ClaimLapsed", "StaleBase", "RepoBusy"].flatMap((tag) =>216+ pointedAt.has(ref(tag).$ref) ? [] : [tag]217+ )218+ ).toStrictEqual([]);219+ expect(220+ ["ask", "base", "head"].flatMap((field) =>221+ fields.has(field) ? [] : [field]222+ )223+ ).toStrictEqual([]);224+ });225+226+ it("says a contract with no refusals of its own can't fail that way", () => {227+ const $defs = definitions();228+229+ const infallible = contracts.flatMap((rpc) =>230+ SchemaAST.isNever(rpc.errorSchema.ast) ? [rpc._tag] : []231+ );232+233+ expect(infallible).not.toHaveLength(0);234+ expect(infallible.map((tag) => $defs[`${tag}.error`])).toStrictEqual(235+ infallible.map(() => ({ not: {} }))236+ );237+ });238+239+ it("admits no non-finite number string and no null under an optional key", () => {240+ expect(241+ leaks(parseJson(content("docs/reference/protocol.schema.json")))242+ ).toStrictEqual([]);243+ });244+245+ it("gives every MCP tool's input and output schema, with no leak in either", () => {246+ const reference = content("docs/reference/mcp-tools.md");247+ const schemas = jsonBlocks(reference);248+249+ // An input and an output for each tool.250+ expect(sections(reference).size).toBeGreaterThan(0);251+ expect(schemas).toHaveLength(2 * sections(reference).size);252+ expect(schemas.flatMap(leaks)).toStrictEqual([]);253+ });254+});255+256+describe("the command catalog", () => {257+ it("decodes with its own schema and lists asks and submit", () => {258+ const { commands, version } = catalog();259+260+ const byName = new Map(commands.map((command) => [command.name, command]));261+262+ expect(version).toBe(1);263+ expect(byName.get("asks")).toMatchObject({264+ contract: "listAsks",265+ destructive: false,266+ idempotent: true,267+ needsApproval: false,268+ path: ["asks"],269+ positional: [],270+ readOnly: true,271+ source: "projected",272+ surfaces: ["rpc", "mcp", "cli", "web"],273+ });274+ expect(byName.get("submit")).toMatchObject({275+ contract: "submitAnswer",276+ destructive: false,277+ idempotent: true,278+ needsApproval: false,279+ path: ["submit"],280+ readOnly: false,281+ source: "projected",282+ });283+ expect(284+ commands.flatMap((command) => leaks(command.payloadSchema))285+ ).toStrictEqual([]);286+ });287+288+ it("is what the CLI reference is rendered from: every command, with its arguments", () => {289+ const { commands } = catalog();290+291+ // A heading is the command line in backticks: the CLI's name, then the path.292+ const byPath = new Map(293+ [...sections(content("docs/reference/cli.md"))].map(([heading, body]) => [294+ heading.replace(/^`\S+ (?<path>.+)`$/u, "$<path>"),295+ body,296+ ])297+ );298+299+ const unrendered = commands.flatMap((command) => {300+ const path = command.path.join(" ");301+ const body = byPath.get(path) ?? "";302+ const positional = new Set(command.positional);303+ const { properties } = payloadFields(command.payloadSchema);304+305+ return [306+ ...command.positional.map((field) => `<${field}>`),307+ ...Object.keys(properties).flatMap((field) =>308+ positional.has(field) ? [] : [`--${field}`]309+ ),310+ ].flatMap((argument) =>311+ body.includes(`| \`${argument}\` |`) ? [] : [`${path} ${argument}`]312+ );313+ });314+315+ expect([...byPath.keys()]).toStrictEqual(316+ commands.map((command) => command.path.join(" "))317+ );318+ expect(unrendered).toStrictEqual([]);319+ // Known rows, so an empty catalog can't pass.320+ expect(byPath.get("asks")).toContain("| `--project` | text | yes |");321+ expect(byPath.get("submit")).toContain("| `--head` | text | yes |");322+ });323+});324+325+describe("the refusals reference", () => {326+ it("gives each refusal's reason as the renderer words it", () => {327+ const reference = content("docs/reference/refusals.md");328+329+ const staleBase = reference.slice(330+ reference.indexOf("### StaleBase"),331+ reference.indexOf("## Checks")332+ );333+334+ expect(staleBase).toContain("main moved to");335+ expect(reference.match(/^- Reason, for example: /gmu)).toHaveLength(336+ reference.match(/^### /gmu)?.length ?? -1337+ );338+ });339+});modified:packages/protocol/src/annotations.ts+64 added-1 removed
1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import { Context } from "effect";import { Context, Schema } from "effect";
/** * What every contract says about itself, beside its schemas. Each is set with * `.annotate(Key, value)` on `Rpc.make(…)` and read with `Context.get`; a * contract that sets none gets the defaults below. */
/** What a contract does, in one sentence, for every surface that lists it. */export const Description = Context.Reference<string>("protocol/Description", { defaultValue: () => "",});
/** * Who may call it: anyone, a signed-in person, or one of the project's * deciders. The handler checks `decider`; the annotation documents it. */export const Audience = Context.Reference<"public" | "signedIn" | "decider">( "protocol/Audience", { defaultValue: () => "signedIn" });
/** Whether its response may be shown to anyone, or only to maintainers. */export const Visibility = Context.Reference<"public" | "maintainers">( "protocol/Visibility", { defaultValue: () => "public" });
/** It only reads: it changes nothing. */export const ReadOnly = Context.Reference<boolean>("protocol/ReadOnly", { defaultValue: () => false,});
/** Calling it again with the same payload changes nothing more. */export const Idempotent = Context.Reference<boolean>("protocol/Idempotent", { defaultValue: () => false,});
/** * It can destroy something a person cannot get back. Set it on every * contract: every tool carries this value, so a destructive contract that * forgot it would tell an agent it is safe (`annotations.test.ts` holds this). */export const Destructive = Context.Reference<boolean>("protocol/Destructive", { defaultValue: () => false,});
/** A person approves it before it runs: the CLI asks for `--yes`. */export const NeedsApproval = Context.Reference<boolean>( "protocol/NeedsApproval", { defaultValue: () => false });
/** The CLI command it becomes: its name, and the payload fields taken in order. */export const Cli = Context.Reference<{ readonly name?: string; readonly positional?: readonly string[];}>("protocol/Cli", { defaultValue: () => ({}) });
/** Every surface a contract can be served on. */export const SurfaceName = Schema.Literals(["rpc", "mcp", "cli", "web"]);
export type SurfaceName = typeof SurfaceName.Type;
/** The surfaces it is served on; every one by default. */export const Surfaces = Context.Reference<readonly SurfaceName[]>( "protocol/Surfaces", { defaultValue: () => SurfaceName.literals });modified:packages/protocol/src/contracts.ts+38 added-6 removed
1234556789101112131415161718192021222324252627282930313233343 unmodified lines3839404121424344454647484950515253542728293055565758596061626364656610 unmodified linesimport { Context, Schema } from "effect";import { Rpc, RpcGroup } from "effect/rpc";import type { RpcClient, RpcClientError } from "effect/rpc";
import { Description } from "./annotations.ts";import { Audience, Cli, Description, Destructive, Idempotent, ReadOnly,} from "./annotations.ts";import { AskId, CommitSha, ProjectName } from "./ids.ts";import { Authenticated } from "./principal.ts";import { ClaimLapsed, NotClaimed, RepoBusy, StaleBase } from "./refusal.ts";
/** The keys every contract is annotated with, for the surfaces that read them. */export { Audience, Cli, Description, Destructive, Idempotent, NeedsApproval, ReadOnly, SurfaceName, Surfaces, Visibility,} from "./annotations.ts";
/** One open ask, as a list of asks shows it. */export const AskListing = Schema.Struct({ ask: AskId, claimed: Schema.Boolean,3 unmodified lines
export class ListAsks extends Rpc.make("listAsks", { payload: { project: ProjectName }, success: Schema.Struct({ asks: Schema.Array(AskListing) }),}).annotate(Description, "List a project's open asks.") {}}) .annotate(Description, "List a project's open asks.") .annotate(ReadOnly, true) .annotate(Idempotent, true) .annotate(Destructive, false) .annotate(Audience, "public") .annotate(Cli, { name: "asks" }) {}
export class SubmitAnswer extends Rpc.make("submitAnswer", { error: Schema.Union([NotClaimed, ClaimLapsed, StaleBase, RepoBusy]), payload: { ask: AskId, base: CommitSha, head: CommitSha }, success: Schema.Struct({ main: CommitSha }),})}).annotate( Description, "Offer the commit `head`, built on `base`, as an answer to an ask; once it lands, `main` is the new tip.") {} .annotate( Description, "Offer the commit `head`, built on `base`, as an answer to an ask; once it lands, `main` is the new tip." ) .annotate(Idempotent, true) .annotate(Destructive, false) .annotate(Audience, "signedIn") .annotate(Cli, { name: "submit" }) {}
/** The one schema: every surface is a projection of this group. */export class Contracts extends RpcGroup.make(ListAsks, SubmitAnswer).middleware( Authenticated10 unmodified linesmodified:packages/protocol/src/mcp.ts+94 added-7 removed
1 // Ported from joelhooks/rat-stack@fba26d8 `packages/capability/src/to-toolkit.ts`2 // (MIT, LICENSES/rat-stack.MIT.txt). Changes are listed in PROVENANCE.md.3-import type { Layer } from "effect";4-import { Context, Effect } from "effect";3+import type { JsonSchema, Layer } from "effect";4+import { Context, Effect, JsonPointer, Predicate, Schema } from "effect";5 import { Tool, Toolkit } from "effect/ai";6 import type { Rpc, RpcClient, RpcClientError, RpcGroup } from "effect/rpc";7 8-import { Description } from "./annotations.ts";8+import {9+ Description,10+ Destructive,11+ Idempotent,12+ NeedsApproval,13+ ReadOnly,14+} from "./annotations.ts";15 import type { Unauthenticated } from "./principal.ts";16 17 /** How a call can fail before its handler runs: in transit, or unauthenticated. */18 type CallError = RpcClientError.RpcClientError | Unauthenticated;22 unmodified lines41 export type ToolsOf<Rpcs extends Rpc.Any> = {42 readonly [R in Rpcs as R["_tag"]]: ToolOf<R>;43 };44 45+/** A tool as MCP's `tools/list` shows it to a client. */46+export interface ToolListing {47+ readonly name: string;48+ readonly description: string;49+ readonly annotations: {50+ readonly readOnlyHint: boolean;51+ readonly idempotentHint: boolean;52+ readonly destructiveHint: boolean;53+ readonly openWorldHint: boolean;54+ };55+ readonly inputSchema: JsonSchema.JsonSchema;56+ readonly outputSchema: JsonSchema.JsonSchema;57+}58+59+/**60+ * The definition a `$ref` names, read as Effect reads it: a URI fragment61+ * (percent-encoded, then `~1` and `~0` escaped) of the form `#/$defs/<key>`.62+ */63+const definitionKey = ($ref: string) => {64+ const tokens = JsonPointer.parseUriFragment($ref);65+66+ return tokens?.length === 2 && tokens[0] === "$defs" ? tokens[1] : undefined;67+};68+69+/**70+ * A schema as MCP lists it, derived the way `McpServer` derives a tool's:71+ * JSON Schema with an object root (a top-level `$ref` is inlined) and its72+ * definitions under `$defs`.73+ */74+export const toJsonSchema = (schema: Schema.Top): JsonSchema.JsonSchema => {75+ const { definitions, schema: root } = Schema.toJsonSchemaDocument(schema);76+77+ const key = Predicate.isString(root.$ref)78+ ? definitionKey(root.$ref)79+ : undefined;80+81+ const inlined = (key === undefined ? undefined : definitions[key]) ?? root;82+83+ return Object.keys(definitions).length === 084+ ? inlined85+ : { ...inlined, $defs: definitions };86+};87+88+/**89+ * The tools a toolkit lists, in its order, as a client reads them from90+ * `tools/list`. The generated MCP reference is written from this.91+ */92+export const listTools = <Tools extends Readonly<Record<string, Tool.Any>>>(93+ toolkit: Toolkit.Toolkit<Tools>94+): readonly ToolListing[] =>95+ // A toolkit keys each tool by its name.96+ Object.entries(toolkit.tools).map(([name, tool]) => ({97+ annotations: {98+ destructiveHint: Context.get(tool.annotations, Tool.Destructive),99+ idempotentHint: Context.get(tool.annotations, Tool.Idempotent),100+ openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),101+ readOnlyHint: Context.get(tool.annotations, Tool.Readonly),102+ },103+ description: Tool.getDescription(tool) ?? "",104+ inputSchema: toJsonSchema(tool.parametersSchema),105+ name,106+ outputSchema: toJsonSchema(tool.successSchema),107+ }));108+109 export interface ToolkitProjection<Rpcs extends Rpc.AnyWithProps, R> {110 readonly toolkit: Toolkit.Toolkit<ToolsOf<Rpcs>>;111 /** Handlers that answer each tool by calling its Rpc through the client. */112 readonly layer: Layer.Layer<Tool.HandlersFor<ToolsOf<Rpcs>>, never, R>;113 }114 115+/** What a tool says before a person-approved contract runs. */116+const ASKS_FIRST = " Asks a person first.";117+118+/**119+ * One contract as a tool. Its hints come from the contract's own annotations,120+ * and every tool says it reaches nothing outside the platform: MCP's defaults121+ * would read an unannotated tool as destructive and open-world.122+ */123+const toTool = (rpc: Rpc.AnyWithProps) => {124+ const description = Context.get(rpc.annotations, Description);45-const toTool = (rpc: Rpc.AnyWithProps) =>46- Tool.make(rpc._tag, {47- description: Context.get(rpc.annotations, Description),125+126+ return Tool.make(rpc._tag, {127+ description: Context.get(rpc.annotations, NeedsApproval)128+ ? `${description}${ASKS_FIRST}`129+ : description,130 failure: rpc.errorSchema,131 parameters: rpc.payloadSchema,132 success: rpc.successSchema,51- });133+ })134+ .annotate(Tool.Readonly, Context.get(rpc.annotations, ReadOnly))135+ .annotate(Tool.Idempotent, Context.get(rpc.annotations, Idempotent))136+ .annotate(Tool.Destructive, Context.get(rpc.annotations, Destructive))137+ .annotate(Tool.OpenWorld, false);138+};139 140 /**141 * Projects a group of contracts onto MCP tools. A tool call runs as a call to142 * its Rpc through `client`, so a refusal reaches the agent as the Rpc's own43 unmodified linesadded:packages/protocol/test/annotations.test.ts+30 added
123456789101112131415161718192021222324252627282930import { describe, expect, it } from "@effect/vitest";import { Context } from "effect";
import { Description, Destructive } from "../src/annotations.ts";import { Contracts } from "../src/contracts.ts";
const contracts = [...Contracts.requests.values()];
describe("every contract's annotations", () => { it("describe what the contract does", () => { const undescribed = contracts.flatMap((rpc) => Context.get(rpc.annotations, Description).trim() === "" ? [rpc._tag] : [] );
expect(contracts).not.toHaveLength(0); expect(undescribed).toStrictEqual([]); });
// The default is false, so a destructive contract that says nothing would // tell an agent it is safe: every contract must decide. it("say whether the contract is destructive, never leaving it to the default", () => { const silent = contracts.flatMap((rpc) => Context.getOrUndefined(rpc.annotations, Destructive) === undefined ? [rpc._tag] : [] );
expect(silent).toStrictEqual([]); });});modified:packages/protocol/test/mcp.test.ts+122 added-3 removed
1 import { describe, expect, it } from "@effect/vitest";2 import { Context, Effect, Schema } from "effect";3+import { Tool } from "effect/ai";4+import { Rpc, RpcGroup } from "effect/rpc";5 4-import { Description } from "../src/annotations.ts";5-import { Contracts, ListAsks, SubmitAnswer } from "../src/contracts.ts";6-import { AskId, CommitSha } from "../src/ids.ts";6+import { Description, NeedsApproval } from "../src/annotations.ts";7+import { Client, Contracts, ListAsks, SubmitAnswer } from "../src/contracts.ts";8+import { AskId, CommitSha, ProjectName } from "../src/ids.ts";9+import { listTools, toJsonSchema, toToolkit } from "../src/mcp.ts";10 import { StaleBase } from "../src/refusal.ts";11 import { ask, base, main, path } from "./examples.ts";12 import { serve } from "./mcp.ts";13 25 unmodified lines39 })40 ),41 });42 43+/** The hints a harness reads before it calls a tool. */44+const HintedTools = Schema.Struct({45+ tools: Schema.Array(46+ Schema.Struct({47+ annotations: Schema.Struct({48+ destructiveHint: Schema.Boolean,49+ idempotentHint: Schema.Boolean,50+ openWorldHint: Schema.Boolean,51+ readOnlyHint: Schema.Boolean,52+ }),53+ name: Schema.String,54+ })55+ ),56+});57+58+/** Each tool as a client reads it, with its schemas left as JSON. */59+const ListedTools = Schema.Struct({60+ tools: Schema.Array(61+ Schema.Struct({62+ annotations: Schema.Unknown,63+ description: Schema.String,64+ inputSchema: Schema.Unknown,65+ name: Schema.String,66+ outputSchema: Schema.Unknown,67+ })68+ ),69+});70+71+/** A struct of one commit, as JSON Schema writes it. */72+const receipt = {73+ additionalProperties: true,74+ properties: { main: { pattern: "^[0-9a-f]{40}$", type: "string" } },75+ required: ["main"],76+ type: "object",77+};78+79 describe("the contracts as MCP tools", () => {80 it.effect("lists each contract as a tool, its payload as the input", () =>81 Effect.gen(function* () {82 const mcp = yield* serve(quiet);20 unmodified lines103 ]);104 })105 );106 107+ it.effect(108+ "hints that listing asks only reads, and that an answer can be offered again",109+ () =>110+ Effect.gen(function* () {111+ const mcp = yield* serve(quiet);112+113+ const { tools } = yield* mcp.call("tools/list", {}, HintedTools);114+115+ expect(tools).toStrictEqual([116+ {117+ annotations: {118+ destructiveHint: false,119+ idempotentHint: true,120+ openWorldHint: false,121+ readOnlyHint: true,122+ },123+ name: "listAsks",124+ },125+ {126+ annotations: {127+ destructiveHint: false,128+ idempotentHint: true,129+ openWorldHint: false,130+ readOnlyHint: false,131+ },132+ name: "submitAnswer",133+ },134+ ]);135+ })136+ );137+138+ // The generated reference reads `listTools`, so it says what a client sees.139+ it.effect("lists each tool exactly as the reference describes it", () =>140+ Effect.gen(function* () {141+ const mcp = yield* serve(quiet);142+143+ const { tools } = yield* mcp.call("tools/list", {}, ListedTools);144+145+ expect(tools).toStrictEqual(146+ listTools(toToolkit(Contracts, Effect.service(Client)).toolkit)147+ );148+ })149+ );150+151+ it("inlines a named root schema, since MCP wants an object at the root", () => {152+ expect(153+ toJsonSchema(154+ Schema.Struct({ main: CommitSha }).annotate({ identifier: "Receipt" })155+ )156+ ).toStrictEqual({ ...receipt, $defs: { Receipt: receipt } });157+ });158+159+ // The pointer to "Answer receipt" is `#/$defs/Answer%20receipt`.160+ it("inlines a named root whose pointer is percent-encoded", () => {161+ expect(162+ toJsonSchema(163+ Schema.Struct({ main: CommitSha }).annotate({164+ identifier: "Answer receipt",165+ })166+ )167+ ).toStrictEqual({ ...receipt, $defs: { "Answer receipt": receipt } });168+ });169+170+ it("tells the agent a person approves a contract that needs approval", () => {171+ class Abandon extends Rpc.make("abandon", {172+ payload: { project: ProjectName },173+ })174+ .annotate(Description, "Abandon a project.")175+ .annotate(NeedsApproval, true) {}176+177+ const { toolkit } = toToolkit(178+ RpcGroup.make(Abandon),179+ Effect.die("a listing calls no tool")180+ );181+182+ expect(Tool.getDescription(toolkit.tools.abandon)).toBe(183+ "Abandon a project. Asks a person first."184+ );185+ });186+187 it.effect("returns a refusal as JSON that keeps its tag", () =>188 Effect.gen(function* () {189 const refusal = new StaleBase({ base, conflicts: [path], main });190 67 unmodified linesmodified:scripts/lib/gen.ts+473 added-14 removed
2 unmodified lines3 * one schema in `packages/protocol`, and how the disk differs from it.4 * `scripts/gen.ts` writes or checks; tests import this directly.5 */6 import { Brand } from "@repo/brand";7-import { groups } from "@repo/protocol/refusal";8-import { Exit, Predicate, SchemaAST, SchemaRepresentation } from "effect";9-import type { Schema } from "effect";7+import {8+ Cli,9+ Client,10+ Contracts,11+ Description,12+ Destructive,13+ Idempotent,14+ NeedsApproval,15+ ReadOnly,16+ SurfaceName,17+ Surfaces,18+} from "@repo/protocol/contracts";19+import { AskId, CommitSha, RepoPath } from "@repo/protocol/ids";20+import { listTools, toJsonSchema, toToolkit } from "@repo/protocol/mcp";21+import type { ToolListing } from "@repo/protocol/mcp";22+import {23+ AskFull,24+ AttemptsExhausted,25+ CapReached,26+ ChecksFailed,27+ ClaimLapsed,28+ Flake,29+ groups,30+ HeldBackFailed,31+ IncompleteBrief,32+ LayerContentInPublicTree,33+ NoAsk,34+ NotClaimed,35+ NotRedFirst,36+ NotVouched,37+ OutOfScope,38+ PostureChange,39+ PrivatePathInPublicTree,40+ Refusal,41+ RepoBusy,42+ SecretInOutput,43+ StaleBase,44+ TouchedJudge,45+ VerifierBlocked,46+ WeakCheck,47+ Weakened,48+} from "@repo/protocol/refusal";49+import { explain } from "@repo/protocol/render";50+import {51+ Array as Arr,52+ Context,53+ DateTime,54+ Effect,55+ Exit,56+ JsonSchema,57+ Order,58+ Predicate,59+ Schema,60+ SchemaAST,61+ SchemaRepresentation,62+} from "effect";63 64 /**12- * The union `refusals.md` is rendered from. Tests in `packages/config` read it13- * here: that package takes no `@repo/*` dependency, since every package14- * dev-depends on it and the edge would be a cycle.65+ * The union and the group the reference is rendered from. Tests in66+ * `packages/config` read them here: that package takes no `@repo/*`67+ * dependency, since every package dev-depends on it and the edge would be a68+ * cycle.69 */70 export { Refusal } from "@repo/protocol/refusal";71 72+export { Contracts } from "@repo/protocol/contracts";73+74+/**75+ * `docs/reference/commands.json`: every command the CLI has. `projected`76+ * commands come from a contract; W4 merges in the hand-written `local` ones.77+ */78+export const CommandCatalog = Schema.Struct({79+ commands: Schema.Array(80+ Schema.Struct({81+ contract: Schema.optionalKey(Schema.String),82+ description: Schema.String,83+ destructive: Schema.Boolean,84+ idempotent: Schema.Boolean,85+ name: Schema.NonEmptyString,86+ needsApproval: Schema.Boolean,87+ path: Schema.Array(Schema.NonEmptyString),88+ // The payload as JSON Schema: the same schema MCP lists as the input.89+ payloadSchema: Schema.Json,90+ positional: Schema.Array(Schema.String),91+ readOnly: Schema.Boolean,92+ source: Schema.Literals(["projected", "local"]),93+ surfaces: Schema.Array(SurfaceName),94+ })95+ ),96+ version: Schema.Literal(1),97+});98+99+export type CommandCatalog = typeof CommandCatalog.Type;100+101+type Command = CommandCatalog["commands"][number];102+103 export interface GeneratedFile {104 readonly path: string;105 readonly content: string;106 }13 unmodified lines120 "skills",121 "plugins",122 ];123 124+const contracts = [...Contracts.requests.values()];125+126+const byPath = Order.mapInput(Order.String, (file: GeneratedFile) => file.path);127+128+const byKey = Order.mapInput(129+ Order.String,130+ ([key]: readonly [string, Schema.Json]) => key131+);132+133+/** Effect's JSON Schema output, checked as JSON where it enters gen. */134+const toJson = Schema.decodeUnknownSync(Schema.Json);135+136+const isJsonArray = (value: Schema.Json): value is Schema.JsonArray =>137+ Array.isArray(value);138+139+const isJsonObject = (value: Schema.Json): value is Schema.JsonObject =>140+ Predicate.isObject(value);141+142+/** The same JSON with every object's keys sorted, so no byte depends on insertion order. */143+const sortKeys = (value: Schema.Json): Schema.Json => {144+ if (isJsonArray(value)) {145+ return value.map(sortKeys);146+ }147+148+ if (isJsonObject(value)) {149+ return Object.fromEntries(150+ Arr.sort(Object.entries(value), byKey).map(([key, item]) => [151+ key,152+ sortKeys(item),153+ ])154+ );155+ }156+157+ return value;158+};159+160+/** JSON as gen writes it: sorted keys and two-space indents. */161+const printJson = (value: Schema.Json) =>162+ JSON.stringify(sortKeys(value), null, 2);163+164+/** A Markdown page: its lines joined, ending in exactly one newline. */165+const page = (lines: readonly string[]) =>166+ `${lines.join("\n").replace(/\n+$/u, "")}\n`;167+168+const yesNo = (value: boolean) => (value ? "yes" : "no");169+170+const generatedBy = (source: string, edit: string) =>171+ `<!-- Generated by \`bun run gen\` from ${source}. Edit ${edit}, not this file: \`bun run gen:check\` fails when they differ. -->`;172+173+// --- refusals.md ------------------------------------------------------------174+175 type Member = (typeof groups)[number]["members"][number];176 177+const ask = AskId.make("fix-parser");178+179+const base = CommitSha.make("1111111111111111111111111111111111111111");180+181+const main = CommitSha.make("2222222222222222222222222222222222222222");182+183+const path = RepoPath.make("src/a.ts");184+185+/**186+ * One example of every refusal, for the reason each section quotes. Keyed by187+ * tag, so a refusal added to the union fails the typecheck until it has one.188+ */189+const examples = {190+ AskFull: new AskFull({ ask }),191+ AttemptsExhausted: new AttemptsExhausted({192+ area: "parser",193+ resetsAt: DateTime.makeUnsafe("2026-10-07T00:00:00Z"),194+ }),195+ CapReached: new CapReached({ cap: 3 }),196+ ChecksFailed: new ChecksFailed({197+ lane: "test",198+ logRef: "logs/7",199+ next: "bun test src/a.test.ts",200+ }),201+ ClaimLapsed: ClaimLapsed.of(ask),202+ Flake: new Flake({ lane: "test" }),203+ HeldBackFailed: new HeldBackFailed({ area: "parser", suite: "edge-cases" }),204+ IncompleteBrief: new IncompleteBrief({ missing: ["territory"] }),205+ LayerContentInPublicTree: new LayerContentInPublicTree({ paths: [path] }),206+ NoAsk: new NoAsk({}),207+ NotClaimed: NotClaimed.of(ask),208+ NotRedFirst: new NotRedFirst({}),209+ NotVouched: new NotVouched({}),210+ OutOfScope: new OutOfScope({ paths: [path] }),211+ PostureChange: new PostureChange({ from: "open", to: "openCore" }),212+ PrivatePathInPublicTree: new PrivatePathInPublicTree({ paths: [path] }),213+ RepoBusy: new RepoBusy({}),214+ SecretInOutput: new SecretInOutput({ item: "PAYMENTS_KEY", where: "output" }),215+ StaleBase: new StaleBase({ base, conflicts: [path], main }),216+ TouchedJudge: new TouchedJudge({ paths: [path] }),217+ VerifierBlocked: new VerifierBlocked({}),218+ WeakCheck: new WeakCheck({ weakness: "no assertion" }),219+ Weakened: new Weakened({220+ weakening: { marker: "it.skip", reason: "flaky on CI" },221+ }),222+} satisfies {223+ readonly [Tag in Refusal["_tag"]]: Extract<Refusal, { readonly _tag: Tag }>;224+};225+226+/** Each example's reason, in the renderer's words, by tag. */227+const reasons = new Map<string, string>(228+ Object.values(examples).map((refusal) => [229+ refusal._tag,230+ (explain([refusal])[0] ?? "").slice(`${refusal._tag}: `.length),231+ ])232+);233+234 // Every refusal carries these; the page explains them once, at the top.235 const envelope = new Set(["_tag", "at", "next", "retryable"]);236 237 /** A schema's type as it travels on the wire, in TypeScript's notation. */16 unmodified lines254 const section = (member: Member) => {255 const fields = Object.entries<Schema.Top>(member.fields);256 const { ast: retryable } = member.fields.retryable;257 const next = constructorDefault(member.fields.next.ast);258+ const reason = reasons.get(member.identifier);259 260 const own = fields.flatMap(([name, field]) =>261 envelope.has(name)262 ? []7 unmodified lines270 "",271 `- Retryable: ${SchemaAST.isLiteral(retryable) && retryable.literal === true ? "yes" : "no"}`,272 `- Next: ${Predicate.isString(next) ? `\`${next}\`` : "set when it is raised"}`,273 ...(own.length === 0 ? ["- Fields: none"] : ["- Fields:", ...own]),274+ ...(reason === undefined ? [] : [`- Reason, for example: ${reason}`]),275 "",276 ];277 };278 279 const refusalsDoc = (): GeneratedFile => ({85- content: [86- "<!-- Generated by `bun run gen` from packages/protocol/src/refusal.ts. Edit the union, not this file: `bun run gen:check` fails when they differ. -->",280+ content: page([281+ generatedBy("packages/protocol/src/refusal.ts", "the union"),282 "",283 "# Refusals",284 "",285 `Every way the platform says no is one refusal from one closed union. The same refusal reaches git's \`remote:\` lines, the \`${Brand.cli}\` CLI and MCP. Every refusal carries:`,2 unmodified lines288 "- `retryable`: whether trying again can help, fixed for each refusal.",289 "- `next`: the command to run next.",290 "- `at` (optional): the `path` and `line` it points at.",291 "",97- "No refusal has a message. Shape refusals accumulate, so one push hears about every one at once. Field types are given as they travel on the wire.",292+ "No refusal has a message. Shape refusals accumulate, so one push hears about every one at once. Field types are given as they travel on the wire. Each reason is what the renderer says for one example of that refusal.",293 "",294 ...groups.flatMap((group) => [295 `## ${group.name}`,296 "",297 ...group.members.flatMap(section),298 ]),104- ]105- .join("\n")106- .replace(/\n+$/u, "\n"),299+ ]),300 path: "docs/reference/refusals.md",301 });302 303+// --- mcp-tools.md -------------------------------------------------------------304+305+/** The tools MCP serves, read from the same projection the servers use. */306+const tools = (): readonly ToolListing[] =>307+ listTools(toToolkit(Contracts, Effect.service(Client)).toolkit);308+309+const jsonBlock = (schema: JsonSchema.JsonSchema) => [310+ "```json",311+ printJson(toJson(schema)),312+ "```",313+];314+315+const toolSection = (tool: ToolListing) => [316+ `## ${tool.name}`,317+ "",318+ tool.description,319+ "",320+ "| Hint | Value |",321+ "| --- | --- |",322+ ...Arr.sort(Object.entries(tool.annotations), byKey).map(323+ ([hint, value]) => `| \`${hint}\` | \`${String(value)}\` |`324+ ),325+ "",326+ "### Input",327+ "",328+ ...jsonBlock(tool.inputSchema),329+ "",330+ "### Output",331+ "",332+ ...jsonBlock(tool.outputSchema),333+ "",334+];335+336+const mcpToolsDoc = (): GeneratedFile => ({337+ content: page([338+ generatedBy(339+ "packages/protocol/src/contracts.ts through `toToolkit` in packages/protocol/src/mcp.ts",340+ "the contracts"341+ ),342+ "",343+ "# MCP tools",344+ "",345+ `Each contract is one MCP tool, named by its tag, as \`tools/list\` shows it over \`/mcp\` and over stdio from \`${Brand.cli} mcp\`. A tool's input is the contract's payload and its output is the contract's success. A refusal comes back as the tool's error result: the refusal as JSON, \`_tag\` and all (see [refusals.md](refusals.md)).`,346+ "",347+ "The hints come from each contract's own annotations. No tool reaches anything outside the platform, so `openWorldHint` is always false.",348+ "",349+ ...tools().flatMap(toolSection),350+ ]),351+ path: "docs/reference/mcp-tools.md",352+});353+354+// --- commands.json and cli.md -------------------------------------------------355+356+/** The CLI commands the contracts project onto, in the group's order. */357+const catalog = (): CommandCatalog => ({358+ commands: contracts.flatMap((rpc): readonly Command[] => {359+ const surfaces = Context.get(rpc.annotations, Surfaces);360+361+ if (!surfaces.includes("cli")) {362+ return [];363+ }364+365+ const cli = Context.get(rpc.annotations, Cli);366+ const name = cli.name ?? rpc._tag;367+368+ return [369+ {370+ contract: rpc._tag,371+ description: Context.get(rpc.annotations, Description),372+ destructive: Context.get(rpc.annotations, Destructive),373+ idempotent: Context.get(rpc.annotations, Idempotent),374+ name,375+ needsApproval: Context.get(rpc.annotations, NeedsApproval),376+ path: name.split(" "),377+ payloadSchema: toJson(toJsonSchema(rpc.payloadSchema)),378+ positional: cli.positional ?? [],379+ readOnly: Context.get(rpc.annotations, ReadOnly),380+ source: "projected",381+ surfaces,382+ },383+ ];384+ }),385+ version: 1,386+});387+388+/** What cli.md reads from a payload's JSON Schema: its fields, and which are required. */389+const PayloadFields = Schema.Struct({390+ properties: Schema.optionalKey(Schema.Record(Schema.String, Schema.Json)),391+ required: Schema.optionalKey(Schema.Array(Schema.String)),392+});393+394+const FieldSchema = Schema.Struct({395+ enum: Schema.optionalKey(Schema.Array(Schema.Json)),396+ type: Schema.optionalKey(Schema.String),397+});398+399+const decodePayloadFields = Schema.decodeUnknownSync(PayloadFields);400+401+const isFieldSchema = Schema.is(FieldSchema);402+403+/** What a field of each JSON type takes on the command line. */404+const kinds = new Map([405+ ["boolean", "nothing (a switch)"],406+ ["integer", "a number"],407+ ["number", "a number"],408+ ["string", "text"],409+]);410+411+/** What a field takes on the command line, in the words `--help` uses. */412+const takes = (field: Schema.Json) => {413+ if (!isFieldSchema(field)) {414+ return "JSON";415+ }416+417+ if (field.enum !== undefined) {418+ return field.enum.map((value) => JSON.stringify(value)).join(" | ");419+ }420+421+ return (422+ (field.type === undefined ? undefined : kinds.get(field.type)) ?? "JSON"423+ );424+};425+426+const commandSection = (command: Command) => {427+ const { properties = {}, required = [] } = decodePayloadFields(428+ command.payloadSchema429+ );430+431+ const positional = new Set(command.positional);432+ const needed = new Set(required);433+434+ const flags = Arr.sort(Object.entries(properties), byKey).filter(435+ ([field]) => !positional.has(field)436+ );437+438+ const usage = [439+ Brand.cli,440+ ...command.path,441+ ...command.positional.map((field) => `<${field}>`),442+ ...flags.map(([field]) =>443+ needed.has(field) ? `--${field} <${field}>` : `[--${field} <${field}>]`444+ ),445+ ].join(" ");446+447+ const rows = [448+ ...command.positional.map(449+ (field) =>450+ `| \`<${field}>\` | ${takes(properties[field] ?? null)} | ${yesNo(needed.has(field))} |`451+ ),452+ ...flags.map(453+ ([field, schema]) =>454+ `| \`--${field}\` | ${takes(schema)} | ${yesNo(needed.has(field))} |`455+ ),456+ ];457+458+ return [459+ `## \`${Brand.cli} ${command.path.join(" ")}\``,460+ "",461+ command.description,462+ "",463+ "```sh",464+ usage,465+ "```",466+ "",467+ ...(command.contract === undefined468+ ? []469+ : [`- Contract: \`${command.contract}\``]),470+ `- Reads only: ${yesNo(command.readOnly)}`,471+ `- Idempotent: ${yesNo(command.idempotent)}`,472+ `- Destructive: ${yesNo(command.destructive)}`,473+ `- Needs approval: ${yesNo(command.needsApproval)}`,474+ `- Surfaces: ${command.surfaces.join(", ")}`,475+ "",476+ ...(rows.length === 0477+ ? ["It takes no arguments."]478+ : ["| Argument | Takes | Required |", "| --- | --- | --- |", ...rows]),479+ "",480+ ];481+};482+483+/** cli.md is rendered from the catalog commands.json holds, so the two agree. */484+const cliDoc = (commands: CommandCatalog): GeneratedFile => ({485+ content: page([486+ generatedBy(487+ "packages/protocol/src/contracts.ts through commands.json",488+ "the contracts"489+ ),490+ "",491+ "# CLI",492+ "",493+ `Each command below is a contract projected onto the \`${Brand.cli}\` CLI: the payload's fields become flags, or positional arguments where the contract names them. Every command also takes \`--json\`, which prints the encoded result, or the refusal, as JSON. [commands.json](commands.json) holds the same catalog as data.`,494+ "",495+ ...commands.commands.flatMap(commandSection),496+ ]),497+ path: "docs/reference/cli.md",498+});499+500+const commandsJson = (commands: CommandCatalog): GeneratedFile => ({501+ content: `${printJson(commands)}\n`,502+ path: "docs/reference/commands.json",503+});504+505+// --- protocol.schema.json -----------------------------------------------------506+507+/**508+ * One JSON Schema document for the whole protocol: a definition for each509+ * contract's payload, success and error, and for the refusal union, sharing510+ * the definitions they name.511+ */512+const protocolSchema = (): GeneratedFile => {513+ const roots: Arr.NonEmptyReadonlyArray<readonly [string, Schema.Top]> = [514+ ["Refusal", Refusal],515+ ...contracts.flatMap((rpc) => [516+ [`${rpc._tag}.payload`, rpc.payloadSchema] as const,517+ [`${rpc._tag}.success`, rpc.successSchema] as const,518+ [`${rpc._tag}.error`, rpc.errorSchema] as const,519+ ]),520+ ];521+522+ // Each root as JSON encodes it, as `Schema.toJsonSchemaDocument` does.523+ const { definitions, schemas } =524+ SchemaRepresentation.toJsonSchemaMultiDocument(525+ SchemaRepresentation.toRepresentations(526+ Arr.map(roots, ([, schema]) => Schema.toCodecJson(schema).ast)527+ )528+ );529+530+ const clash = roots.find(([name]) => Object.hasOwn(definitions, name));531+532+ if (clash !== undefined) {533+ throw new Error(534+ `protocol.schema.json: the root ${clash[0]} has the name of a shared definition`535+ );536+ }537+538+ const document = toJson({539+ $comment:540+ "Generated by `bun run gen` from packages/protocol. Edit the contracts, not this file.",541+ $defs: {542+ ...definitions,543+ ...Object.fromEntries(544+ roots.map(([name], index) => [name, schemas[index] ?? {}])545+ ),546+ },547+ $schema: JsonSchema.META_SCHEMA_URI_DRAFT_2020_12,548+ title: `The ${Brand.name} protocol`,549+ });550+551+ return {552+ content: `${printJson(document)}\n`,553+ path: "docs/reference/protocol.schema.json",554+ };555+};556+557 /** Every file gen writes, sorted by path. */111-export const generate = (): readonly GeneratedFile[] =>112- [refusalsDoc()].toSorted((a, b) => a.path.localeCompare(b.path));558+export const generate = (): readonly GeneratedFile[] => {559+ const commands = catalog();560 561+ return Arr.sort(562+ [563+ cliDoc(commands),564+ commandsJson(commands),565+ mcpToolsDoc(),566+ protocolSchema(),567+ refusalsDoc(),568+ ],569+ byPath570+ );571+};572+573 /**574 * How the files on disk under the owned roots differ from what gen would575 * write: changed, not there yet, or not gen's at all.576 */23 unmodified lines