oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package wire
2
3import (
4 "encoding/base64"
5 "encoding/json"
6 "fmt"
7 "regexp"
8 "slices"
9 "strings"
10 "unicode"
11 "unicode/utf8"
12)
13
14// The Design specialist's wire (spec 2026-11-28-dynamic-specialists.md,
15// sections 1 and 3; ProtocolDesign): a maker step's specialist binding on
16// its dispatch, the page_render lease check, the captures a Design step
17// names in its report's options, and the render_file chunks that carry
18// them. Both ends validate with the functions here.
19
20// Bounds of a Design report and its captures.
21const (
22 // MaxDesignOptions and MaxDesignCaptures bound a report's options and
23 // the captures named across all of them.
24 MaxDesignOptions = 4
25 MaxDesignCaptures = 12
26 // MaxOptionName bounds an option's name, in bytes.
27 MaxOptionName = 60
28 // MaxCaptureBytes is the most one capture holds (spec: re-encoded
29 // to at most 2 MB); render_page writes none larger.
30 MaxCaptureBytes = 2 << 20
31 // RenderFileChunk is one render_file frame's share of a capture, as
32 // research_file's; MaxRenderFileChunks the most a capture needs.
33 RenderFileChunk = ResearchFileChunk
34 MaxRenderFileChunks = (MaxCaptureBytes + RenderFileChunk - 1) / RenderFileChunk
35 // MaxBindingCapabilities bounds a binding's capabilities.
36 MaxBindingCapabilities = 8
37 // MaxSpecialistBrief bounds a dispatch's SpecialistBrief: the menu's
38 // bound on a specialist's brief (specialist.MaxBrief).
39 MaxSpecialistBrief = 2 << 10
40 // MaxCaptureWidth and MaxCaptureHeight bound a capture's pixels: the
41 // widest viewport (desktop) and a full page's clip (spec: full pages
42 // capped at 10,000 px), as render_page writes them.
43 MaxCaptureWidth = 1440
44 MaxCaptureHeight = 10000
45)
46
47// A Design step that waits, by placement: PlacementDesign while the
48// runner it would run on cannot run Design (below ProtocolDesign, its
49// page renderer not ok, or no Claude connection of the person there);
50// PlacementDesignLimit while the task's autonomy limit holds it for its
51// person (HoldDesignLimit, through the held-step card).
52const (
53 PlacementDesign = "design_runner"
54 PlacementDesignLimit = "design_limit"
55)
56
57// HoldDesignLimit is the hold, and the need, of a Design step held by the
58// autonomy limit: Design ran DesignRunLimit attempts of the task since
59// its person last acted on it. The instance sets it; a runner never
60// reports it (it is not in HoldReasons).
61const HoldDesignLimit = "design_limit"
62
63// DesignRunLimit is how many Design attempts a task runs without a word
64// from its person (spec section 4, Budget).
65const DesignRunLimit = 3
66
67// CardMakerRemoved asks a task's creator, once its maker specialist was
68// removed and every attempt of its steps has ended with its end proven,
69// whether to hand the task to Engineering; ChoiceToEngineering is its one
70// answer.
71const (
72 CardMakerRemoved = "maker_removed"
73 ChoiceToEngineering = "to_engineering"
74)
75
76// DesignOption is one mockup option of a Design step's candidate: the
77// name the person will use for it and the captures that show it.
78type DesignOption struct {
79 Name string `json:"name"`
80 Captures []DesignCapture `json:"captures"`
81}
82
83// DesignCapture is one capture an option names: its render_page file id
84// (the name under /render/), the SHA-256 of its PNG and the digest of the
85// exported tree it was rendered from (a diff carries work's).
86type DesignCapture struct {
87 ID string `json:"id"`
88 SHA256 string `json:"sha256"`
89 TreeDigest string `json:"tree_digest"`
90}
91
92// StepDesign is what a done Design attempt kept, on the task's read
93// shape only: the options its final report named, in its order, each
94// with the captures the instance kept for it (a capture is kept only
95// once the report validated it).
96type StepDesign struct {
97 Attempt int64 `json:"attempt"`
98 Options []StepDesignOption `json:"options"`
99}
100
101// StepDesignOption is one option and its kept captures, in the report's
102// order. Name is the specialist's label for it.
103type StepDesignOption struct {
104 Name string `json:"name"`
105 Captures []StepCapture `json:"captures"`
106}
107
108// StepCapture is one kept capture: ID is its task file (GET
109// /tasks/{task}/files/{id}), CaptureID the render_page file it was
110// (its tree is in the name), with its size and pixel size.
111type StepCapture struct {
112 ID string `json:"id"`
113 CaptureID string `json:"capture_id"`
114 Size int64 `json:"size"`
115 Width int `json:"width"`
116 Height int `json:"height"`
117}
118
119// CaptureTree is the tree a capture id names: base, work or diff ("" for
120// an id that is not a capture's).
121func CaptureTree(id string) string {
122 m := captureID.FindStringSubmatch(id)
123 if m == nil {
124 return ""
125 }
126 return m[2]
127}
128
129// A Design step's render audit (spec section 4, "Audit": each render's
130// counts and timing on the step): one record per accepted render_page
131// call, kept by the runner on the step and carried on its final report
132// (StepReport.Renders, ProtocolDesign), as plain data.
133const (
134 // MaxRenderAudits is a step's render_page calls (renderpage.MaxCalls).
135 MaxRenderAudits = 20
136 // MaxRenderPages is one call's pages (render.MaxPages).
137 MaxRenderPages = 6
138 // MaxRenderAuditMS bounds a record's duration: well past the call's
139 // 60 seconds, so a slow end still records.
140 MaxRenderAuditMS = 10 * 60 * 1000
141)
142
143// A record's tree: base, work, or compare (both, then their diffs).
144const (
145 RenderTreeBase = "base"
146 RenderTreeWork = "work"
147 RenderTreeCompare = "compare"
148)
149
150// A record's outcome: rendered, a refusal's fixed code, or cancelled
151// (the step ended during the call).
152const (
153 RenderRendered = "rendered"
154 RenderCancelled = "cancelled"
155)
156
157// RenderOutcomes are every outcome a record may have: rendered, the
158// spec's seven codes and the plan's two (renderpage.Codes), cancelled.
159var RenderOutcomes = []string{RenderRendered, "renderer_missing", "renderer_mismatch", "no_site", "too_many", "busy", "timeout", "crashed", "secrets", "scanner", RenderCancelled}
160
161// RenderAudit is one accepted render_page call: its number in the step
162// (1 to MaxRenderAudits), the attempt it ran in, its tree, its pages,
163// the captures it counted against the step's 60 (pages, twice for a
164// compare), the files it wrote (its captures and a compare's diffs; none
165// unless rendered), how long it took and how it ended.
166type RenderAudit struct {
167 Call int `json:"call"`
168 Attempt int64 `json:"attempt"`
169 Tree string `json:"tree"`
170 Pages int `json:"pages"`
171 Captures int `json:"captures"`
172 Files int `json:"files"`
173 DurationMS int64 `json:"duration_ms"`
174 Outcome string `json:"outcome"`
175}
176
177// ValidRenderAudits strictly bounds a report's render records for its
178// attempt: at most MaxRenderAudits, each call numbered 1 to
179// MaxRenderAudits and above the one before, each attempt from 1, never
180// below the one before nor above attempt (a failover keeps the step's
181// calls), a known tree and outcome, 1 to MaxRenderPages pages, captures
182// exactly its pages (twice for a compare), files only for a rendered
183// call and then its captures and a compare's diffs (one a page), and a
184// duration of 0 to MaxRenderAuditMS.
185func ValidRenderAudits(recs []RenderAudit, attempt int64) error {
186 if len(recs) > MaxRenderAudits {
187 return fmt.Errorf("%w: %d render records", ErrStrict, len(recs))
188 }
189 call, at := 0, int64(1)
190 for _, r := range recs {
191 trees := 1
192 switch r.Tree {
193 case RenderTreeBase, RenderTreeWork:
194 case RenderTreeCompare:
195 trees = 2
196 default:
197 return fmt.Errorf("%w: render %d's tree %q", ErrStrict, r.Call, r.Tree)
198 }
199 files := 0
200 if r.Outcome == RenderRendered {
201 files = r.Pages * trees
202 if trees == 2 {
203 files += r.Pages
204 }
205 }
206 switch {
207 case r.Call <= call || r.Call > MaxRenderAudits:
208 return fmt.Errorf("%w: render call %d after %d", ErrStrict, r.Call, call)
209 case r.Attempt < at || r.Attempt > attempt:
210 return fmt.Errorf("%w: render %d's attempt %d", ErrStrict, r.Call, r.Attempt)
211 case r.Pages < 1 || r.Pages > MaxRenderPages || r.Captures != r.Pages*trees || r.Files != files:
212 return fmt.Errorf("%w: render %d's counts", ErrStrict, r.Call)
213 case r.DurationMS < 0 || r.DurationMS > MaxRenderAuditMS:
214 return fmt.Errorf("%w: render %d's duration", ErrStrict, r.Call)
215 case !slices.Contains(RenderOutcomes, r.Outcome):
216 return fmt.Errorf("%w: render %d's outcome %q", ErrStrict, r.Call, r.Outcome)
217 }
218 call, at = r.Call, r.Attempt
219 }
220 return nil
221}
222
223// RenderFile is one chunk of a named capture, runner to instance, sent
224// before the step's final report. Index counts from 0 to Total-1; SHA256
225// and Size are the whole file's.
226type RenderFile struct {
227 TaskID string `json:"task_id"`
228 StepID string `json:"step_id"`
229 Attempt int64 `json:"attempt"`
230 CaptureID string `json:"capture_id"`
231 Index int `json:"index"`
232 Total int `json:"total"`
233 Size int64 `json:"size"`
234 SHA256 string `json:"sha256"`
235 Data string `json:"data"`
236}
237
238var (
239 // captureID is render_page's file name: <call>-<tree>-<n>.png, call
240 // and n from 1 with no leading zero (renderpage.Tool).
241 captureID = regexp.MustCompile(`^([1-9][0-9]?)-(base|work|diff)-([1-9][0-9]?)\.png$`)
242 // The instance's ids (newID): sp_ and p_ then lower-case base32.
243 specialistID = regexp.MustCompile(`^sp_[a-z0-9]{1,40}$`)
244 projectID = regexp.MustCompile(`^p_[a-z0-9]{1,40}$`)
245 // A menu profile id (research-v1, design-review-v1) and capability
246 // id (web.research, page.render).
247 profileID = regexp.MustCompile(`^[a-z][a-z0-9]*(-[a-z0-9]+)*-v[1-9][0-9]{0,2}$`)
248 capabilityID = regexp.MustCompile(`^[a-z]+(\.[a-z]+)+$`)
249)
250
251// ValidCaptureID is a render_page capture's file id.
252func ValidCaptureID(id string) bool { return captureID.MatchString(id) }
253
254// ValidOptions strictly bounds a Design report's options: at most
255// MaxDesignOptions, at most MaxDesignCaptures captures across them, each
256// option's name a plain label (validOptionName) said once (case folded),
257// each capture's id a capture id named once across all options, its
258// SHA-256 and tree digest lower-case hex SHA-256. An option may name no
259// capture; no options at all is valid. Whether the captures were staged
260// is the receiver's check.
261func ValidOptions(opts []DesignOption) error {
262 if len(opts) > MaxDesignOptions {
263 return fmt.Errorf("%w: %d options", ErrStrict, len(opts))
264 }
265 names, ids := map[string]bool{}, map[string]bool{}
266 for _, o := range opts {
267 folded := strings.ToLower(o.Name)
268 if !validOptionName(o.Name) || names[folded] {
269 return fmt.Errorf("%w: option name %q", ErrStrict, o.Name)
270 }
271 names[folded] = true
272 for _, c := range o.Captures {
273 if !ValidCaptureID(c.ID) || ids[c.ID] || !ValidSHA256(c.SHA256) || !ValidSHA256(c.TreeDigest) {
274 return fmt.Errorf("%w: capture %q", ErrStrict, c.ID)
275 }
276 ids[c.ID] = true
277 }
278 }
279 if len(ids) > MaxDesignCaptures {
280 return fmt.Errorf("%w: %d captures", ErrStrict, len(ids))
281 }
282 return nil
283}
284
285// validOptionName: at most MaxOptionName bytes; letters, digits, spaces,
286// hyphens and apostrophes only (so valid UTF-8: a bad byte reads as
287// U+FFFD, not a letter); never two spaces together; starting and ending
288// with a letter or digit (so never empty). Nothing that reads as markup,
289// a path, a control or a format character.
290func validOptionName(s string) bool {
291 if len(s) > MaxOptionName || strings.Contains(s, " ") {
292 return false
293 }
294 for _, r := range s {
295 if !word(r) && r != ' ' && r != '-' && r != '\'' {
296 return false
297 }
298 }
299 first, _ := utf8.DecodeRuneInString(s)
300 last, _ := utf8.DecodeLastRuneInString(s)
301 return word(first) && word(last)
302}
303
304func word(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) }
305
306// ValidRenderFile bounds one render_file chunk: its task, step (at most
307// 128 bytes each) and attempt; a capture id; a whole file of at most
308// MaxCaptureBytes in exactly the chunks its size needs (so at least one
309// byte: an empty file has no chunk to be); and this chunk's data, strict
310// padded base64, exactly its share of the file.
311func ValidRenderFile(v RenderFile) bool {
312 if v.TaskID == "" || len(v.TaskID) > 128 || v.StepID == "" || len(v.StepID) > 128 || v.Attempt < 1 || !ValidCaptureID(v.CaptureID) || !ValidSHA256(v.SHA256) {
313 return false
314 }
315 if v.Size > MaxCaptureBytes || int64(v.Total) != (v.Size+RenderFileChunk-1)/RenderFileChunk || v.Index < 0 || v.Index >= v.Total {
316 return false
317 }
318 share := int64(RenderFileChunk)
319 if v.Index == v.Total-1 {
320 share = v.Size - int64(v.Total-1)*RenderFileChunk
321 }
322 data, err := base64.StdEncoding.Strict().DecodeString(v.Data)
323 return err == nil && int64(len(data)) == share
324}
325
326// ValidSpecialistBinding: a dispatch carries no specialist binding at all
327// (Engineering itself, and every other step), or a whole one: a
328// specialist id of the instance's shape, a revision from 1, a project id
329// or "" for the team, a profile id of the menu's shape, 1 to
330// MaxBindingCapabilities distinct capability ids, and a brief of at most
331// MaxSpecialistBrief bytes of text. Whether the binding
332// is still granted is the instance's check.
333func ValidSpecialistBinding(d *DispatchCommand) bool {
334 if !hasBinding(d) {
335 return true
336 }
337 if !specialistID.MatchString(d.SpecialistID) || d.SpecialistRevision < 1 || d.SpecialistProject != "" && !projectID.MatchString(d.SpecialistProject) || len(d.Profile) > 40 || !profileID.MatchString(d.Profile) {
338 return false
339 }
340 if len(d.Capabilities) < 1 || len(d.Capabilities) > MaxBindingCapabilities {
341 return false
342 }
343 if len(d.SpecialistBrief) > MaxSpecialistBrief || !utf8.ValidString(d.SpecialistBrief) || strings.ContainsRune(d.SpecialistBrief, 0) {
344 return false
345 }
346 seen := map[string]bool{}
347 for _, c := range d.Capabilities {
348 if len(c) > 40 || !capabilityID.MatchString(c) || seen[c] {
349 return false
350 }
351 seen[c] = true
352 }
353 return true
354}
355
356// hasBinding: any part of a specialist binding is set.
357func hasBinding(d *DispatchCommand) bool {
358 return d.SpecialistID != "" || d.SpecialistRevision != 0 || d.SpecialistProject != "" || d.Profile != "" || len(d.Capabilities) > 0 || d.Explore || d.SpecialistBrief != ""
359}
360
361// downgradeDesign makes a frame speak a protocol below ProtocolDesign. A
362// dispatch with any part of a specialist binding is refused: an older
363// runner would run the step as plain Engineering, outside its grant. So
364// are a page_render check (an older instance would ack it as a start
365// authorization, without the grant check), a render_file chunk, and a
366// propose_specialist call for one project (an older instance has no
367// scope, so it would propose for the whole team); a proposal's empty
368// project, the team's, is dropped. A report's options and render
369// records are dropped. It reports whether anything changed.
370func downgradeDesign(body any, protocol int) (bool, error) {
371 switch v := body.(type) {
372 case *DispatchCommand:
373 if hasBinding(v) {
374 return false, fmt.Errorf("%w: a specialist's dispatch at protocol %d", ErrProtocol, protocol)
375 }
376 case *LeaseCheck:
377 if v.Purpose == LeasePurposeRender {
378 return false, fmt.Errorf("%w: a render check at protocol %d", ErrProtocol, protocol)
379 }
380 case *RenderFile:
381 return false, fmt.Errorf("%w: render_file at protocol %d", ErrProtocol, protocol)
382 case *StepReport:
383 if v.Options != nil || v.Renders != nil {
384 v.Options, v.Renders = nil, nil
385 return true, nil
386 }
387 case *ToolCall:
388 return withoutTeamProject(v, protocol)
389 }
390 return false, nil
391}
392
393// ProjectProposal reports whether a call is propose_specialist for one
394// project: its project is anything but "" (the team's) or absent. The
395// runner answers such a call itself below ProtocolDesign.
396func ProjectProposal(v *ToolCall) bool {
397 project, ok := proposalProject(v)
398 return ok && string(project) != `""`
399}
400
401// proposalProject is a propose_specialist call's project as sent, and
402// whether it has one.
403func proposalProject(v *ToolCall) (json.RawMessage, bool) {
404 if v.Name != ToolProposeSpecialist {
405 return nil, false
406 }
407 var args map[string]json.RawMessage
408 if json.Unmarshal(v.Args, &args) != nil {
409 return nil, false
410 }
411 project, ok := args["project"]
412 return project, ok
413}
414
415// withoutTeamProject drops propose_specialist's project when it is ""
416// (the team's, all an older instance knows) and refuses the call when it
417// names anything else.
418func withoutTeamProject(v *ToolCall, protocol int) (bool, error) {
419 if _, ok := proposalProject(v); !ok {
420 return false, nil
421 }
422 if ProjectProposal(v) {
423 return false, fmt.Errorf("%w: a proposal for one project at protocol %d", ErrProtocol, protocol)
424 }
425 var args map[string]json.RawMessage
426 if err := json.Unmarshal(v.Args, &args); err != nil {
427 return false, err
428 }
429 delete(args, "project")
430 raw, err := json.Marshal(args)
431 if err != nil {
432 return false, err
433 }
434 v.Args = raw
435 return true, nil
436}
437