package wire import ( "encoding/base64" "encoding/json" "fmt" "regexp" "slices" "strings" "unicode" "unicode/utf8" ) // The Design specialist's wire (spec 2026-11-28-dynamic-specialists.md, // sections 1 and 3; ProtocolDesign): a maker step's specialist binding on // its dispatch, the page_render lease check, the captures a Design step // names in its report's options, and the render_file chunks that carry // them. Both ends validate with the functions here. // Bounds of a Design report and its captures. const ( // MaxDesignOptions and MaxDesignCaptures bound a report's options and // the captures named across all of them. MaxDesignOptions = 4 MaxDesignCaptures = 12 // MaxOptionName bounds an option's name, in bytes. MaxOptionName = 60 // MaxCaptureBytes is the most one capture holds (spec: re-encoded // to at most 2 MB); render_page writes none larger. MaxCaptureBytes = 2 << 20 // RenderFileChunk is one render_file frame's share of a capture, as // research_file's; MaxRenderFileChunks the most a capture needs. RenderFileChunk = ResearchFileChunk MaxRenderFileChunks = (MaxCaptureBytes + RenderFileChunk - 1) / RenderFileChunk // MaxBindingCapabilities bounds a binding's capabilities. MaxBindingCapabilities = 8 // MaxSpecialistBrief bounds a dispatch's SpecialistBrief: the menu's // bound on a specialist's brief (specialist.MaxBrief). MaxSpecialistBrief = 2 << 10 // MaxCaptureWidth and MaxCaptureHeight bound a capture's pixels: the // widest viewport (desktop) and a full page's clip (spec: full pages // capped at 10,000 px), as render_page writes them. MaxCaptureWidth = 1440 MaxCaptureHeight = 10000 ) // A Design step that waits, by placement: PlacementDesign while the // runner it would run on cannot run Design (below ProtocolDesign, its // page renderer not ok, or no Claude connection of the person there); // PlacementDesignLimit while the task's autonomy limit holds it for its // person (HoldDesignLimit, through the held-step card). const ( PlacementDesign = "design_runner" PlacementDesignLimit = "design_limit" ) // HoldDesignLimit is the hold, and the need, of a Design step held by the // autonomy limit: Design ran DesignRunLimit attempts of the task since // its person last acted on it. The instance sets it; a runner never // reports it (it is not in HoldReasons). const HoldDesignLimit = "design_limit" // DesignRunLimit is how many Design attempts a task runs without a word // from its person (spec section 4, Budget). const DesignRunLimit = 3 // CardMakerRemoved asks a task's creator, once its maker specialist was // removed and every attempt of its steps has ended with its end proven, // whether to hand the task to Engineering; ChoiceToEngineering is its one // answer. const ( CardMakerRemoved = "maker_removed" ChoiceToEngineering = "to_engineering" ) // DesignOption is one mockup option of a Design step's candidate: the // name the person will use for it and the captures that show it. type DesignOption struct { Name string `json:"name"` Captures []DesignCapture `json:"captures"` } // DesignCapture is one capture an option names: its render_page file id // (the name under /render/), the SHA-256 of its PNG and the digest of the // exported tree it was rendered from (a diff carries work's). type DesignCapture struct { ID string `json:"id"` SHA256 string `json:"sha256"` TreeDigest string `json:"tree_digest"` } // StepDesign is what a done Design attempt kept, on the task's read // shape only: the options its final report named, in its order, each // with the captures the instance kept for it (a capture is kept only // once the report validated it). type StepDesign struct { Attempt int64 `json:"attempt"` Options []StepDesignOption `json:"options"` } // StepDesignOption is one option and its kept captures, in the report's // order. Name is the specialist's label for it. type StepDesignOption struct { Name string `json:"name"` Captures []StepCapture `json:"captures"` } // StepCapture is one kept capture: ID is its task file (GET // /tasks/{task}/files/{id}), CaptureID the render_page file it was // (its tree is in the name), with its size and pixel size. type StepCapture struct { ID string `json:"id"` CaptureID string `json:"capture_id"` Size int64 `json:"size"` Width int `json:"width"` Height int `json:"height"` } // CaptureTree is the tree a capture id names: base, work or diff ("" for // an id that is not a capture's). func CaptureTree(id string) string { m := captureID.FindStringSubmatch(id) if m == nil { return "" } return m[2] } // A Design step's render audit (spec section 4, "Audit": each render's // counts and timing on the step): one record per accepted render_page // call, kept by the runner on the step and carried on its final report // (StepReport.Renders, ProtocolDesign), as plain data. const ( // MaxRenderAudits is a step's render_page calls (renderpage.MaxCalls). MaxRenderAudits = 20 // MaxRenderPages is one call's pages (render.MaxPages). MaxRenderPages = 6 // MaxRenderAuditMS bounds a record's duration: well past the call's // 60 seconds, so a slow end still records. MaxRenderAuditMS = 10 * 60 * 1000 ) // A record's tree: base, work, or compare (both, then their diffs). const ( RenderTreeBase = "base" RenderTreeWork = "work" RenderTreeCompare = "compare" ) // A record's outcome: rendered, a refusal's fixed code, or cancelled // (the step ended during the call). const ( RenderRendered = "rendered" RenderCancelled = "cancelled" ) // RenderOutcomes are every outcome a record may have: rendered, the // spec's seven codes and the plan's two (renderpage.Codes), cancelled. var RenderOutcomes = []string{RenderRendered, "renderer_missing", "renderer_mismatch", "no_site", "too_many", "busy", "timeout", "crashed", "secrets", "scanner", RenderCancelled} // RenderAudit is one accepted render_page call: its number in the step // (1 to MaxRenderAudits), the attempt it ran in, its tree, its pages, // the captures it counted against the step's 60 (pages, twice for a // compare), the files it wrote (its captures and a compare's diffs; none // unless rendered), how long it took and how it ended. type RenderAudit struct { Call int `json:"call"` Attempt int64 `json:"attempt"` Tree string `json:"tree"` Pages int `json:"pages"` Captures int `json:"captures"` Files int `json:"files"` DurationMS int64 `json:"duration_ms"` Outcome string `json:"outcome"` } // ValidRenderAudits strictly bounds a report's render records for its // attempt: at most MaxRenderAudits, each call numbered 1 to // MaxRenderAudits and above the one before, each attempt from 1, never // below the one before nor above attempt (a failover keeps the step's // calls), a known tree and outcome, 1 to MaxRenderPages pages, captures // exactly its pages (twice for a compare), files only for a rendered // call and then its captures and a compare's diffs (one a page), and a // duration of 0 to MaxRenderAuditMS. func ValidRenderAudits(recs []RenderAudit, attempt int64) error { if len(recs) > MaxRenderAudits { return fmt.Errorf("%w: %d render records", ErrStrict, len(recs)) } call, at := 0, int64(1) for _, r := range recs { trees := 1 switch r.Tree { case RenderTreeBase, RenderTreeWork: case RenderTreeCompare: trees = 2 default: return fmt.Errorf("%w: render %d's tree %q", ErrStrict, r.Call, r.Tree) } files := 0 if r.Outcome == RenderRendered { files = r.Pages * trees if trees == 2 { files += r.Pages } } switch { case r.Call <= call || r.Call > MaxRenderAudits: return fmt.Errorf("%w: render call %d after %d", ErrStrict, r.Call, call) case r.Attempt < at || r.Attempt > attempt: return fmt.Errorf("%w: render %d's attempt %d", ErrStrict, r.Call, r.Attempt) case r.Pages < 1 || r.Pages > MaxRenderPages || r.Captures != r.Pages*trees || r.Files != files: return fmt.Errorf("%w: render %d's counts", ErrStrict, r.Call) case r.DurationMS < 0 || r.DurationMS > MaxRenderAuditMS: return fmt.Errorf("%w: render %d's duration", ErrStrict, r.Call) case !slices.Contains(RenderOutcomes, r.Outcome): return fmt.Errorf("%w: render %d's outcome %q", ErrStrict, r.Call, r.Outcome) } call, at = r.Call, r.Attempt } return nil } // RenderFile is one chunk of a named capture, runner to instance, sent // before the step's final report. Index counts from 0 to Total-1; SHA256 // and Size are the whole file's. type RenderFile struct { TaskID string `json:"task_id"` StepID string `json:"step_id"` Attempt int64 `json:"attempt"` CaptureID string `json:"capture_id"` Index int `json:"index"` Total int `json:"total"` Size int64 `json:"size"` SHA256 string `json:"sha256"` Data string `json:"data"` } var ( // captureID is render_page's file name: --.png, call // and n from 1 with no leading zero (renderpage.Tool). captureID = regexp.MustCompile(`^([1-9][0-9]?)-(base|work|diff)-([1-9][0-9]?)\.png$`) // The instance's ids (newID): sp_ and p_ then lower-case base32. specialistID = regexp.MustCompile(`^sp_[a-z0-9]{1,40}$`) projectID = regexp.MustCompile(`^p_[a-z0-9]{1,40}$`) // A menu profile id (research-v1, design-review-v1) and capability // id (web.research, page.render). profileID = regexp.MustCompile(`^[a-z][a-z0-9]*(-[a-z0-9]+)*-v[1-9][0-9]{0,2}$`) capabilityID = regexp.MustCompile(`^[a-z]+(\.[a-z]+)+$`) ) // ValidCaptureID is a render_page capture's file id. func ValidCaptureID(id string) bool { return captureID.MatchString(id) } // ValidOptions strictly bounds a Design report's options: at most // MaxDesignOptions, at most MaxDesignCaptures captures across them, each // option's name a plain label (validOptionName) said once (case folded), // each capture's id a capture id named once across all options, its // SHA-256 and tree digest lower-case hex SHA-256. An option may name no // capture; no options at all is valid. Whether the captures were staged // is the receiver's check. func ValidOptions(opts []DesignOption) error { if len(opts) > MaxDesignOptions { return fmt.Errorf("%w: %d options", ErrStrict, len(opts)) } names, ids := map[string]bool{}, map[string]bool{} for _, o := range opts { folded := strings.ToLower(o.Name) if !validOptionName(o.Name) || names[folded] { return fmt.Errorf("%w: option name %q", ErrStrict, o.Name) } names[folded] = true for _, c := range o.Captures { if !ValidCaptureID(c.ID) || ids[c.ID] || !ValidSHA256(c.SHA256) || !ValidSHA256(c.TreeDigest) { return fmt.Errorf("%w: capture %q", ErrStrict, c.ID) } ids[c.ID] = true } } if len(ids) > MaxDesignCaptures { return fmt.Errorf("%w: %d captures", ErrStrict, len(ids)) } return nil } // validOptionName: at most MaxOptionName bytes; letters, digits, spaces, // hyphens and apostrophes only (so valid UTF-8: a bad byte reads as // U+FFFD, not a letter); never two spaces together; starting and ending // with a letter or digit (so never empty). Nothing that reads as markup, // a path, a control or a format character. func validOptionName(s string) bool { if len(s) > MaxOptionName || strings.Contains(s, " ") { return false } for _, r := range s { if !word(r) && r != ' ' && r != '-' && r != '\'' { return false } } first, _ := utf8.DecodeRuneInString(s) last, _ := utf8.DecodeLastRuneInString(s) return word(first) && word(last) } func word(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) } // ValidRenderFile bounds one render_file chunk: its task, step (at most // 128 bytes each) and attempt; a capture id; a whole file of at most // MaxCaptureBytes in exactly the chunks its size needs (so at least one // byte: an empty file has no chunk to be); and this chunk's data, strict // padded base64, exactly its share of the file. func ValidRenderFile(v RenderFile) bool { if v.TaskID == "" || len(v.TaskID) > 128 || v.StepID == "" || len(v.StepID) > 128 || v.Attempt < 1 || !ValidCaptureID(v.CaptureID) || !ValidSHA256(v.SHA256) { return false } if v.Size > MaxCaptureBytes || int64(v.Total) != (v.Size+RenderFileChunk-1)/RenderFileChunk || v.Index < 0 || v.Index >= v.Total { return false } share := int64(RenderFileChunk) if v.Index == v.Total-1 { share = v.Size - int64(v.Total-1)*RenderFileChunk } data, err := base64.StdEncoding.Strict().DecodeString(v.Data) return err == nil && int64(len(data)) == share } // ValidSpecialistBinding: a dispatch carries no specialist binding at all // (Engineering itself, and every other step), or a whole one: a // specialist id of the instance's shape, a revision from 1, a project id // or "" for the team, a profile id of the menu's shape, 1 to // MaxBindingCapabilities distinct capability ids, and a brief of at most // MaxSpecialistBrief bytes of text. Whether the binding // is still granted is the instance's check. func ValidSpecialistBinding(d *DispatchCommand) bool { if !hasBinding(d) { return true } if !specialistID.MatchString(d.SpecialistID) || d.SpecialistRevision < 1 || d.SpecialistProject != "" && !projectID.MatchString(d.SpecialistProject) || len(d.Profile) > 40 || !profileID.MatchString(d.Profile) { return false } if len(d.Capabilities) < 1 || len(d.Capabilities) > MaxBindingCapabilities { return false } if len(d.SpecialistBrief) > MaxSpecialistBrief || !utf8.ValidString(d.SpecialistBrief) || strings.ContainsRune(d.SpecialistBrief, 0) { return false } seen := map[string]bool{} for _, c := range d.Capabilities { if len(c) > 40 || !capabilityID.MatchString(c) || seen[c] { return false } seen[c] = true } return true } // hasBinding: any part of a specialist binding is set. func hasBinding(d *DispatchCommand) bool { return d.SpecialistID != "" || d.SpecialistRevision != 0 || d.SpecialistProject != "" || d.Profile != "" || len(d.Capabilities) > 0 || d.Explore || d.SpecialistBrief != "" } // downgradeDesign makes a frame speak a protocol below ProtocolDesign. A // dispatch with any part of a specialist binding is refused: an older // runner would run the step as plain Engineering, outside its grant. So // are a page_render check (an older instance would ack it as a start // authorization, without the grant check), a render_file chunk, and a // propose_specialist call for one project (an older instance has no // scope, so it would propose for the whole team); a proposal's empty // project, the team's, is dropped. A report's options and render // records are dropped. It reports whether anything changed. func downgradeDesign(body any, protocol int) (bool, error) { switch v := body.(type) { case *DispatchCommand: if hasBinding(v) { return false, fmt.Errorf("%w: a specialist's dispatch at protocol %d", ErrProtocol, protocol) } case *LeaseCheck: if v.Purpose == LeasePurposeRender { return false, fmt.Errorf("%w: a render check at protocol %d", ErrProtocol, protocol) } case *RenderFile: return false, fmt.Errorf("%w: render_file at protocol %d", ErrProtocol, protocol) case *StepReport: if v.Options != nil || v.Renders != nil { v.Options, v.Renders = nil, nil return true, nil } case *ToolCall: return withoutTeamProject(v, protocol) } return false, nil } // ProjectProposal reports whether a call is propose_specialist for one // project: its project is anything but "" (the team's) or absent. The // runner answers such a call itself below ProtocolDesign. func ProjectProposal(v *ToolCall) bool { project, ok := proposalProject(v) return ok && string(project) != `""` } // proposalProject is a propose_specialist call's project as sent, and // whether it has one. func proposalProject(v *ToolCall) (json.RawMessage, bool) { if v.Name != ToolProposeSpecialist { return nil, false } var args map[string]json.RawMessage if json.Unmarshal(v.Args, &args) != nil { return nil, false } project, ok := args["project"] return project, ok } // withoutTeamProject drops propose_specialist's project when it is "" // (the team's, all an older instance knows) and refuses the call when it // names anything else. func withoutTeamProject(v *ToolCall, protocol int) (bool, error) { if _, ok := proposalProject(v); !ok { return false, nil } if ProjectProposal(v) { return false, fmt.Errorf("%w: a proposal for one project at protocol %d", ErrProtocol, protocol) } var args map[string]json.RawMessage if err := json.Unmarshal(v.Args, &args); err != nil { return false, err } delete(args, "project") raw, err := json.Marshal(args) if err != nil { return false, err } v.Args = raw return true, nil }