oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package designstep is the Design step's tools on the runner (spec
2// 2026-11-28-dynamic-specialists.md, sections 1, 3 and 5; plan task 18):
3// render_page behind the instance's render check, submit_candidate's
4// options bound to this attempt's own captures, ask_person's fixed
5// reply, and the named captures as render_file chunks. The texts here
6// are for the model; people never read them.
7package designstep
8
9import (
10 "bytes"
11 "context"
12 "crypto/sha256"
13 "encoding/base64"
14 "encoding/hex"
15 "encoding/json"
16 "errors"
17 "fmt"
18 "io"
19 "os"
20 "strconv"
21 "sync"
22
23 "amadan.net/oficina/equipo/internal/runner/renderpage"
24 "amadan.net/oficina/equipo/internal/specialist"
25 "amadan.net/oficina/equipo/internal/wire"
26)
27
28// The Design step's tools, design-v1's.
29const (
30 ToolRenderPage = specialist.ToolRenderPage
31 ToolSubmitCandidate = specialist.ToolSubmitCandidate
32 ToolAskPerson = specialist.ToolAskPerson
33)
34
35// ErrRenderRefused marks a render check the instance answered with a
36// refusal; any other failed check could not be made.
37var ErrRenderRefused = errors.New("designstep: the instance refused the render")
38
39// Fixed replies.
40const (
41 // RenderRefusedText and RenderUnconfirmedText answer render_page for
42 // the rest of the step once a render check failed.
43 RenderRefusedText = "render_page is stopped for the rest of this step: Equipo's instance refused to let this step render (its Design grant or this attempt no longer holds). Do not call render_page again. Finish without renders, submit what you have, and say in your summary that rendering was refused."
44 RenderUnconfirmedText = "render_page is stopped for the rest of this step: Equipo's instance could not confirm that this step may render. Do not call render_page again. Finish without renders, submit what you have, and say in your summary that rendering was not available."
45 // AskText answers ask_person: nobody is there during the step.
46 AskText = "Nobody can answer during this step. Make the most reasonable choice, build it, and name the assumption in your summary and on the options page."
47
48 renderCancelledText = "render_page: the call was cancelled."
49 submitUnrecordedText = "submit_candidate could not record the options. Call it again with the same options."
50 submitRulesText = "submit_candidate refused: at most 4 options and 12 captures in all; each option named once, in letters, digits, single spaces, hyphens and apostrophes, at most 60 bytes, starting and ending with a letter or digit; each capture named once. Nothing was recorded: fix it and call again."
51 submitInputText = "submit_candidate refused: the input is {\"options\": [{\"name\": \"...\", \"captures\": [\"<file name under /render/>\", ...]}, ...]} and nothing else. Nothing was recorded: fix it and call again."
52)
53
54// capture is one capture render_page made in this attempt, as it wrote
55// it: its file's SHA-256 and size, and the tree digest it showed.
56type capture struct {
57 sha, digest string
58 size int64
59}
60
61// Attempt is one Design attempt's tools. Build one per attempt; it is
62// safe for concurrent calls, which it takes one at a time.
63type Attempt struct {
64 // Confirm asks the instance whether this attempt may render now
65 // (wire.LeasePurposeRender); an error wrapping ErrRenderRefused is
66 // its refusal. nil: no render is allowed.
67 Confirm func(context.Context) error
68 // Render is render_page itself on the attempt's step.
69 Render func(context.Context, json.RawMessage) (string, []renderpage.Capture, error)
70 // Dir is the attempt's render directory, where Render writes.
71 Dir string
72 // Record keeps the options submit_candidate accepted, durably, for
73 // this attempt (nil: kept in memory only).
74 Record func(context.Context, []wire.DesignOption) error
75
76 mu sync.Mutex
77 stopped string
78 captures map[string]capture
79 options []wire.DesignOption
80}
81
82// Call answers one of the step's tools (a thin.ToolFunc).
83func (a *Attempt) Call(ctx context.Context, name, _ string, raw json.RawMessage) (string, bool) {
84 a.mu.Lock()
85 defer a.mu.Unlock()
86 switch name {
87 case ToolRenderPage:
88 return a.render(ctx, raw)
89 case ToolSubmitCandidate:
90 return a.submit(ctx, raw)
91 case ToolAskPerson:
92 return AskText, false
93 }
94 return "unavailable", true
95}
96
97// render is render_page: the instance is asked first, every call; a
98// failed check stops rendering for the rest of the attempt.
99func (a *Attempt) render(ctx context.Context, raw json.RawMessage) (string, bool) {
100 if a.stopped != "" {
101 return a.stopped, true
102 }
103 err := errors.New("designstep: no render check")
104 if a.Confirm != nil {
105 err = a.Confirm(ctx)
106 }
107 switch {
108 case ctx.Err() != nil:
109 return renderCancelledText, true
110 case errors.Is(err, ErrRenderRefused):
111 a.stopped = RenderRefusedText
112 return a.stopped, true
113 case err != nil:
114 a.stopped = RenderUnconfirmedText
115 return a.stopped, true
116 }
117 text, caps, err := a.Render(ctx, raw)
118 a.keep(caps)
119 return text, err != nil
120}
121
122// keep records caps as written in Dir: only a regular file there, its
123// bytes hashed now, is a capture submit_candidate may name.
124func (a *Attempt) keep(caps []renderpage.Capture) {
125 if a.captures == nil {
126 a.captures = map[string]capture{}
127 }
128 for _, c := range caps {
129 if !wire.ValidCaptureID(c.File) || !wire.ValidSHA256(c.Digest) {
130 continue
131 }
132 b, err := readCapture(a.Dir, c.File)
133 if err != nil {
134 continue
135 }
136 sum := sha256.Sum256(b)
137 a.captures[c.File] = capture{sha: hex.EncodeToString(sum[:]), digest: c.Digest, size: int64(len(b))}
138 }
139}
140
141// submission is submit_candidate's input.
142type submission struct {
143 Options *[]struct {
144 Name string `json:"name"`
145 Captures []string `json:"captures"`
146 } `json:"options"`
147}
148
149// submit is submit_candidate: the options, each capture one this
150// attempt made, within the wire's bounds; they replace any before.
151func (a *Attempt) submit(ctx context.Context, raw json.RawMessage) (string, bool) {
152 var in submission
153 dec := json.NewDecoder(bytes.NewReader(raw))
154 dec.DisallowUnknownFields()
155 if dec.Decode(&in) != nil || in.Options == nil || dec.Decode(new(json.RawMessage)) != io.EOF {
156 return submitInputText, true
157 }
158 opts := []wire.DesignOption{}
159 n := 0
160 for _, o := range *in.Options {
161 opt := wire.DesignOption{Name: o.Name, Captures: []wire.DesignCapture{}}
162 for _, id := range o.Captures {
163 c, ok := a.captures[id]
164 if !ok {
165 return fmt.Sprintf("submit_candidate refused: %s is not a capture render_page made in this step. Name only the file names its replies gave under /render/. Nothing was recorded.", strconv.Quote(clip(id, 80))), true
166 }
167 opt.Captures = append(opt.Captures, wire.DesignCapture{ID: id, SHA256: c.sha, TreeDigest: c.digest})
168 n++
169 }
170 opts = append(opts, opt)
171 }
172 if wire.ValidOptions(opts) != nil {
173 return submitRulesText, true
174 }
175 if a.Record != nil && a.Record(ctx, opts) != nil {
176 return submitUnrecordedText, true
177 }
178 a.options = opts
179 return fmt.Sprintf("Recorded %d options with %d captures. They replace any you submitted before. Equipo commits and pushes your workspace when you finish: end with the reply the step prompt asks for.", len(opts), n), false
180}
181
182// Options are the options last recorded (nil: none).
183func (a *Attempt) Options() []wire.DesignOption {
184 a.mu.Lock()
185 defer a.mu.Unlock()
186 return clone(a.options)
187}
188
189// Files are opts' captures read from dir, the attempt's render
190// directory, each as its render_file chunks bound to task, step and
191// attempt. A capture that is not a regular file there, or not the file
192// recorded (its SHA-256), refuses them all; so do options the wire
193// refuses. Only the captures opts name are read.
194func Files(dir, task, step string, attempt int64, opts []wire.DesignOption) ([][]wire.RenderFile, error) {
195 if err := wire.ValidOptions(opts); err != nil {
196 return nil, err
197 }
198 var out [][]wire.RenderFile
199 for _, o := range opts {
200 for _, c := range o.Captures {
201 b, err := readCapture(dir, c.ID)
202 if err != nil {
203 return nil, err
204 }
205 sum := sha256.Sum256(b)
206 if hex.EncodeToString(sum[:]) != c.SHA256 {
207 return nil, fmt.Errorf("designstep: capture %s changed", c.ID)
208 }
209 total := (len(b) + wire.RenderFileChunk - 1) / wire.RenderFileChunk
210 var chunks []wire.RenderFile
211 for i := range total {
212 part := b[i*wire.RenderFileChunk : min((i+1)*wire.RenderFileChunk, len(b))]
213 f := wire.RenderFile{TaskID: task, StepID: step, Attempt: attempt, CaptureID: c.ID, Index: i, Total: total, Size: int64(len(b)), SHA256: c.SHA256, Data: base64.StdEncoding.EncodeToString(part)}
214 if !wire.ValidRenderFile(f) {
215 return nil, fmt.Errorf("designstep: capture %s chunk %d is not a render_file", c.ID, i)
216 }
217 chunks = append(chunks, f)
218 }
219 out = append(out, chunks)
220 }
221 }
222 return out, nil
223}
224
225// readCapture is the capture id's bytes in dir: a regular file reached
226// through no link, of 1 to wire.MaxCaptureBytes bytes.
227func readCapture(dir, id string) ([]byte, error) {
228 if !wire.ValidCaptureID(id) {
229 return nil, fmt.Errorf("designstep: capture id %q", id)
230 }
231 root, err := os.OpenRoot(dir)
232 if err != nil {
233 return nil, err
234 }
235 defer root.Close()
236 info, err := root.Lstat(id)
237 if err != nil {
238 return nil, err
239 }
240 if !info.Mode().IsRegular() {
241 return nil, fmt.Errorf("designstep: capture %s is not a regular file", id)
242 }
243 f, err := root.Open(id)
244 if err != nil {
245 return nil, err
246 }
247 defer f.Close()
248 b, err := io.ReadAll(io.LimitReader(f, wire.MaxCaptureBytes+1))
249 if err != nil {
250 return nil, err
251 }
252 if len(b) == 0 || len(b) > wire.MaxCaptureBytes {
253 return nil, fmt.Errorf("designstep: capture %s is %d bytes", id, len(b))
254 }
255 return b, nil
256}
257
258func clone(opts []wire.DesignOption) []wire.DesignOption {
259 if opts == nil {
260 return nil
261 }
262 out := make([]wire.DesignOption, len(opts))
263 for i, o := range opts {
264 out[i] = wire.DesignOption{Name: o.Name, Captures: append([]wire.DesignCapture{}, o.Captures...)}
265 }
266 return out
267}
268
269func clip(s string, n int) string {
270 if len(s) > n {
271 return s[:n]
272 }
273 return s
274}
275