oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package team is the durable core of the team service: jobs made of
2// bounded acyclic steps, fenced attempts under short leases, a reservation
3// ledger, replay-classified action intents with receipts, immutable
4// hash-pinned artifacts and the evidence predicates that decide success.
5//
6// Design: docs/superpowers/specs/2026-11-01-team-service-design.md and
7// docs/superpowers/plans/2026-11-01-team-service.md (M0, M1 and the M5
8// fixture workflow). Nothing here opens a network connection, launches a
9// goroutine or reads credentials: Authority and adapters are injected, the
10// clock is injected, and every read or write binds an account and a job.
11//
12// This file holds the closed record types. Every enumerated field is a
13// closed set checked by a Valid method; a value outside the set fails closed
14// wherever it is read or written, including rows found in the database.
15package team
16
17import (
18 "errors"
19 "fmt"
20 "time"
21)
22
23// Code is a sentinel error class. Callers compare with errors.Is against the
24// Err* values below; the Detail of an Error is for operators and logs, not
25// for users.
26type Code string
27
28const (
29 CodeScope Code = "scope" // unknown job, or a job outside the caller's account
30 CodeInvalid Code = "invalid" // malformed request
31 CodeUnknownKind Code = "unknown_kind" // schema, state, operation or policy field outside the closed set
32 CodeState Code = "state" // transition not allowed from the current state
33 CodeRevision Code = "revision" // expected revision does not match the stored one
34 CodeFence Code = "fence" // handle does not match the stored current fence
35 CodeLeaseExpired Code = "lease_expired" // attempt's lease deadline has passed
36 CodeQuota Code = "quota" // attempt, concurrency or time cap reached
37 CodeBudget Code = "budget" // reservation would exceed a job, ancestor or account limit
38 CodeOverflow Code = "overflow" // integer accounting would overflow
39 CodeConflict Code = "conflict" // same logical key with a different payload, or duplicate identity
40 CodeDependency Code = "dependency" // step dependencies not yet satisfied
41 CodeContainment Code = "containment" // a prior attempt is not yet contained
42 CodeWorkspace Code = "workspace" // workspace identity reused across attempts
43 CodeAdmissionPaused Code = "admission_paused" // store is in startup or quarantine
44 CodeAdmissionExpired Code = "admission_expired" // authority admission older than the policy allows
45 CodeGrantRevoked Code = "grant_revoked" // authority reports the grant revoked or unknown
46 CodeGrantStale Code = "grant_stale" // authority version or epoch differs from the stored snapshot
47 CodeAuthorityUnavailable Code = "authority_unavailable" // authority could not answer; nothing was decided
48 CodeReceiptConflict Code = "receipt_conflict" // a different receipt or usage for a settled reservation
49 CodeNotDispatched Code = "not_dispatched" // adapter proves no dispatch or usage; releases the reservation
50 CodeUncertain Code = "uncertain" // external outcome unknown; reconcile before replaying
51 CodeReplayUnsafe Code = "replay_unsafe" // operation class forbids replay without a definitive answer
52 CodeEvidence Code = "evidence" // success predicate not satisfied
53 CodeSize Code = "size" // payload, artifact or event over its byte limit
54 CodeStaleStore Code = "stale_store" // schema newer than this binary
55)
56
57// Error is the one error type the package returns. Is matches on Code so
58// callers can test errors.Is(err, ErrFence) regardless of Detail.
59type Error struct {
60 Code Code
61 Detail string
62}
63
64func (e *Error) Error() string {
65 if e.Detail == "" {
66 return "team: " + string(e.Code)
67 }
68 return "team: " + string(e.Code) + ": " + e.Detail
69}
70
71// Is reports whether target is an *Error with the same Code.
72func (e *Error) Is(target error) bool {
73 t, ok := target.(*Error)
74 return ok && t.Code == e.Code
75}
76
77func fail(code Code, format string, args ...any) error {
78 return &Error{Code: code, Detail: fmt.Sprintf(format, args...)}
79}
80
81// CodeOf returns the Code of err when it is a team Error, else "".
82func CodeOf(err error) Code {
83 var e *Error
84 if errors.As(err, &e) {
85 return e.Code
86 }
87 return ""
88}
89
90var (
91 ErrScope = &Error{Code: CodeScope}
92 ErrInvalid = &Error{Code: CodeInvalid}
93 ErrUnknownKind = &Error{Code: CodeUnknownKind}
94 ErrState = &Error{Code: CodeState}
95 ErrRevision = &Error{Code: CodeRevision}
96 ErrFence = &Error{Code: CodeFence}
97 ErrLeaseExpired = &Error{Code: CodeLeaseExpired}
98 ErrQuota = &Error{Code: CodeQuota}
99 ErrBudget = &Error{Code: CodeBudget}
100 ErrOverflow = &Error{Code: CodeOverflow}
101 ErrConflict = &Error{Code: CodeConflict}
102 ErrDependency = &Error{Code: CodeDependency}
103 ErrContainment = &Error{Code: CodeContainment}
104 ErrWorkspace = &Error{Code: CodeWorkspace}
105 ErrAdmissionPaused = &Error{Code: CodeAdmissionPaused}
106 ErrAdmissionExpired = &Error{Code: CodeAdmissionExpired}
107 ErrGrantRevoked = &Error{Code: CodeGrantRevoked}
108 ErrGrantStale = &Error{Code: CodeGrantStale}
109 ErrAuthorityUnavailable = &Error{Code: CodeAuthorityUnavailable}
110 ErrReceiptConflict = &Error{Code: CodeReceiptConflict}
111 ErrNotDispatched = &Error{Code: CodeNotDispatched}
112 ErrUncertain = &Error{Code: CodeUncertain}
113 ErrReplayUnsafe = &Error{Code: CodeReplayUnsafe}
114 ErrEvidence = &Error{Code: CodeEvidence}
115 ErrSize = &Error{Code: CodeSize}
116 ErrStaleStore = &Error{Code: CodeStaleStore}
117)
118
119// Identifiers. Rows are SQLite integer keys; the typed wrappers keep a step
120// id from being passed where an attempt id is wanted.
121type (
122 AccountID string
123 JobID int64
124 StepID int64
125 AttemptID int64
126 ActionID int64
127 ArtifactID int64
128 ReservationID int64
129)
130
131// Scope binds every read and write to one account and one job. A job that
132// exists in another account is indistinguishable from one that does not
133// exist: both answer ErrScope.
134type Scope struct {
135 Account AccountID
136 Job JobID
137}
138
139func (s Scope) validate() error {
140 if s.Account == "" || s.Job <= 0 {
141 return fail(CodeScope, "empty scope")
142 }
143 return nil
144}
145
146// JobState is the closed job state set from the spec.
147type JobState string
148
149const (
150 JobQueued JobState = "queued"
151 JobRunning JobState = "running"
152 JobWaiting JobState = "waiting"
153 JobVerifying JobState = "verifying"
154 JobSucceeded JobState = "succeeded"
155 JobFailed JobState = "failed"
156 JobCancelled JobState = "cancelled"
157)
158
159func (s JobState) Valid() bool {
160 switch s {
161 case JobQueued, JobRunning, JobWaiting, JobVerifying, JobSucceeded, JobFailed, JobCancelled:
162 return true
163 }
164 return false
165}
166
167// Terminal reports whether the state admits no further transition.
168func (s JobState) Terminal() bool {
169 return s == JobSucceeded || s == JobFailed || s == JobCancelled
170}
171
172// WaitReason types a waiting job. Only the listed reasons exist.
173type WaitReason string
174
175const (
176 WaitNone WaitReason = ""
177 WaitApproval WaitReason = "approval"
178 WaitProviderLimit WaitReason = "provider_limit"
179 WaitBudget WaitReason = "budget"
180 WaitDependency WaitReason = "dependency"
181 WaitRunnerUnavailable WaitReason = "runner_unavailable"
182 WaitUncertainOutcome WaitReason = "uncertain_external_outcome"
183)
184
185func (w WaitReason) Valid() bool {
186 switch w {
187 case WaitNone, WaitApproval, WaitProviderLimit, WaitBudget, WaitDependency, WaitRunnerUnavailable, WaitUncertainOutcome:
188 return true
189 }
190 return false
191}
192
193// claimable reports whether a runner may claim a step while the job waits
194// for this reason. Uncertain outcomes, budget and approval need an explicit
195// resolution first; the others resolve by trying again.
196func (w WaitReason) claimable() bool {
197 switch w {
198 case WaitProviderLimit, WaitDependency, WaitRunnerUnavailable:
199 return true
200 }
201 return false
202}
203
204// TargetKind closes the set of things a job can be bound to.
205type TargetKind string
206
207const (
208 TargetConversation TargetKind = "conversation"
209 TargetProjectRead TargetKind = "project_read"
210 TargetRepository TargetKind = "repository"
211 TargetBusiness TargetKind = "business"
212)
213
214// TargetBinding is the explicit account-side mapping of a job to what it
215// works on. Nothing is inferred from names; a repository target needs a
216// repository and a base revision, a business target needs a subject.
217type TargetBinding struct {
218 Kind TargetKind `json:"kind"`
219 // Repository is the forge-qualified repository name, Ref the branch the
220 // job may publish to, BaseRevision the exact base identity (a hash).
221 // DefaultRef names the protected default branch; publication to it is
222 // refused by the store before any adapter sees it.
223 Repository string `json:"repository,omitempty"`
224 Ref string `json:"ref,omitempty"`
225 DefaultRef string `json:"default_ref,omitempty"`
226 BaseRevision string `json:"base_revision,omitempty"`
227 App string `json:"app,omitempty"`
228 // Subject identifies a business target (a ledger period, a customer
229 // file). No Git fields are required or allowed.
230 Subject string `json:"subject,omitempty"`
231}
232
233func (t TargetBinding) validate() error {
234 switch t.Kind {
235 case TargetConversation:
236 if t.Subject == "" || t.Repository != "" || t.Ref != "" || t.DefaultRef != "" || t.BaseRevision != "" || t.App != "" {
237 return ErrInvalid
238 }
239 case TargetProjectRead:
240 if t.Repository == "" || t.BaseRevision == "" || t.Ref != "" || t.DefaultRef != "" || t.Subject != "" {
241 return fail(CodeInvalid, "read_target_invalid")
242 }
243 case TargetRepository:
244 if t.Repository == "" || t.Ref == "" || t.DefaultRef == "" || t.BaseRevision == "" {
245 return fail(CodeInvalid, "repository target needs repository, ref, default_ref and base_revision")
246 }
247 if t.Ref == t.DefaultRef {
248 return fail(CodeInvalid, "repository target ref is the default branch")
249 }
250 if t.Subject != "" {
251 return fail(CodeInvalid, "repository target carries a business subject")
252 }
253 case TargetBusiness:
254 if t.Subject == "" {
255 return fail(CodeInvalid, "business target needs a subject")
256 }
257 if t.Repository != "" || t.Ref != "" || t.DefaultRef != "" || t.BaseRevision != "" || t.App != "" {
258 return fail(CodeInvalid, "business target carries repository fields")
259 }
260 default:
261 return fail(CodeUnknownKind, "target kind %q", t.Kind)
262 }
263 return nil
264}
265
266// Predicate names the success predicate a job is held to.
267type Predicate string
268
269const (
270 // PredicateSoftwareFix: frozen reproduction fails on base and passes on
271 // the candidate under the trusted check definition, an independent
272 // reviewer approved that exact candidate, and that exact candidate was
273 // published with a receipt.
274 PredicateSoftwareFix Predicate = "software_fix"
275 PredicateSoftwareFeature Predicate = "software_feature"
276 PredicateRenderedChange Predicate = "rendered_change"
277 // PredicateAttestedReconciliation: a reconciliation over at least
278 // RequiredSources source records, with explicit discrepancies, approved
279 // by an independent reviewer.
280 PredicateAttestedReconciliation Predicate = "attested_reconciliation"
281)
282
283func (p Predicate) Valid() bool {
284 return p == PredicateSoftwareFeature || p == PredicateRenderedChange || p == PredicateSoftwareFix || p == PredicateAttestedReconciliation
285}
286
287// EvidenceRequirement is the job's configured success predicate and its
288// parameters. ExpectedSymptom must appear in the base failure message;
289// CheckDefinitionHash pins the trusted check definition every result must
290// have run under. BaselineTestSetHash pins the executor's required test set.
291type EvidenceRequirement struct {
292 FrozenAcceptanceHash string `json:"frozen_acceptance_hash,omitempty"`
293 RenderedApprovalHash string `json:"rendered_approval_hash,omitempty"`
294 RenderedApprovals []RenderedApproval `json:"rendered_approvals,omitempty"`
295 RequiredDecisions []string `json:"required_decisions,omitempty"`
296 RequireBugFreeze bool `json:"require_bug_freeze,omitempty"`
297 FrozenReproductionHash string `json:"frozen_reproduction_hash,omitempty"`
298 BaselineTestSetHash string `json:"baseline_test_set_hash,omitempty"`
299 Predicate Predicate `json:"predicate"`
300 ExpectedSymptom string `json:"expected_symptom,omitempty"`
301 CheckDefinitionHash string `json:"check_definition_hash,omitempty"`
302 RequiredSources int `json:"required_sources,omitempty"`
303}
304
305func (e EvidenceRequirement) validate(kind TargetKind) error {
306 switch e.Predicate {
307 case "":
308 if kind != TargetProjectRead && kind != TargetConversation {
309 return fail(CodeInvalid, "read_target_required")
310 }
311 case PredicateSoftwareFeature, PredicateRenderedChange:
312 if kind != TargetRepository || !lowerHex(e.CheckDefinitionHash, 64) || !lowerHex(e.BaselineTestSetHash, 64) {
313 return fail(CodeInvalid, "publication_definition_required")
314 }
315 if e.Predicate == PredicateRenderedChange && !validDecisions(e.RequiredDecisions) {
316 return fail(CodeInvalid, "rendered_decisions_required")
317 }
318 case PredicateSoftwareFix:
319 if kind != TargetRepository {
320 return fail(CodeInvalid, "software_fix predicate needs a repository target")
321 }
322 if e.ExpectedSymptom == "" || e.CheckDefinitionHash == "" {
323 return fail(CodeInvalid, "software_fix predicate needs expected_symptom and check_definition_hash")
324 }
325 case PredicateAttestedReconciliation:
326 if kind != TargetBusiness {
327 return fail(CodeInvalid, "attested_reconciliation predicate needs a business target")
328 }
329 if e.RequiredSources < 1 {
330 return fail(CodeInvalid, "attested_reconciliation predicate needs required_sources >= 1")
331 }
332 default:
333 return fail(CodeUnknownKind, "predicate %q", e.Predicate)
334 }
335 return nil
336}
337
338// GrantSnapshot is the locally observed view of the console-owned grant:
339// a reference and the version/epoch last confirmed online. It is an audit
340// record, never an authorization source; admission compares it with a fresh
341// Admission and refuses when they differ.
342type GrantSnapshot struct {
343 Ref string `json:"ref"`
344 Version int64 `json:"version"`
345 Epoch int64 `json:"epoch"`
346 ObservedAt time.Time `json:"observed_at"`
347}
348
349// Job is the durable job record.
350type Job struct {
351 Project ProjectID
352 ID JobID
353 Account AccountID
354 Parent JobID // 0 when top-level
355 Requester string
356 Target TargetBinding
357 Evidence EvidenceRequirement
358 PolicyVersion int
359 Policy Policy
360 Grant GrantSnapshot
361 State JobState
362 Wait WaitReason
363 Revision int64
364 Outcome string
365 CreatedAt time.Time
366 UpdatedAt time.Time
367}
368
369// Capability closes the set of step capabilities. Each one admits a fixed
370// set of artifact roles (see roleAllowed) so an implementer cannot register
371// a reproduction and a reviewer cannot register a candidate.
372type Capability string
373
374const (
375 CapCoordinate Capability = "coordinate"
376 CapScope Capability = "scope"
377 CapResearch Capability = "research"
378 CapReproduce Capability = "reproduce"
379 CapImplement Capability = "implement"
380 CapReview Capability = "review"
381 CapVerify Capability = "verify"
382 CapPublish Capability = "publish"
383 CapCollect Capability = "collect"
384 CapReconcile Capability = "reconcile"
385)
386
387func (c Capability) Valid() bool {
388 switch c {
389 case CapCoordinate, CapScope, CapResearch, CapReproduce, CapImplement, CapReview, CapVerify, CapPublish, CapCollect, CapReconcile:
390 return true
391 }
392 return false
393}
394
395// StepState is the closed step state set.
396type StepState string
397
398const (
399 StepPending StepState = "pending"
400 StepRunning StepState = "running"
401 StepSucceeded StepState = "succeeded"
402 StepFailed StepState = "failed"
403 StepCancelled StepState = "cancelled"
404)
405
406func (s StepState) Valid() bool {
407 switch s {
408 case StepPending, StepRunning, StepSucceeded, StepFailed, StepCancelled:
409 return true
410 }
411 return false
412}
413
414// StepSpec describes one step at job creation. DependsOn names other steps
415// of the same job by Key; the graph must be acyclic and at most MaxSteps.
416type StepSpec struct {
417 Key string `json:"key"`
418 Capability Capability `json:"capability"`
419 Version int `json:"version"`
420 DependsOn []string `json:"depends_on,omitempty"`
421}
422
423// Step is the durable step record. Fence increases monotonically on every
424// claim and every cancellation; an attempt is current only while its fence
425// equals the step's.
426type Step struct {
427 ID StepID
428 Job JobID
429 Key string
430 Capability Capability
431 Version int
432 DependsOn []string
433 State StepState
434 Fence int64
435 Holder AttemptID // active attempt, 0 when none
436 Attempts int
437}
438
439// AttemptState is the closed attempt state set.
440type AttemptState string
441
442const (
443 AttemptActive AttemptState = "active"
444 AttemptStopping AttemptState = "stopping" // stop requested, not yet acknowledged
445 AttemptExpired AttemptState = "expired" // lease deadline passed; containment pending until acknowledged
446 AttemptReleased AttemptState = "released" // runner gave the step back (waiting)
447 AttemptStopped AttemptState = "stopped" // stop acknowledged
448 AttemptSucceeded AttemptState = "succeeded" //
449 AttemptFailed AttemptState = "failed" //
450)
451
452func (s AttemptState) Valid() bool {
453 switch s {
454 case AttemptActive, AttemptStopping, AttemptExpired, AttemptReleased, AttemptStopped, AttemptSucceeded, AttemptFailed:
455 return true
456 }
457 return false
458}
459
460// Containment records whether the runner supervisor has confirmed the
461// attempt's whole containment unit is gone. A step cannot be reclaimed while
462// any prior attempt is still pending; the partial unique index on attempts
463// (step_id) WHERE containment='pending' enforces one live attempt per step.
464type Containment string
465
466const (
467 ContainmentPending Containment = "pending"
468 ContainmentContained Containment = "contained"
469)
470
471// Attempt is the durable attempt record.
472type Attempt struct {
473 ID AttemptID
474 Job JobID
475 Step StepID
476 Number int
477 Runner string
478 Workspace string
479 Fence int64
480 LeaseDeadline time.Time
481 State AttemptState
482 Containment Containment
483 StopRequested time.Time
484 StopAcked time.Time
485 Provider string
486 Model string
487 Effort string
488 Outcome string
489 CreatedAt time.Time
490 UpdatedAt time.Time
491}
492
493// Handle is what a runner presents on every call after a claim. The store
494// compares the attempt, fence and runner with stored rows; a mismatch is
495// ErrFence. Revision is the job revision checked by FreezeBugEvidence.
496// A handle carries no authority.
497type Handle struct {
498 Revision int64
499 Attempt AttemptID
500 Fence int64
501 Runner string
502}
503
504// Outcome closes the ways an attempt or action can end.
505type Outcome string
506
507const (
508 OutcomeSuccess Outcome = "success"
509 OutcomeFailure Outcome = "failure"
510)
511
512func (o Outcome) Valid() bool { return o == OutcomeSuccess || o == OutcomeFailure }
513
514// AttemptResult is a runner's terminal report for its attempt.
515type AttemptResult struct {
516 Outcome Outcome
517 Detail string
518}
519
520// Operation closes the set of external operations an action may name.
521type Operation string
522
523const (
524 OpProviderCall Operation = "provider.call"
525 OpForgePublish Operation = "forge.publish_branch"
526 OpTrackerPublish Operation = "tracker.publish_event"
527 OpJobContinue Operation = "job.continue" // authority check at startup
528 OpAttemptContinue Operation = "attempt.continue" // authority check at renewal
529)
530
531func (o Operation) Valid() bool {
532 switch o {
533 case OpProviderCall, OpForgePublish, OpTrackerPublish, OpJobContinue, OpAttemptContinue:
534 return true
535 }
536 return false
537}
538
539// external reports whether the operation is dispatched through an adapter.
540func (o Operation) external() bool {
541 return o == OpProviderCall || o == OpForgePublish || o == OpTrackerPublish
542}
543
544func operationAllowed(cap Capability, op Operation) bool {
545 switch op {
546 case OpProviderCall:
547 return cap.Valid()
548 case OpForgePublish, OpTrackerPublish:
549 return cap == CapPublish
550 default:
551 return false
552 }
553}
554
555// ReplayClass is the adapter's classification of an operation.
556type ReplayClass string
557
558const (
559 ReplayReadOnly ReplayClass = "read_only" // replay freely
560 ReplayIdempotent ReplayClass = "idempotent" // same key replays safely upstream
561 ReplayReconcilable ReplayClass = "reconcilable" // ask the adapter by key before replaying
562 ReplayUnsafe ReplayClass = "unsafe" // never replay without a receipt
563)
564
565func (c ReplayClass) Valid() bool {
566 switch c {
567 case ReplayReadOnly, ReplayIdempotent, ReplayReconcilable, ReplayUnsafe:
568 return true
569 }
570 return false
571}
572
573// ActionState is the closed action state set. Terminal states: succeeded,
574// failed, revoked. Uncertain is not terminal and blocks replay until an
575// adapter receipt or definitive absence resolves it.
576type ActionState string
577
578const (
579 ActionIntent ActionState = "intent" // persisted with its reservation, not admitted
580 ActionDispatching ActionState = "dispatching" // admitted in a transaction; the adapter may be running
581 ActionUncertain ActionState = "uncertain" // dispatched, reply lost
582 ActionSucceeded ActionState = "succeeded"
583 ActionFailed ActionState = "failed"
584 ActionRevoked ActionState = "revoked" // cancelled before dispatch; nothing was spent
585)
586
587func (s ActionState) Valid() bool {
588 switch s {
589 case ActionIntent, ActionDispatching, ActionUncertain, ActionSucceeded, ActionFailed, ActionRevoked:
590 return true
591 }
592 return false
593}
594
595func (s ActionState) Terminal() bool {
596 return s == ActionSucceeded || s == ActionFailed || s == ActionRevoked
597}
598
599// inFlight reports whether an external effect may exist and is unresolved.
600func (s ActionState) inFlight() bool { return s == ActionDispatching || s == ActionUncertain }
601
602// IntentSpec is what a runner asks the broker to record before anything
603// external happens. Payload must be a JSON object; it is canonicalised and
604// hashed, and a later intent under the same Key with a different hash is
605// ErrConflict. Reserve is the maximum usage the dispatch may consume and is
606// reserved in the same transaction.
607type IntentSpec struct {
608 Key string
609 Operation Operation
610 Payload []byte
611 Reserve Usage
612}
613
614// Action is the durable action record.
615type Action struct {
616 AdmittedIncarnation int64
617 ID ActionID
618 Job JobID
619 Step StepID
620 Attempt AttemptID
621 Fence int64
622 Key string
623 Operation Operation
624 Class ReplayClass
625 PayloadHash string
626 Payload []byte
627 State ActionState
628 Reservation ReservationID
629 Grant GrantSnapshot
630 AdmittedAt time.Time
631 AdmissionEnds time.Time
632 Receipt *Receipt
633 LastError string
634 CreatedAt time.Time
635 UpdatedAt time.Time
636}
637
638// Dispatch is the admitted, immutable request an adapter executes.
639type Dispatch struct {
640 Action ActionID
641 Key string
642 Operation Operation
643 Payload []byte
644 Hash string
645}
646
647// Receipt is an adapter's definitive answer. Usage nil means the adapter
648// could not measure usage; the reservation then stays open. Two receipts
649// for one action must carry the same ID and the same content, otherwise
650// the second is ErrReceiptConflict.
651type Receipt struct {
652 ID string `json:"id"`
653 Outcome Outcome `json:"outcome"`
654 Usage *Usage `json:"usage,omitempty"`
655 Provider string `json:"provider,omitempty"`
656 Model string `json:"model,omitempty"`
657 Effort string `json:"effort,omitempty"`
658 Detail string `json:"detail,omitempty"`
659 Fields map[string]string `json:"fields,omitempty"`
660}
661
662func (r Receipt) validate() error {
663 if r.ID == "" {
664 return fail(CodeInvalid, "receipt without id")
665 }
666 if !r.Outcome.Valid() {
667 return fail(CodeUnknownKind, "receipt outcome %q", r.Outcome)
668 }
669 if r.Usage != nil {
670 if err := r.Usage.validate(); err != nil {
671 return err
672 }
673 }
674 return nil
675}
676
677// ReconcileResult is an adapter's answer to "did key happen?". Definitive
678// with a nil Receipt means the adapter proves it did not; non-definitive
679// absence means wait.
680type ReconcileResult struct {
681 Receipt *Receipt
682 Definitive bool
683}
684
685// Event is one entry of a job's append-only log, appended in the same
686// transaction as the change it records.
687type Event struct {
688 Job JobID
689 Seq int64
690 Type string
691 Actor string
692 Payload []byte
693 SourceAt time.Time
694}
695
696// Role closes the set of artifact roles.
697type Role string
698
699const (
700 RoleAcceptance Role = "acceptance"
701 RoleAnswer Role = "answer"
702 RoleRender Role = "render"
703 RoleReproduction Role = "reproduction" // frozen reproduction, registered by reproduce before any candidate
704 RoleBaseResult Role = "base_result" // CheckResult of the reproduction on the base
705 RoleCandidate Role = "candidate" // candidate identity and content
706 RoleCandidateResult Role = "candidate_result" // CheckResult of the reproduction on the candidate
707 RoleRepositoryChecks Role = "repository_checks"
708 RoleReview Role = "review" // Review of an exact candidate or reconciliation
709 RoleSourceRecord Role = "source_record" // business input
710 RoleReconciliation Role = "reconciliation" // business output over source records
711)
712
713func (r Role) Valid() bool {
714 switch r {
715 case RoleAcceptance, RoleAnswer, RoleRender, RoleReproduction, RoleBaseResult, RoleCandidate, RoleCandidateResult, RoleRepositoryChecks, RoleReview, RoleSourceRecord, RoleReconciliation:
716 return true
717 }
718 return false
719}
720
721// roleAllowed is the closed capability -> role table.
722func roleAllowed(c Capability, r Role) bool {
723 switch c {
724 case CapScope:
725 return r == RoleAcceptance || r == RoleBaseResult
726 case CapResearch:
727 return r == RoleAnswer
728 case CapReproduce:
729 return r == RoleReproduction || r == RoleBaseResult
730 case CapImplement:
731 return r == RoleRender || r == RoleCandidate
732 case CapReview:
733 return r == RoleReview
734 case CapVerify:
735 return r == RoleRender || r == RoleCandidateResult || r == RoleBaseResult || r == RoleRepositoryChecks
736 case CapCollect:
737 return r == RoleSourceRecord
738 case CapReconcile:
739 return r == RoleReconciliation
740 }
741 return false
742}
743
744// Provenance records who produced an artifact: the producer identity, the
745// provider and model behind it and the context (conversation or session)
746// it came from. V2 also requires different observed model families.
747type Provenance struct {
748 ConnectionID string `json:"connection_id,omitempty"`
749 ModelFamily string `json:"model_family,omitempty"`
750 Isolation IsolationSnapshot `json:"isolation,omitzero"`
751 Producer string `json:"producer"`
752 Provider string `json:"provider"`
753 Model string `json:"model,omitempty"`
754 Context string `json:"context"`
755}
756
757func (p Provenance) validate() error {
758 if p.Producer == "" || p.Provider == "" || p.Context == "" {
759 return fail(CodeInvalid, "provenance needs producer, provider and context")
760 }
761 return nil
762}
763
764// ArtifactSpec is a registration request. The store computes the hash.
765type ArtifactSpec struct {
766 Role Role
767 MediaType string
768 Payload []byte
769 Provenance Provenance
770}
771
772// Artifact is the immutable registered record.
773type Artifact struct {
774 ID ArtifactID
775 Job JobID
776 Step StepID
777 Attempt AttemptID
778 Fence int64
779 Role Role
780 Hash string
781 MediaType string
782 Size int64
783 Provenance Provenance
784 Payload []byte
785 CreatedAt time.Time
786}
787
788// CheckOutcome closes the ways a check run can end. Only Fail counts as the
789// expected base failure and only Pass as a candidate pass; everything else
790// is invalid evidence.
791type CheckOutcome string
792
793const (
794 CheckPass CheckOutcome = "pass"
795 CheckFail CheckOutcome = "fail"
796 CheckCompileError CheckOutcome = "compile_error"
797 CheckSkipped CheckOutcome = "skipped"
798 CheckNoTests CheckOutcome = "no_tests"
799)
800
801func (c CheckOutcome) Valid() bool {
802 switch c {
803 case CheckPass, CheckFail, CheckCompileError, CheckSkipped, CheckNoTests:
804 return true
805 }
806 return false
807}
808
809// CheckResult is the JSON payload of base_result and candidate_result
810// artifacts: which reproduction ran, on what, under which check
811// definition, and what happened.
812type CheckResult struct {
813 ExitCode int `json:"exit_code,omitempty"`
814 LogHash string `json:"log_hash,omitempty"`
815 SubjectCommit string `json:"subject_commit,omitempty"`
816 OverlayHash string `json:"overlay_hash,omitempty"`
817 CollisionChecked bool `json:"collision_checked,omitempty"`
818 ObservedNames []TestIdentity `json:"observed_names,omitempty"`
819 Isolation IsolationSnapshot `json:"isolation,omitzero"`
820 ExecutorBinary string `json:"executor_binary,omitempty"`
821 ExecutorVersion string `json:"executor_version,omitempty"`
822 ReproductionHash string `json:"reproduction_hash"`
823 SubjectHash string `json:"subject_hash"`
824 CheckDefinitionHash string `json:"check_definition_hash"`
825 Outcome CheckOutcome `json:"outcome"`
826 TestsRun int `json:"tests_run"`
827 TestsFailed int `json:"tests_failed"`
828 FailureMessage string `json:"failure_message,omitempty"`
829}
830
831// Verdict closes a review's answer.
832type Verdict string
833
834const (
835 VerdictApprove Verdict = "approve"
836 VerdictReject Verdict = "reject"
837)
838
839func (v Verdict) Valid() bool { return v == VerdictApprove || v == VerdictReject }
840
841// Review is the JSON payload of a review artifact: the exact subject hash
842// (candidate or reconciliation) and the verdict. Independence comes from
843// the artifact's Provenance, not from this payload.
844type Review struct {
845 SubjectHash string `json:"subject_hash"`
846 Verdict Verdict `json:"verdict"`
847 Notes string `json:"notes,omitempty"`
848}
849
850// Reconciliation is the JSON payload of a reconciliation artifact.
851type Reconciliation struct {
852 SourceHashes []string `json:"source_hashes"`
853 Matched int `json:"matched"`
854 Discrepancies []Discrepancy `json:"discrepancies"`
855}
856
857// Discrepancy is one explicit unresolved difference between sources.
858type Discrepancy struct {
859 Key string `json:"key"`
860 Detail string `json:"detail"`
861}
862
863// Usage is integer accounting. CostMicros is in micro-units of the
864// configured currency. All fields are non-negative; arithmetic on them is
865// checked and refuses overflow.
866type Usage struct {
867 CachedInputTokens int64 `json:"cached_input_tokens,omitempty"`
868 CostUnavailable bool `json:"cost_unavailable,omitempty"`
869 Calls int64 `json:"calls"`
870 InputTokens int64 `json:"input_tokens"`
871 OutputTokens int64 `json:"output_tokens"`
872 CostMicros int64 `json:"cost_micros"`
873}
874
875func (u Usage) validate() error {
876 if u.CachedInputTokens < 0 || u.Calls < 0 || u.InputTokens < 0 || u.OutputTokens < 0 || u.CostMicros < 0 {
877 return fail(CodeInvalid, "negative usage")
878 }
879 return nil
880}
881
882func (u Usage) add(v Usage) (Usage, error) {
883 var out Usage
884 out.CostUnavailable = u.CostUnavailable || v.CostUnavailable
885 var err error
886 if out.CachedInputTokens, err = addChecked(u.CachedInputTokens, v.CachedInputTokens); err != nil {
887 return out, err
888 }
889 if out.Calls, err = addChecked(u.Calls, v.Calls); err != nil {
890 return out, err
891 }
892 if out.InputTokens, err = addChecked(u.InputTokens, v.InputTokens); err != nil {
893 return out, err
894 }
895 if out.OutputTokens, err = addChecked(u.OutputTokens, v.OutputTokens); err != nil {
896 return out, err
897 }
898 if out.CostMicros, err = addChecked(u.CostMicros, v.CostMicros); err != nil {
899 return out, err
900 }
901 return out, nil
902}
903
904// within reports whether u fits under l.
905func (u Usage) within(l Limits) bool {
906 return u.Calls <= l.Calls && u.InputTokens <= l.InputTokens && u.OutputTokens <= l.OutputTokens && u.CostMicros <= l.CostMicros
907}
908
909func addChecked(a, b int64) (int64, error) {
910 if a < 0 || b < 0 {
911 return 0, fail(CodeInvalid, "negative accounting value")
912 }
913 s := a + b
914 if s < a {
915 return 0, fail(CodeOverflow, "sum overflows")
916 }
917 return s, nil
918}
919
920func mulChecked(a, b int64) (int64, error) {
921 if a < 0 || b < 0 {
922 return 0, fail(CodeInvalid, "negative accounting value")
923 }
924 if a == 0 || b == 0 {
925 return 0, nil
926 }
927 p := a * b
928 if p/b != a {
929 return 0, fail(CodeOverflow, "product overflows")
930 }
931 return p, nil
932}
933
934// ReservationState closes the ledger row states.
935type ReservationState string
936
937const (
938 ReservationOpen ReservationState = "open"
939 ReservationSettled ReservationState = "settled"
940 ReservationSettledAudited ReservationState = "settled_audited" // conservative operator settlement at the reserved maximum
941 ReservationReleased ReservationState = "released" // intent revoked before anything was dispatched
942)
943
944func (s ReservationState) Valid() bool {
945 switch s {
946 case ReservationOpen, ReservationSettled, ReservationSettledAudited, ReservationReleased:
947 return true
948 }
949 return false
950}
951
952// Reservation is one ledger row.
953type Reservation struct {
954 ID ReservationID
955 Account AccountID
956 Job JobID
957 Step StepID
958 Attempt AttemptID
959 Action ActionID
960 Reserved Usage
961 Settled Usage
962 State ReservationState
963 ReceiptID string
964 SettledBy string
965 CreatedAt time.Time
966 SettledAt time.Time
967}
968
969// LedgerSummary is reserved-plus-spent accounting for one scope. Reserved
970// counts open reservations at their reserved maximum; Spent counts settled
971// ones at their settled usage. Charged is the sum both limits are checked
972// against.
973type LedgerSummary struct {
974 Reserved Usage
975 Spent Usage
976 Charged Usage
977}
978
979// Limits bounds usage. Every field is a hard cap.
980type Limits struct {
981 Seconds int64 `json:"seconds,omitempty"`
982 Calls int64 `json:"calls"`
983 InputTokens int64 `json:"input_tokens"`
984 OutputTokens int64 `json:"output_tokens"`
985 CostMicros int64 `json:"cost_micros"`
986}
987
988func (l Limits) validate(what string) error {
989 if l.Calls <= 0 || l.InputTokens <= 0 || l.OutputTokens <= 0 || l.CostMicros <= 0 {
990 return fail(CodeInvalid, "%s limits must all be positive and explicit", what)
991 }
992 return nil
993}
994
995// CancelReport is what Cancel returns: the job is cancelled, but stops may
996// still be pending and external effects may be in flight. Neither is
997// claimed complete here.
998type CancelReport struct {
999 Children []CancelReport // descendant scopes whose workers must also stop
1000 Job JobID
1001 Revision int64
1002 StopsPending []AttemptID
1003 InFlight []ActionID
1004 Revoked []ActionID
1005 OpenReserved Usage
1006}
1007
1008// Status is the store's startup/quarantine state.
1009type Status struct {
1010 Incarnation int64
1011 AdmissionPaused bool
1012 Quarantine bool
1013 QuarantineWhy string
1014 SchemaVersion int
1015}
1016