Add revision conventions and resumable cross-app scheduling

codex agent, operated by paul@keymail.dev pushed by paul@keymail.dev e4ea91480ce6e33476b3824a73261caee301b928 parent 72d48f5
18 files changed, +1,362 −27
  • README.md +42 −1
  • client/client.go +1 −1
  • client/failure_test.go +31 −0
  • connection/server.go +4 −3
  • docs/api-conventions.md +67 −0
  • docs/resumable-scheduling.md +150 −0
  • failure.go +29 −0
  • gateway.go +30 −19
  • go.mod +2 −2
  • go.sum +2 −0
  • mcp.go +4 −0
  • operation.go +4 −1
  • schedule.go +314 −0
  • schedule_contract.go +66 −0
  • schedule_guard.go +24 −0
  • schedule_interop_test.go +192 −0
  • schedule_test.go +350 −0
  • scripts/suite-interop.py +50 −0

CI passed — run details

CI log
=== ci ===
go vet ./...
go: downloading github.com/gofrs/flock v0.12.1
go: downloading github.com/zalando/go-keyring v0.2.8
go: downloading golang.org/x/oauth2 v0.35.0
go: downloading github.com/modelcontextprotocol/go-sdk v1.7.0
go: downloading amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060
go: downloading amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489
go: downloading modernc.org/sqlite v1.55.0
go: downloading github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2
go: downloading github.com/google/uuid v1.6.0
go: downloading github.com/santhosh-tekuri/jsonschema/v6 v6.0.3
go: downloading golang.org/x/sys v0.46.0
go: downloading github.com/godbus/dbus/v5 v5.2.2
go: downloading github.com/google/jsonschema-go v0.4.3
go: downloading github.com/yosida95/uritemplate/v3 v3.0.2
go: downloading golang.org/x/sync v0.21.0
go: downloading golang.org/x/time v0.15.0
go: downloading gorm.io/gorm v1.31.2
go: downloading gorm.io/plugin/dbresolver v1.6.2
go: downloading golang.org/x/text v0.39.0
go: downloading github.com/segmentio/encoding v0.5.4
go: downloading github.com/jinzhu/now v1.1.5
go: downloading modernc.org/libc v1.74.1
go: downloading github.com/jinzhu/inflection v1.0.0
go: downloading github.com/segmentio/asm v1.1.3
go: downloading github.com/dustin/go-humanize v1.0.1
go: downloading modernc.org/mathutil v1.7.1
go: downloading modernc.org/memory v1.11.0
go: downloading github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec
go test -race ./...
ok  	amadan.net/oficina/agent-access.git	2.172s
ok  	amadan.net/oficina/agent-access.git/client	1.045s
?   	amadan.net/oficina/agent-access.git/cmd/oficina	[no test files]
ok  	amadan.net/oficina/agent-access.git/cmd/oficina-connect	5.509s
ok  	amadan.net/oficina/agent-access.git/connection	1.422s
ok  	amadan.net/oficina/agent-access.git/grant	1.545s
diff --git a/README.md b/README.md
index 0810502..6ee5c9d 100644
--- a/README.md
+++ b/README.md
@@ -9,7 +9,8 @@ CLI, browser consent with PKCE, rotating refresh tokens and revocation are
implemented. Tests exercise browser authorization through an HTTPS fixture,
including real loopback callbacks and the signed Home identity handoff. A runnable
connection service and reviewed adapters for Docs, Sheets, Memoria, Calendar,
-Calls and Slides are on feature branches, exposing 20 operations. Live four-client
+Calls and Slides are on feature branches, exposing 27 app operations plus the
+shared `calls_schedule` workflow (28 total). Live four-client
acceptance and deployment remain outstanding. No production endpoint is deployed.
Each request supplies a verified person, client, grant, selected teams and
@@ -167,3 +168,43 @@ or infrastructure change occurs. It checks the native artifact through the real
`carlos vet --boot` contract. Repeat on Linux/arm64 with `--target linux-arm64`
for the deployment artifact. The generated fixture is only for boot verification,
never a production secret or a valid live app registration.
+
+
+## Editing and interoperability
+
+The [shared conventions](docs/api-conventions.md) define opaque IDs, resource
+references, revision preconditions, immutable retry acknowledgements and stable
+failure categories. Existing operation names and identifier types are retained.
+
+| App | Added operation | Supported editing |
+| --- | --- | --- |
+| Docs | `docs_update` | Bounded paragraph/heading splices; untouched rich content is preserved |
+| Sheets | `sheets_set_range` | Atomic ordered cell inputs with native formula recalculation |
+| Slides | `slides_update_deck` | Thirteen discoverable semantic operation variants |
+| Memoria | `notes_get`, `notes_update` | Read/replace local notes with indexing; imported items remain read-only |
+| Calendar | `calendar_update_event` | Patch single noncancelled events, preserving omitted fields and repairing reminders |
+| Calls | `calls_reserve_schedule` | Bind a workflow UUID to a keyed request fingerprint |
+
+Each new edit requires the revision returned by its app's read operation and a
+fresh UUID `client_id`. An exact retry returns its original acknowledgement;
+a changed request with that UUID conflicts. Read again for the current content.
+This is bounded editing support, not complete browser feature parity: Docs rich
+formatting, Sheets tab/format management, and Calendar recurrence/cancellation
+remain outside these new operations.
+
+`oficina calls schedule --team acme --input schedule.json` invokes
+[resumable scheduling](docs/resumable-scheduling.md). It creates an optional Docs
+agenda, a Calls meeting, and a Calendar event containing their member URLs.
+The same operation is available through HTTP and MCP. It requires read and write
+scopes in each selected app. No invitation is sent and a URL grants no access.
+A partial result identifies confirmed and unconfirmed steps. Resume with the
+same UUID and exact original JSON: a lost response may hide a committed write.
+This is synchronous retry-based recovery, not a background job or a transaction
+spanning apps.
+
+Run `python3 scripts/suite-interop.py --workspace /path/to/oficina` with sibling
+`docs-agent-access`, `calls-agent-access` and `calendar-agent-access` worktrees.
+It builds opt-in test binaries and uses temporary sealed app stores and private
+HTTPS fixtures. The test exercises CLI creation, a lost committed response,
+fresh-gateway MCP resumption, readable linked resources, exact retries, conflicting
+retry arguments and revocation. No live account or production service is used.
diff --git a/client/client.go b/client/client.go
index aaf09fe..a1b2d4a 100644
--- a/client/client.go
+++ b/client/client.go
@@ -70,7 +70,7 @@ func (c *Client) readJSON(ctx context.Context, req *http.Request, out any) error
return errors.New("invalid or oversized Oficina response")
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- return fmt.Errorf("Oficina returned HTTP %d", resp.StatusCode)
+ return access.FailureForStatus(resp.StatusCode)
}
if access.DecodeJSON(raw, out) != nil {
return errors.New("Oficina returned invalid JSON")
diff --git a/client/failure_test.go b/client/failure_test.go
new file mode 100644
index 0000000..a5b27c6
--- /dev/null
+++ b/client/failure_test.go
@@ -0,0 +1,31 @@
+package client
+
+import (
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ access "amadan.net/oficina/agent-access.git"
+)
+
+func TestRemoteFailuresRetainCategoryWithoutRemoteContent(t *testing.T) {
+ for status, code := range map[int]string{401: "unauthenticated", 403: "forbidden", 404: "not_found", 409: "conflict", 413: "too_large", 415: "unsupported_media_type", 422: "invalid", 429: "rate_limited", 500: "internal", 503: "unavailable", 302: "unavailable"} {
+ t.Run(code, func(t *testing.T) {
+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(status)
+ w.Write([]byte(`{"error":{"code":"forbidden","message":"private-document-marker"}}`))
+ }))
+ defer s.Close()
+ c := New(nil)
+ req, _ := http.NewRequest("GET", s.URL, nil)
+ var out any
+ err := c.readJSON(t.Context(), req, &out)
+ var failure access.Failure
+ if !errors.As(err, &failure) || failure.Code != code || strings.Contains(err.Error(), "private-document-marker") {
+ t.Fatalf("%d: %v", status, err)
+ }
+ })
+ }
+}
diff --git a/connection/server.go b/connection/server.go
index d262886..d893dfe 100644
--- a/connection/server.go
+++ b/connection/server.go
@@ -144,9 +144,10 @@ func New(ctx context.Context, cfg Config, d *db.DB, logger *slog.Logger) (*Serve
return nil, err
}
mux.Handle("/mcp", grants.ResourceHandler(mcpHandler))
- mux.Handle("/api/v1/connection", grants.ResourceHandler(registry.HTTP(grants)))
- mux.Handle("/api/v1/operations", grants.ResourceHandler(registry.HTTP(grants)))
- mux.Handle("/api/v1/operations/", grants.ResourceHandler(registry.HTTP(grants)))
+ api := registry.HTTPGuarded(grants, grants, registry.ScheduleResponseGuard)
+ mux.Handle("/api/v1/connection", grants.ResourceHandler(api))
+ mux.Handle("/api/v1/operations", grants.ResourceHandler(api))
+ mux.Handle("/api/v1/operations/", grants.ResourceHandler(api))
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(200) })
mux.Handle("/", grants.Handler())
u, _ := url.Parse(cfg.Origin)
diff --git a/docs/api-conventions.md b/docs/api-conventions.md
new file mode 100644
index 0000000..7ced28a
--- /dev/null
+++ b/docs/api-conventions.md
@@ -0,0 +1,67 @@
+# API conventions and editing contract
+
+Status: November 1 specification by GPT-6 Astra; independently approved by GPT-6 Astra (review_docs_access). Applies to
+the shared delegated operation interface, not a replacement for editor/native
+wire protocols. Existing operation contracts remain compatible.
+
+## Resource identity and revisions
+
+Resource IDs are opaque and app-scoped. Never parse one app's ID as another's,
+infer team membership from a URL, or use a returned URL as a routing argument.
+Existing `id`, `sqid`, `sheet_id` and `tab_id` fields retain their types. Exact
+JSON integers must survive all transports without a float conversion.
+
+New cross-app references use `{team,app,id,url}` with an opaque string ID and a
+canonical member-facing URL. A reference grants no access; each destination
+checks the current person. It is never a guest invitation or bearer URL.
+The configured directory and app routes remain the routing authority.
+
+An edit supplies a canonical nonzero UUID `client_id` and `expected_revision`.
+The precondition has the type and exact value returned by that app's read:
+Docs `body_revision`, Sheets/Slides `revision` (decimal strings), Memoria
+`revision` and Calendar `sequence` (integers). Revisions are equality tokens,
+not a suite-wide clock. A new stale edit is `conflict` with no effects.
+
+The domain write, revision check and immutable retry receipt share one writer
+transaction. Receipts bind authority/subject/client/team/operation/UUID and the
+full request, including the target and precondition. Exact completed retries
+recheck current access and the live target, return the original applied revision,
+and never apply the edit again or overwrite later edits. Reusing a UUID with
+different arguments is `conflict`. Removed resources are not recreated.
+New edit acknowledgements report their original applied `revision`; read again
+for current content. Existing create acknowledgement behavior is unchanged.
+
+Browser, native and delegated edits use the same canonical domain mutations.
+Editable content retains the original app's collaboration, sealing, attribution,
+indexing and reminder semantics. An unsupported edit is explicitly refused.
+
+## Errors, pagination and compatibility
+
+HTTP failures use `{error:{code,message}}`. Stable codes map to 401
+`unauthenticated`, 403 `forbidden`, 404 `not_found`, 409 `conflict`, 413
+`too_large`, 415 `unsupported_media_type`, 422 `invalid`, 429 `rate_limited`,
+503 `unavailable`, and 500 `internal`. Gateways and clients retain the code
+without forwarding arbitrary remote error prose, HTML or credentials. Neither
+a timeout nor `unavailable` proves a write failed: retry with the original
+UUID and exact request. Authorization refusals are not automatic retry loops.
+
+Existing pagination remains as exported: Calls uses `after/next_after/has_more`;
+Docs, Sheets and Slides use `cursor/next_cursor`. New paginated operations use
+opaque `cursor`, bounded `limit`, and `next_cursor`, empty at the end. Do not
+silently rename fields in old operations. Document limits and partial results.
+
+Exported operation schemas are the machine contract for HTTP, CLI and MCP.
+Removing/renaming a field, tightening accepted inputs or changing meaning needs
+a new operation/version and a migration path. New operations are additive;
+existing scopes do not expand to sharing, deletion or invitation delivery.
+App exports and connection routes must agree exactly. Compatibility tests use
+real exported contracts and behavior, not a parallel handwritten schema.
+
+## Authorized next slice
+
+`docs_update`, `sheets_set_range`, `slides_update_deck`, `notes_get`,
+`notes_update`, and `calendar_update_event` complete the bounded editing loop.
+Per-app amendments define supported content and the tests behind each boundary.
+The scheduling amendment adds resumable composition of already authorized
+creates. Search/export/sharing/history gaps remain listed as gaps; this slice
+does not claim every browser action is automated.
diff --git a/docs/resumable-scheduling.md b/docs/resumable-scheduling.md
new file mode 100644
index 0000000..cd17884
--- /dev/null
+++ b/docs/resumable-scheduling.md
@@ -0,0 +1,150 @@
+# Resumable cross-app scheduling
+
+Status: November 1 draft by GPT-6 Astra, independently reviewed and approved by GPT-6 Astra (review_docs_access), November 1. The user
+authorized implementing the everyday editing APIs, shared conventions and one
+substantial workflow including interruption, retry and revoked access.
+
+## Boundary
+
+`calls_schedule` is a synchronous composite operation in the connection gateway.
+It creates an optional Docs agenda, a Calls meeting and a Calendar event holding
+their member-facing URLs. It sends no invitations, grants no new access and
+does not claim a reservation from advisory free/busy. It never deletes objects
+automatically to undo a partial result. There is no cross-app transaction.
+
+The gateway stores no workflow inputs, results or credentials. Durable state
+is the workflow fingerprint reservation in the selected team's Calls database
+plus each app's existing atomic create receipts. Resumption means submitting the
+same UUID and original arguments again, even after every process restarts.
+This is not a background job, autonomous retry service or a status-only API.
+The client must retain its original request. No cross-team composition exists.
+
+## Input and reservation
+
+Input: `{team,client_id,title,calendar_id,start,end,tz,notes,agenda?}`. `start`
+and `end` are RFC3339 instants with explicit offsets; `tz` is an IANA zone.
+The offsets must match that zone at both instants, end must follow start, and
+local date/time conversion must round-trip without ambiguity. Calendar's own
+validator is authoritative. `agenda` contains a title and the bounded literal
+blocks accepted by `docs_create`. Unknown fields are rejected.
+
+Before any content effect, validate all known downstream inputs against
+the configured exported schemas, every required route for this exact team, and
+all scopes: `calls:read`, `calls:write`, `calendar:read`, `calendar:write`, plus
+`docs:read` and `docs:write` for an agenda.
+Each step obtains a fresh audience-bound credential using the original current
+principal. Current directory membership and destination checks remain in force.
+
+New app operation `calls_reserve_schedule` (`calls:write`) takes
+`{team,client_id,fingerprint}` and returns `{reserved:true}`. The fingerprint
+is the lower-case SHA-256 of the normalized complete typed workflow request,
+including version `1`. Calls stores only keyed fingerprints: a domain-separated
+coordinate binding identity/delegation issuers, subject, client, team, operation
+and UUID, and a keyed fingerprint of the supplied digest. No title, event text,
+agenda, credentials or remote resource coordinates are persisted there. The
+reservation is atomic, stable across restart and bound by existing immutable
+authority configuration. Same UUID/different fingerprint refuses before effects.
+The operation can also be called directly; it only reserves a fingerprint, never
+claims that another app committed a step and never grants authority.
+
+The gateway derives distinct deterministic nonzero UUIDs for agenda, meeting and
+event from the root UUID and a versioned step namespace. Existing app receipts
+also bind person/client/team/authority; two people using the same UUID cannot
+collide. The full-input reservation prevents changed later fields from causing
+partial changes under an already-used workflow UUID. There is no receipt expiry
+that permits implicit recreation within this implementation.
+
+## Execution and results
+
+Order: reserve, optional agenda, meeting, event. After each success record only
+the response in transient memory. The Calendar event gets explicit local start,
+end and zone, `kind:meeting`, confirmed status, supplied notes plus canonical agenda
+and meeting member URLs. Exact enum values follow the exported app contract.
+URLs are checked against the corresponding configured app origin and known
+resource route; no external response URL is fetched. Invitations remain false.
+
+Replays execute the same sequence with the same step IDs. App receipts return
+the prior resources and preserve later manual changes. If a prior resource was
+deleted or access was removed, stop; do not recreate it or skip the failure.
+An ambiguous/lost response is retried only with the same step UUID. Concurrent
+requests rely on each app's atomic uniqueness and receipt transaction.
+
+Result: workflow UUID, team, `status:complete|partial`, confirmed step references,
+`invitations_sent:false`, and, on partial completion, a failed step plus a fixed
+failure code. Unattempted steps are distinguishable from confirmed steps. A
+failed request may nevertheless have committed; failure is not a nonexistence
+claim. When authorization is lost, return an authorization failure without
+previously selected resource details. On other errors, revalidate selected
+resources under current authority before releasing partial details. Completed
+responses likewise revalidate selected resources. A later retry rediscovers
+progress through receipts, not an unverified checkpoint supplied by a client.
+
+## Evidence
+
+Use exported app contracts to validate every step and the composite contract.
+Test whole success, missing scope/route before effects, changed-input reservation,
+failure and lost response after each commit, full restart and replay, concurrent
+retries, deletion/manual edit after partial completion, same UUID across users,
+revocation between each step and before response, false/foreign URLs, DST gaps
+and folds, result limits, HTTP/CLI/MCP parity, and real app store effects.
+Remove reservation binding, step-ID stability and revalidation separately to
+prove the behavioral gates fail. Source review precedes deployment; existing
+team adoption and scoped infrastructure approval remain separate live gates.
+
+## Review resolutions (November 1)
+
+Require read scopes as well as write scopes. Resource revalidation uses only
+`docs_get`, `calls_get_meeting`, and `calendar_get_event`, never mutation replay.
+Before every step and after all read checks, validate every required scope/team/
+destination through the credential provider against the original immutable
+Subject/Client/Grant. Any unavailable/refused revalidation suppresses all
+references. HTTP uses the existing guarded emission path before headers/chunks;
+MCP revalidates before returning the bounded tool result to the SDK. There is no
+claim of a cross-app atomic snapshot or byte-by-byte authorization inside the SDK.
+
+Preflight validates known fields only. Generated URLs are validated against
+trusted routes and schemas before subsequent use; authoritative app validation
+can still refuse a later step and leave an honest partial result. No pure
+Calendar preflight endpoint is claimed. Calendar local minute precision requires
+zero input seconds/nanoseconds; offsets and ambiguity are checked before effects.
+
+The fingerprint is SHA-256 of JSON for a version-1 typed request, with exact
+int64 calendar ID and fields in declared order. UUID spelling is canonical;
+title/notes/zone and canonical RFC3339 start/end spelling are preserved. Agenda
+absence is nil; paragraph level omission normalizes to zero. Versioned step IDs
+are RFC4122 v5 using namespace 8ba3600d-9e03-52df-8c34-9ff05a6e66cb and the exact
+name `oficina.schedule.v1/<root UUID>/<agenda|meeting|event>`. Receipts additionally
+bind actor, client and team. Responses are limited below 64 KiB.
+
+
+## Implementation evidence (2026-11-01)
+
+The opt-in `TestSuiteSchedulingInterop` passed against the real Docs, Calls and
+Calendar delegated HTTP handlers, their exported contracts, sealed stores and
+atomic create receipts. The CLI adapter observed a partial result after a
+transport deliberately lost Calendar's committed reply. A fresh gateway's MCP
+server completed the unchanged request, returned identical resources on replay,
+and exposed the expected agenda body and both cross-app URLs in the event.
+Changed arguments conflicted and revoked credentials refused resumption.
+`python3 scripts/suite-interop.py` reproduces this with temporary private stores.
+This does not establish deployed Home/team setup or hosted-client acceptance.
+
+The shared tests additionally drop responses after every step, reject revoked
+read scopes before writes, withhold results after revocation, reject foreign
+resource URLs, recheck deleted resources with pure reads, reject malformed
+Unicode before reservation, reject DST folds/gaps, and recheck authority at the
+MCP result-return seam after registry output validation.
+
+Independent GPT-6 Astra review selected six shared-runtime fault mutations:
+accept malformed Unicode, omit the MCP final guard, omit final resource checks,
+skip an earlier app's scope, accept a foreign URL, and randomize retry step IDs.
+Each caused a behavioral test failure; no build failure counted as detection.
+All original sources were restored. Resource references additionally validate
+against the destination's read schema and member-route ID shape before use;
+the response guard verifies the step, app, ID and canonical URL together.
+
+Final shared implementation review: GPT-6 Astra (`review_docs_access`) approved
+on 2026-11-01 after inspecting source, all six effective mutation failures and
+the three-app acceptance evidence. The restored source passed `make ci`,
+including all-package race tests. Calls roster reconciliation and reservation
+have their own app review and gate; live four-client acceptance remains pending.
diff --git a/failure.go b/failure.go
new file mode 100644
index 0000000..aeae1eb
--- /dev/null
+++ b/failure.go
@@ -0,0 +1,29 @@
+package agentaccess
+
+// FailureForStatus preserves the public error category without copying remote
+// prose. Bodies may contain app content, HTML, credentials or proxy errors.
+// No transport failure proves that an attempted mutation did not commit.
+func FailureForStatus(status int) Failure {
+ switch status {
+ case 401:
+ return Failure{"unauthenticated", "Connect to Oficina again."}
+ case 403:
+ return Failure{"forbidden", "Current access does not allow this operation."}
+ case 404:
+ return Failure{"not_found", "The app or item is unavailable."}
+ case 409:
+ return Failure{"conflict", "Check the resource revision and retry identifier."}
+ case 413:
+ return Failure{"too_large", "The request or result exceeds the app's limit."}
+ case 415:
+ return Failure{"unsupported_media_type", "Send application/json."}
+ case 400, 422:
+ return Failure{"invalid", "Check the arguments against the operation schema."}
+ case 429:
+ return Failure{"rate_limited", "The app is busy. Try again later."}
+ case 500:
+ return Failure{"internal", "The app could not confirm the operation."}
+ default:
+ return Failure{"unavailable", "The app could not confirm the operation. Retry writes only with the original client_id and arguments."}
+ }
+}
diff --git a/gateway.go b/gateway.go
index f8dceac..2faf883 100644
--- a/gateway.go
+++ b/gateway.go
@@ -98,24 +98,7 @@ func Gateway(routes []Route, credentials CredentialProvider, transport http.Roun
return nil, Fail("unavailable", "The app returned an unreadable response.")
}
if response.StatusCode != 200 {
- // Do not forward arbitrary HTML, content-bearing server errors,
- // redirect destinations or credentials into an agent conversation.
- code, message := "unavailable", "The app could not confirm the operation."
- switch response.StatusCode {
- case 401:
- code, message = "unauthenticated", "The app refused this connection."
- case 403:
- code, message = "forbidden", "The app refused access. Check account linking and current membership."
- case 404:
- code, message = "not_found", "The app or item is unavailable."
- case 409:
- code, message = "conflict", "The app reported a conflict. Check the revision or retry key."
- case 400, 422:
- code, message = "invalid", "The app refused these arguments. Check the operation schema."
- case 429:
- code, message = "rate_limited", "The app is busy. Try again later."
- }
- return nil, Fail(code, message)
+ return nil, FailureForStatus(response.StatusCode)
}
var output any
if DecodeJSON(body, &output) != nil {
@@ -125,5 +108,33 @@ func Gateway(routes []Route, credentials CredentialProvider, transport http.Roun
}
operations = append(operations, op)
}
- return NewRegistry(operations...)
+ base, err := NewRegistry(operations...)
+ if err != nil {
+ return nil, err
+ }
+ schedule := &scheduler{registry: base, credentials: credentials, routes: map[string]map[string]string{}}
+ for key, resource := range destinations {
+ if schedule.routes[key.team] == nil {
+ schedule.routes[key.team] = map[string]string{}
+ }
+ schedule.routes[key.team][key.name] = resource
+ }
+ // A reservation-capable Calls release opts a team into the composite. Old
+ // deployments retain exactly their existing operation set.
+ for team := range schedule.routes {
+ ready := true
+ for _, name := range schedule.required(false) {
+ ready = ready && schedule.routes[team][name] != ""
+ }
+ if !ready {
+ continue
+ }
+ out, err := NewRegistry(append(operations, schedule.operation())...)
+ if err != nil {
+ return nil, err
+ }
+ out.schedule = schedule
+ return out, nil
+ }
+ return base, nil
}
diff --git a/go.mod b/go.mod
index 7677523..42d979f 100644
--- a/go.mod
+++ b/go.mod
@@ -5,7 +5,9 @@ go 1.25.0
require (
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489
amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060
+ github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2
github.com/gofrs/flock v0.12.1
+ github.com/google/uuid v1.6.0
github.com/modelcontextprotocol/go-sdk v1.7.0
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3
github.com/zalando/go-keyring v0.2.8
@@ -16,10 +18,8 @@ require (
require (
github.com/danieljoos/wincred v1.2.3 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
- github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 // indirect
github.com/godbus/dbus/v5 v5.2.2 // indirect
github.com/google/jsonschema-go v0.4.3 // indirect
- github.com/google/uuid v1.6.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
diff --git a/go.sum b/go.sum
index 9db3d8d..ee7d97e 100644
--- a/go.sum
+++ b/go.sum
@@ -2,6 +2,8 @@ amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 h1:RPKtyry/71
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k=
amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060 h1:K2PXcCKfm+AYrqgH1ea6cNsFs4sN7MKLvq+uBY11NZE=
amadan.net/rastrillo/rastrillo v0.27.1-0.20261006204347-fb806a287060/go.mod h1:WmC8TAIfqjAkSwmD+FCTqr7VuqAO5FaX03HlV49K608=
+amadan.net/rastrillo/rastrillo/money v0.1.0 h1:MxU4oqNrW8abxRTkgZBv24OYNpFnvonajNqeLIzmmaM=
+amadan.net/rastrillo/rastrillo/money v0.1.0/go.mod h1:cmgkjBEIQh1pFSYvQk0UU6oPYS8kSDypdT9+t4Flx0U=
github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ=
github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
diff --git a/mcp.go b/mcp.go
index d0f4a03..7bf80e9 100644
--- a/mcp.go
+++ b/mcp.go
@@ -29,6 +29,10 @@ func (r *Registry) MCPServer(p Principal) *mcp.Server {
if err != nil {
return nil, err
}
+ if err := r.ScheduleResponseGuard(ctx, p, op.Name, req.Params.Arguments, result); err != nil {
+ f := SafeFailure(err)
+ return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: f.Error()}}}, nil
+ }
return &mcp.CallToolResult{StructuredContent: result, Content: []mcp.Content{&mcp.TextContent{Text: string(raw)}}}, nil
})
}
diff --git a/operation.go b/operation.go
index 5a92612..f387cd4 100644
--- a/operation.go
+++ b/operation.go
@@ -67,7 +67,10 @@ type compiled struct {
op Operation
input, output *jsonschema.Schema
}
-type Registry struct{ operations map[string]compiled }
+type Registry struct {
+ operations map[string]compiled
+ schedule *scheduler
+}
var namePattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`)
diff --git a/schedule.go b/schedule.go
new file mode 100644
index 0000000..1d12068
--- /dev/null
+++ b/schedule.go
@@ -0,0 +1,314 @@
+package agentaccess
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "strconv"
+ "strings"
+ "time"
+ _ "time/tzdata" // Standalone binaries must validate IANA zones on minimal hosts.
+
+ strictjson "github.com/go-json-experiment/json"
+ "github.com/google/uuid"
+)
+
+type scheduler struct {
+ registry *Registry
+ credentials CredentialProvider
+ routes map[string]map[string]string // team, operation -> trusted resource
+}
+
+var scheduleNamespace = uuid.MustParse("8ba3600d-9e03-52df-8c34-9ff05a6e66cb")
+
+func scheduleID(root, step string) string {
+ return uuid.NewSHA1(scheduleNamespace, []byte("oficina.schedule.v1/"+root+"/"+step)).String()
+}
+func (s *scheduler) required(agenda bool) []string {
+ ops := []string{"calls_reserve_schedule", "calls_create_meeting", "calls_get_meeting", "calendar_create_event", "calendar_get_event"}
+ if agenda {
+ ops = append(ops, "docs_create", "docs_get")
+ }
+ return ops
+}
+func (s *scheduler) available(p Principal) bool {
+ for _, team := range p.Teams {
+ if s.eligible(p, team, false) == nil {
+ return true
+ }
+ }
+ return false
+}
+func (s *scheduler) eligible(p Principal, team string, agenda bool) error {
+ for _, name := range s.required(agenda) {
+ op, ok := s.registry.operations[name]
+ if !ok || s.routes[team][name] == "" {
+ return Fail("not_found", "Scheduling is unavailable for this team.")
+ }
+ if !p.Allows(team, op.op.Scope) {
+ return Fail("forbidden", "Scheduling requires read and write access to each selected app.")
+ }
+ }
+ return nil
+}
+
+// Revalidate every composite scope before each effect, including scopes whose
+// step has already completed. The provider binds the original grant identity.
+func (s *scheduler) authorize(ctx context.Context, p Principal, in scheduleInput) error {
+ if err := s.eligible(p, in.Team, in.Agenda != nil); err != nil {
+ return err
+ }
+ for _, name := range s.required(in.Agenda != nil) {
+ op := s.registry.operations[name].op
+ if _, err := s.credentials.Downstream(ctx, p, s.routes[in.Team][name], in.Team, []string{op.Scope}); err != nil {
+ return err
+ }
+ }
+ return ctx.Err()
+}
+func (s *scheduler) validate(name string, input any) error {
+ op, ok := s.registry.operations[name]
+ if !ok {
+ return Fail("not_found", "Required app operation is unavailable.")
+ }
+ raw, err := json.Marshal(input)
+ if err != nil || len(raw) > MaxPayload {
+ return Fail("too_large", "Scheduling input is too large.")
+ }
+ var value any
+ if DecodeJSON(raw, &value) != nil || op.input.Validate(value) != nil {
+ return Fail("invalid", "Scheduling fields do not match an app contract.")
+ }
+ return nil
+}
+func (s *scheduler) call(ctx context.Context, p Principal, name string, input any) (map[string]any, error) {
+ if err := s.validate(name, input); err != nil {
+ return nil, err
+ }
+ raw, _ := json.Marshal(input)
+ out, err := s.registry.Call(ctx, p, name, raw)
+ if err != nil {
+ return nil, err
+ }
+ value, ok := out.(map[string]any)
+ if !ok {
+ return nil, Fail("unavailable", "The app returned an invalid result.")
+ }
+ return value, nil
+}
+
+// Reject ambiguous folds as well as gaps. Calendar's canonical validator still
+// decides whether this event can be created; schema checks cannot promise that.
+func scheduleTimes(in scheduleInput) (string, string, error) {
+ zone, err := time.LoadLocation(in.TZ)
+ if err != nil || in.TZ == "" || in.TZ == "Local" {
+ return "", "", Fail("invalid", "Supply an explicit IANA time zone.")
+ }
+ parse := func(raw string) (time.Time, string, error) {
+ t, err := time.Parse(time.RFC3339, raw)
+ if err != nil || t.Format(time.RFC3339) != raw || t.Second() != 0 || t.Nanosecond() != 0 {
+ return t, "", Fail("invalid", "Use canonical RFC3339 times at whole-minute precision.")
+ }
+ _, given := t.Zone()
+ _, actual := t.In(zone).Zone()
+ local := t.In(zone).Format("2006-01-02T15:04")
+ if given != actual {
+ return t, "", Fail("invalid", "The time offset does not match the named zone.")
+ }
+ // Offsets spanning nearby transitions cover non-hour and date-line folds.
+ offsets := map[int]bool{}
+ for h := -48; h <= 48; h++ {
+ _, off := t.Add(time.Duration(h) * time.Hour).In(zone).Zone()
+ offsets[off] = true
+ }
+ for off := range offsets {
+ other := t.Add(time.Duration(actual-off) * time.Second)
+ if !other.Equal(t) && other.In(zone).Format("2006-01-02T15:04") == local {
+ return t, "", Fail("invalid", "Ambiguous local times are unsupported.")
+ }
+ }
+ return t, local, nil
+ }
+ start, sl, err := parse(in.Start)
+ if err != nil {
+ return "", "", err
+ }
+ end, el, err := parse(in.End)
+ if err != nil {
+ return "", "", err
+ }
+ if !end.After(start) {
+ return "", "", Fail("invalid", "The event must end after it starts.")
+ }
+ return sl, el, nil
+}
+
+func (s *scheduler) invoke(ctx context.Context, p Principal, raw json.RawMessage) (any, error) {
+ var in scheduleInput
+ if strictjson.Unmarshal(raw, &in) != nil {
+ return nil, Fail("invalid", "Invalid scheduling request.")
+ }
+ uid, err := uuid.Parse(in.ClientID)
+ if err != nil || uid == uuid.Nil || uid.String() != in.ClientID || strings.TrimSpace(in.Title) == "" {
+ return nil, Fail("invalid", "Supply a title and canonical nonzero UUID client_id.")
+ }
+ start, end, err := scheduleTimes(in)
+ if err != nil {
+ return nil, err
+ }
+ if err = s.authorize(ctx, p, in); err != nil {
+ return nil, err
+ }
+ meeting := map[string]any{"team": in.Team, "client_id": scheduleID(in.ClientID, "meeting"), "title": in.Title, "starts_at": in.Start}
+ event := map[string]any{"team": in.Team, "client_id": scheduleID(in.ClientID, "event"), "calendar_id": in.CalendarID, "title": in.Title, "start_local": start, "end_local": end, "tz": in.TZ, "all_day": false, "kind": "meeting", "status": "confirmed", "location": "", "notes": in.Notes}
+ var agenda map[string]any
+ if in.Agenda != nil {
+ agenda = map[string]any{"team": in.Team, "client_id": scheduleID(in.ClientID, "agenda"), "title": in.Agenda.Title, "blocks": in.Agenda.Blocks}
+ if err = s.validate("docs_create", agenda); err != nil {
+ return nil, err
+ }
+ }
+ if err = s.validate("calls_create_meeting", meeting); err != nil {
+ return nil, err
+ }
+ if err = s.validate("calendar_create_event", event); err != nil {
+ return nil, err
+ }
+ fingerprint, _ := json.Marshal(struct {
+ Version int `json:"version"`
+ Input scheduleInput `json:"input"`
+ }{1, in})
+ digest := sha256.Sum256(fingerprint)
+ if _, err = s.call(ctx, p, "calls_reserve_schedule", map[string]any{"team": in.Team, "client_id": in.ClientID, "fingerprint": hex.EncodeToString(digest[:])}); err != nil {
+ return nil, err
+ }
+ out := scheduleResult{Team: in.Team, ClientID: in.ClientID, Status: "complete", Steps: []scheduleStep{}}
+ if agenda != nil {
+ out.Steps = append(out.Steps, scheduleStep{Name: "agenda", State: "pending"})
+ }
+ out.Steps = append(out.Steps, scheduleStep{Name: "meeting", State: "pending"}, scheduleStep{Name: "event", State: "pending"})
+ for i := range out.Steps {
+ step := &out.Steps[i]
+ if err = s.authorize(ctx, p, in); err != nil {
+ return nil, err
+ }
+ name, args := "calls_create_meeting", meeting
+ switch step.Name {
+ case "agenda":
+ name, args = "docs_create", agenda
+ case "event":
+ name, args = "calendar_create_event", event
+ }
+ result, callErr := s.call(ctx, p, name, args)
+ if callErr == nil {
+ step.Resource, callErr = s.reference(in.Team, step.Name, result)
+ }
+ if callErr != nil {
+ f := SafeFailure(callErr)
+ if f.Code == "unauthenticated" || f.Code == "forbidden" {
+ return nil, f
+ }
+ step.State = "unconfirmed"
+ out.Status = "partial"
+ out.Failure = &scheduleFailure{step.Name, f.Code}
+ break
+ }
+ step.State = "confirmed"
+ if step.Name != "event" {
+ event["notes"] = event["notes"].(string) + "\n\n" + step.Name + ": " + step.Resource.URL
+ }
+ }
+ if err = s.revalidate(ctx, p, in, out); err != nil {
+ return nil, err
+ }
+ encoded, _ := json.Marshal(out)
+ if len(encoded) > 65535 {
+ return nil, Fail("too_large", "Scheduling result is too large.")
+ }
+ return out, nil
+}
+
+func (s *scheduler) reference(team, step string, value map[string]any) (*ResourceReference, error) {
+ if step != "agenda" && step != "meeting" && step != "event" {
+ return nil, Fail("unavailable", "The app returned an invalid resource reference.")
+ }
+ app, operation, idField, path := "calls", "calls_create_meeting", "sqid", "/m/"
+ if step == "agenda" {
+ app, operation, idField, path = "docs", "docs_create", "id", "/d/"
+ }
+ if step == "event" {
+ app, operation, idField, path = "calendar", "calendar_create_event", "id", "/events/"
+ }
+ id, ok := value[idField].(string)
+ if app == "calendar" {
+ if n, yes := value[idField].(json.Number); yes {
+ v, e := strconv.ParseInt(n.String(), 10, 64)
+ if e == nil && v > 0 {
+ id, ok = n.String(), true
+ }
+ }
+ }
+ if !ok || id == "" || strings.ContainsAny(id, "/?#%\\") {
+ return nil, Fail("unavailable", "The app returned an invalid resource reference.")
+ }
+ if app != "calendar" && (len(id) != 10 || strings.Trim(id, "23456789abcdefghjkmnpqrstuvwxyz") != "") {
+ return nil, Fail("unavailable", "The app returned an invalid resource reference.")
+ }
+ get := strings.Replace(operation, "create", "get", 1)
+ if err := s.validate(get, map[string]any{"team": team, idField: value[idField]}); err != nil {
+ return nil, Fail("unavailable", "The app returned an unreadable resource reference.")
+ }
+ want := strings.TrimSuffix(s.routes[team][operation], "/api/v1") + path + id
+ if value["url"] != want {
+ return nil, Fail("unavailable", "The app returned a foreign resource reference.")
+ }
+ return &ResourceReference{team, app, id, want}, nil
+}
+
+func (s *scheduler) revalidate(ctx context.Context, p Principal, in scheduleInput, out scheduleResult) error {
+ if err := s.authorize(ctx, p, in); err != nil {
+ return err
+ }
+ for _, step := range out.Steps {
+ if step.State != "confirmed" {
+ continue
+ }
+ ref := step.Resource
+ if ref == nil || ref.Team != in.Team {
+ return Fail("unavailable", "Workflow provenance is unavailable.")
+ }
+ name, key := "calls_get_meeting", "sqid"
+ var id any = ref.ID
+ switch ref.App {
+ case "docs":
+ name, key = "docs_get", "id"
+ case "calendar":
+ name, key = "calendar_get_event", "id"
+ n, e := strconv.ParseInt(ref.ID, 10, 64)
+ if e != nil {
+ return Fail("unavailable", "Workflow provenance is unavailable.")
+ }
+ id = json.Number(strconv.FormatInt(n, 10))
+ case "calls":
+ default:
+ return Fail("unavailable", "Workflow provenance is unavailable.")
+ }
+ checked, err := s.reference(in.Team, step.Name, map[string]any{key: id, "url": ref.URL})
+ if err != nil || *checked != *ref {
+ return Fail("unavailable", "Workflow provenance changed.")
+ }
+ current, err := s.call(ctx, p, name, map[string]any{"team": in.Team, key: id})
+ if err != nil {
+ return err
+ }
+ if ref.App == "calendar" {
+ if current[key] != json.Number(ref.ID) {
+ return Fail("unavailable", "Workflow provenance changed.")
+ }
+ } else if current[key] != ref.ID {
+ return Fail("unavailable", "Workflow provenance changed.")
+ }
+ }
+ return s.authorize(ctx, p, in)
+}
diff --git a/schedule_contract.go b/schedule_contract.go
new file mode 100644
index 0000000..1d46145
--- /dev/null
+++ b/schedule_contract.go
@@ -0,0 +1,66 @@
+package agentaccess
+
+import "encoding/json"
+
+// ResourceReference is a locator, never an authorization or invitation token.
+type ResourceReference struct {
+ Team string `json:"team"`
+ App string `json:"app"`
+ ID string `json:"id"`
+ URL string `json:"url"`
+}
+
+type scheduleBlock struct {
+ Type string `json:"type"`
+ Text string `json:"text"`
+ Level int `json:"level,omitempty"`
+}
+type scheduleAgenda struct {
+ Title string `json:"title"`
+ Blocks []scheduleBlock `json:"blocks"`
+}
+type scheduleInput struct {
+ Team string `json:"team"`
+ ClientID string `json:"client_id"`
+ Title string `json:"title"`
+ CalendarID int64 `json:"calendar_id"`
+ Start string `json:"start"`
+ End string `json:"end"`
+ TZ string `json:"tz"`
+ Notes string `json:"notes"`
+ Agenda *scheduleAgenda `json:"agenda,omitempty"`
+}
+type scheduleStep struct {
+ Name string `json:"name"`
+ State string `json:"state"`
+ Resource *ResourceReference `json:"resource,omitempty"`
+}
+type scheduleFailure struct {
+ Step string `json:"step"`
+ Code string `json:"code"`
+}
+type scheduleResult struct {
+ Team string `json:"team"`
+ ClientID string `json:"client_id"`
+ Status string `json:"status"`
+ Steps []scheduleStep `json:"steps"`
+ InvitationsSent bool `json:"invitations_sent"`
+ Failure *scheduleFailure `json:"failure,omitempty"`
+}
+
+func schemaObject(properties map[string]any, required ...string) map[string]any {
+ return map[string]any{"type": "object", "properties": properties, "required": required, "additionalProperties": false}
+}
+func schemaString(max int) map[string]any { return map[string]any{"type": "string", "maxLength": max} }
+func schemaJSON(v any) json.RawMessage { b, _ := json.Marshal(v); return b }
+
+func (s *scheduler) operation() Operation {
+ block := schemaObject(map[string]any{"type": map[string]any{"enum": []string{"paragraph", "heading"}}, "text": schemaString(131072), "level": map[string]any{"type": "integer", "minimum": 0, "maximum": 6}}, "type", "text")
+ agenda := schemaObject(map[string]any{"title": schemaString(512), "blocks": map[string]any{"type": "array", "maxItems": 200, "items": block}}, "title", "blocks")
+ ref := schemaObject(map[string]any{"team": schemaString(128), "app": schemaString(32), "id": schemaString(128), "url": schemaString(2048)}, "team", "app", "id", "url")
+ step := schemaObject(map[string]any{"name": map[string]any{"enum": []string{"agenda", "meeting", "event"}}, "state": map[string]any{"enum": []string{"pending", "confirmed", "unconfirmed"}}, "resource": ref}, "name", "state")
+ failure := schemaObject(map[string]any{"step": schemaString(32), "code": schemaString(32)}, "step", "code")
+ return Operation{Name: "calls_schedule", Description: "Create an optional agenda, a meeting and a Calendar event. Requires read/write scopes for each selected app. Resume after interruption with the same client_id and exact original request: durable app receipts prevent duplicates. Partial does not mean the failed step did not commit. Sends no invitations; links grant no access.", Scope: "calls:write", Idempotent: true,
+ Input: schemaJSON(schemaObject(map[string]any{"team": schemaString(64), "client_id": schemaString(36), "title": schemaString(200), "calendar_id": map[string]any{"type": "integer", "minimum": 1, "maximum": int64(9223372036854775807)}, "start": schemaString(35), "end": schemaString(35), "tz": schemaString(128), "notes": schemaString(3000), "agenda": agenda}, "team", "client_id", "title", "calendar_id", "start", "end", "tz", "notes")),
+ Output: schemaJSON(schemaObject(map[string]any{"team": schemaString(64), "client_id": schemaString(36), "status": map[string]any{"enum": []string{"complete", "partial"}}, "steps": map[string]any{"type": "array", "minItems": 2, "maxItems": 3, "items": step}, "invitations_sent": map[string]any{"const": false}, "failure": failure}, "team", "client_id", "status", "steps", "invitations_sent")), Available: s.available, Invoke: s.invoke}
+}
diff --git a/schedule_guard.go b/schedule_guard.go
new file mode 100644
index 0000000..849df71
--- /dev/null
+++ b/schedule_guard.go
@@ -0,0 +1,24 @@
+package agentaccess
+
+import (
+ "context"
+ "encoding/json"
+)
+
+// ScheduleResponseGuard performs only current reads and credential checks.
+// Other operations keep their own app-owned emission authorization.
+func (r *Registry) ScheduleResponseGuard(ctx context.Context, p Principal, name string, raw json.RawMessage, result any) error {
+ if name != "calls_schedule" {
+ return nil
+ }
+ if r.schedule == nil {
+ return Fail("unavailable", "Scheduling is unavailable.")
+ }
+ var in scheduleInput
+ var out scheduleResult
+ body, err := json.Marshal(result)
+ if err != nil || len(body) > 65535 || json.Unmarshal(raw, &in) != nil || json.Unmarshal(body, &out) != nil || out.Team != in.Team || out.ClientID != in.ClientID {
+ return Fail("unavailable", "Workflow provenance is unavailable.")
+ }
+ return r.schedule.revalidate(ctx, p, in, out)
+}
diff --git a/schedule_interop_test.go b/schedule_interop_test.go
new file mode 100644
index 0000000..904db61
--- /dev/null
+++ b/schedule_interop_test.go
@@ -0,0 +1,192 @@
+package agentaccess_test
+
+import (
+ access "amadan.net/oficina/agent-access.git"
+ "amadan.net/oficina/agent-access.git/client"
+ "context"
+ "crypto/tls"
+ "encoding/json"
+ "errors"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+ "golang.org/x/oauth2"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+type interopCredentials struct{ revoked bool }
+
+func (c *interopCredentials) Downstream(context.Context, access.Principal, string, string, []string) (string, error) {
+ if c.revoked {
+ return "", access.Fail("unauthenticated", "Revoked")
+ }
+ return "fixture", nil
+}
+
+type interopStore struct{ c client.Credentials }
+
+func (s *interopStore) Load() (client.Credentials, error) { return s.c, nil }
+func (s *interopStore) Save(c client.Credentials) error { s.c = c; return nil }
+func (s *interopStore) Delete() error { return nil }
+
+type interopTransport struct {
+ base http.RoundTripper
+ dest map[string]string
+ mu sync.Mutex
+ drop string
+}
+
+func (t *interopTransport) RoundTrip(r *http.Request) (*http.Response, error) {
+ copy := r.Clone(r.Context())
+ target, ok := t.dest[r.URL.Scheme+"://"+r.URL.Host]
+ if !ok {
+ return nil, errors.New("unregistered fixture destination")
+ }
+ u, _ := url.Parse(target)
+ copy.URL.Scheme = u.Scheme
+ copy.URL.Host = u.Host
+ copy.Header.Set("Authorization", "Bearer fixture")
+ resp, err := t.base.RoundTrip(copy)
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if err == nil && t.drop != "" && strings.HasSuffix(r.URL.Path, "/"+t.drop) {
+ t.drop = ""
+ resp.Body.Close()
+ return nil, errors.New("lost committed response")
+ }
+ return resp, err
+}
+func TestSuiteSchedulingInterop(t *testing.T) {
+ dir := os.Getenv("OFICINA_INTEROP_DIR")
+ if dir == "" {
+ t.Skip("run scripts/suite-interop.py with the three app worktrees")
+ }
+ p := access.Principal{Subject: "opaque-home-alice", Client: "oficina-interop", Grant: "interop-grant", Teams: []string{"acme"}, Scopes: []string{"docs:read", "docs:write", "calls:read", "calls:write", "calendar:read", "calendar:write"}}
+ transport := &interopTransport{base: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}, dest: map[string]string{}} // Private ephemeral test TLS only.
+ defer transport.base.(*http.Transport).CloseIdleConnections()
+ var routes []access.Route
+ var calendarID int64
+ for _, app := range []string{"docs", "calls", "calendar"} {
+ var fixture struct {
+ URL, Origin string
+ CalendarID int64 `json:"calendar_id"`
+ }
+ b, err := os.ReadFile(filepath.Join(dir, app+".json"))
+ if err != nil || json.Unmarshal(b, &fixture) != nil || fixture.Origin == "" {
+ t.Fatalf("%s fixture metadata: %v %s", app, err, b)
+ }
+ transport.dest[fixture.Origin] = fixture.URL
+ req, _ := http.NewRequestWithContext(t.Context(), "GET", fixture.Origin+"/api/v1/operations", nil)
+ resp, err := (&http.Client{Transport: transport}).Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var contracts struct{ Operations []access.Operation }
+ err = json.NewDecoder(resp.Body).Decode(&contracts)
+ resp.Body.Close()
+ if err != nil || resp.StatusCode != 200 || len(contracts.Operations) == 0 {
+ t.Fatal(app, resp.StatusCode, err)
+ }
+ routes = append(routes, access.Route{Team: "acme", Resource: fixture.Origin + "/api/v1", Operations: contracts.Operations})
+ if app == "calendar" {
+ calendarID = fixture.CalendarID
+ }
+ }
+ credentials := &interopCredentials{}
+ gateway, err := access.Gateway(routes, credentials, transport)
+ if err != nil {
+ t.Fatal(err)
+ }
+ verify := access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return p, nil })
+ server := httptest.NewTLSServer(gateway.HTTPGuarded(verify, verify, gateway.ScheduleResponseGuard))
+ defer server.Close()
+ cli := client.New(&interopStore{client.Credentials{Server: server.URL, Resource: server.URL + "/mcp", TokenEndpoint: server.URL + "/token", Token: &oauth2.Token{AccessToken: "fixture", Expiry: time.Now().Add(time.Hour)}}})
+ cli.HTTP = server.Client()
+ args := map[string]any{"team": "acme", "client_id": "3395dd82-455b-46ae-a758-a7fb1484f3e6", "title": "Interop review", "calendar_id": calendarID, "start": "2026-11-02T10:00:00Z", "end": "2026-11-02T11:00:00Z", "tz": "Europe/Dublin", "notes": "Review shipped changes", "agenda": map[string]any{"title": "Review agenda", "blocks": []any{map[string]any{"type": "paragraph", "text": "Check the shared workflow"}}}}
+ raw, _ := json.Marshal(args)
+ transport.drop = "calendar_create_event"
+ first, err := cli.Call(t.Context(), "calls_schedule", raw)
+ if err != nil || first.(map[string]any)["status"] != "partial" {
+ t.Fatal("lost-response partial", first, err)
+ }
+ // A fresh gateway, fresh MCP server and unchanged app stores model restarting
+ // the stateless connection process. Every app must replay its durable receipt.
+ restarted, err := access.Gateway(routes, credentials, transport)
+ if err != nil {
+ t.Fatal(err)
+ }
+ mcpServer := httptest.NewTLSServer(restarted.MCP(verify))
+ defer mcpServer.Close()
+ mcpTransport := &interopTransport{base: mcpServer.Client().Transport, dest: map[string]string{mcpServer.URL: mcpServer.URL}}
+ session, err := mcp.NewClient(&mcp.Implementation{Name: "suite-interop", Version: "1"}, nil).Connect(t.Context(), &mcp.StreamableClientTransport{Endpoint: mcpServer.URL, HTTPClient: &http.Client{Transport: mcpTransport}}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer session.Close()
+ result, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "calls_schedule", Arguments: args})
+ if err != nil || result.IsError {
+ t.Fatal("MCP resume", result, err)
+ }
+ var out struct {
+ Status string
+ Steps []struct {
+ Name string
+ Resource access.ResourceReference
+ }
+ InvitationsSent bool `json:"invitations_sent"`
+ }
+ b, _ := json.Marshal(result.StructuredContent)
+ if json.Unmarshal(b, &out) != nil || out.Status != "complete" || len(out.Steps) != 3 || out.InvitationsSent {
+ t.Fatal(string(b))
+ }
+ refs := map[string]access.ResourceReference{}
+ for _, s := range out.Steps {
+ refs[s.Name] = s.Resource
+ }
+ get := func(name string, in map[string]any) map[string]any {
+ t.Helper()
+ raw, _ := json.Marshal(in)
+ value, err := restarted.Call(t.Context(), p, name, raw)
+ if err != nil {
+ t.Fatal(name, err)
+ }
+ return value.(map[string]any)
+ }
+ doc := get("docs_get", map[string]any{"team": "acme", "id": refs["agenda"].ID})
+ text, _ := json.Marshal(doc)
+ if !strings.Contains(string(text), "Check the shared workflow") {
+ t.Fatal("agenda content missing", string(text))
+ }
+ eventID := json.Number(refs["event"].ID)
+ event := get("calendar_get_event", map[string]any{"team": "acme", "id": eventID})
+ text, _ = json.Marshal(event)
+ for _, name := range []string{"agenda", "meeting"} {
+ if !strings.Contains(string(text), refs[name].URL) {
+ t.Fatal("cross-app reference missing", name, string(text))
+ }
+ }
+ again, err := cli.Call(t.Context(), "calls_schedule", raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ a, _ := json.Marshal(again)
+ if string(a) != string(b) {
+ t.Fatal("transport replay changed result", string(a), string(b))
+ }
+ args["notes"] = "different request"
+ changed, _ := json.Marshal(args)
+ if _, err = cli.Call(t.Context(), "calls_schedule", changed); access.SafeFailure(err).Code != "conflict" {
+ t.Fatal("changed retry accepted", err)
+ }
+ credentials.revoked = true
+ if _, err = restarted.Call(t.Context(), p, "calls_schedule", raw); access.SafeFailure(err).Code != "unauthenticated" {
+ t.Fatal("revoked workflow accepted", err)
+ }
+ t.Log("Real Docs/Calls/Calendar stores: HTTPS CLI partial, lost committed Calendar response, fresh-gateway MCP resume, readable linked resources, exact replay, changed request conflict, revocation all passed")
+}
diff --git a/schedule_test.go b/schedule_test.go
new file mode 100644
index 0000000..27b3d54
--- /dev/null
+++ b/schedule_test.go
@@ -0,0 +1,350 @@
+package agentaccess
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "github.com/google/uuid"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+)
+
+type scheduleCredentials struct {
+ mu sync.Mutex
+ revoked bool
+ denied string
+}
+
+func (c *scheduleCredentials) Downstream(_ context.Context, p Principal, resource, team string, scopes []string) (string, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.revoked {
+ return "", Fail("unauthenticated", "Revoked")
+ }
+ for _, s := range scopes {
+ if s == c.denied {
+ return "", Fail("forbidden", "Scope removed")
+ }
+ }
+ return "test", nil
+}
+
+type scheduleHarness struct {
+ server *httptest.Server
+ credentials *scheduleCredentials
+ routes []Route
+ p Principal
+ mu sync.Mutex
+ receipts map[string]string
+ objects map[string]map[string]any
+ effects map[string]int
+ drop, fail, foreign, revokeAfter string
+ denyAfter string
+ reads int
+}
+
+func schedulePrincipal() Principal {
+ return Principal{Subject: "person", Client: "client", Grant: "grant", Teams: []string{"acme"}, Scopes: []string{"calls:read", "calls:write", "calendar:read", "calendar:write", "docs:read", "docs:write"}}
+}
+func newScheduleHarness(t *testing.T) *scheduleHarness {
+ t.Helper()
+ h := &scheduleHarness{credentials: &scheduleCredentials{}, p: schedulePrincipal(), receipts: map[string]string{}, objects: map[string]map[string]any{}, effects: map[string]int{}}
+ h.server = httptest.NewTLSServer(http.HandlerFunc(h.serve))
+ t.Cleanup(h.server.Close)
+ for _, name := range []string{"calls_reserve_schedule", "calls_create_meeting", "calls_get_meeting", "calendar_create_event", "calendar_get_event", "docs_create", "docs_get"} {
+ scope := strings.Split(name, "_")[0] + ":write"
+ if strings.Contains(name, "get") {
+ scope = strings.Split(name, "_")[0] + ":read"
+ }
+ op := Operation{Name: name, Description: name, Scope: scope, Input: json.RawMessage(`{"type":"object"}`), Output: json.RawMessage(`{"type":"object"}`)}
+ h.routes = append(h.routes, Route{Team: "acme", Resource: h.server.URL + "/api/v1", Operations: []Operation{op}})
+ }
+ return h
+}
+func (h *scheduleHarness) serve(w http.ResponseWriter, r *http.Request) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ name := strings.TrimPrefix(r.URL.Path, "/api/v1/operations/")
+ var in map[string]any
+ raw, _ := io.ReadAll(r.Body)
+ if DecodeJSON(raw, &in) != nil {
+ w.WriteHeader(422)
+ return
+ }
+ if name == h.fail {
+ w.WriteHeader(503)
+ return
+ }
+ if strings.Contains(name, "get") {
+ h.reads++
+ id := in["id"]
+ if name == "calls_get_meeting" {
+ id = in["sqid"]
+ }
+ for _, v := range h.objects {
+ if v["id"] == id || v["sqid"] == id {
+ writeJSON(w, 200, v)
+ return
+ }
+ }
+ w.WriteHeader(404)
+ return
+ }
+ key := name + "/" + in["client_id"].(string)
+ canonical, _ := json.Marshal(in)
+ if old, ok := h.receipts[key]; ok && old != string(canonical) {
+ w.WriteHeader(409)
+ return
+ }
+ if name == "calls_reserve_schedule" {
+ h.receipts[key] = string(canonical)
+ writeJSON(w, 200, map[string]any{"reserved": true})
+ return
+ }
+ out := h.objects[key]
+ if out == nil {
+ h.effects[name]++
+ path, id := "/m/", "abcdef2345"
+ field := "sqid"
+ var value any = id
+ if name == "docs_create" {
+ path, id, field = "/d/", "ghjkmnpqrs", "id"
+ value = id
+ }
+ if name == "calendar_create_event" {
+ path, id, field = "/events/", "1", "id"
+ value = json.Number("1")
+ }
+ out = map[string]any{field: value, "url": h.server.URL + path + id}
+ h.objects[key] = out
+ h.receipts[key] = string(canonical)
+ }
+ if name == h.foreign {
+ out = map[string]any{"id": "ghjkmnpqrs", "url": "https://foreign.test/d/ghjkmnpqrs"}
+ }
+ if name == h.revokeAfter {
+ h.credentials.mu.Lock()
+ h.credentials.revoked = true
+ h.credentials.mu.Unlock()
+ }
+ if name == h.denyAfter {
+ h.credentials.mu.Lock()
+ h.credentials.denied = "docs:read"
+ h.credentials.mu.Unlock()
+ }
+ writeJSON(w, 200, out)
+}
+
+type scheduleDropTransport struct{ h *scheduleHarness }
+
+func (d scheduleDropTransport) RoundTrip(r *http.Request) (*http.Response, error) {
+ resp, err := d.h.server.Client().Transport.RoundTrip(r)
+ d.h.mu.Lock()
+ defer d.h.mu.Unlock()
+ if err == nil && strings.HasSuffix(r.URL.Path, "/"+d.h.drop) && d.h.drop != "" {
+ d.h.drop = ""
+ resp.Body.Close()
+ return nil, errors.New("response lost after commit")
+ }
+ return resp, err
+}
+func (h *scheduleHarness) gateway(t *testing.T) *Registry {
+ t.Helper()
+ r, err := Gateway(h.routes, h.credentials, scheduleDropTransport{h})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return r
+}
+func scheduleArgs() map[string]any {
+ return map[string]any{"team": "acme", "client_id": "3395dd82-455b-46ae-a758-a7fb1484f3e6", "title": "Review", "calendar_id": 1, "start": "2026-11-02T10:00:00Z", "end": "2026-11-02T11:00:00Z", "tz": "Europe/Dublin", "notes": "Bring notes", "agenda": map[string]any{"title": "Agenda", "blocks": []any{map[string]any{"type": "paragraph", "text": "Review changes"}}}}
+}
+func scheduleCall(t *testing.T, r *Registry, p Principal, in map[string]any) (scheduleResult, error) {
+ t.Helper()
+ b, _ := json.Marshal(in)
+ out, err := r.Call(t.Context(), p, "calls_schedule", b)
+ var result scheduleResult
+ if err == nil {
+ b, _ = json.Marshal(out)
+ if err = json.Unmarshal(b, &result); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return result, err
+}
+func TestScheduleResumeLostResponsesAndGatewayRestart(t *testing.T) {
+ for _, drop := range []string{"docs_create", "calls_create_meeting", "calendar_create_event"} {
+ t.Run(drop, func(t *testing.T) {
+ h := newScheduleHarness(t)
+ h.drop = drop
+ first, err := scheduleCall(t, h.gateway(t), h.p, scheduleArgs())
+ if err != nil || first.Status != "partial" || first.Failure.Code != "unavailable" {
+ t.Fatal(first, err)
+ }
+ second, err := scheduleCall(t, h.gateway(t), h.p, scheduleArgs())
+ if err != nil || second.Status != "complete" || second.InvitationsSent {
+ t.Fatal(second, err)
+ }
+ for _, name := range []string{"docs_create", "calls_create_meeting", "calendar_create_event"} {
+ if h.effects[name] != 1 {
+ t.Fatal("duplicate effect", name, h.effects)
+ }
+ }
+ before := h.reads
+ r := h.gateway(t)
+ raw, _ := json.Marshal(scheduleArgs())
+ if err = r.ScheduleResponseGuard(t.Context(), h.p, "calls_schedule", raw, second); err != nil || h.reads != before+3 {
+ t.Fatal("guard not pure reads", err, h.reads)
+ }
+ changed := scheduleArgs()
+ changed["notes"] = "changed"
+ if _, err = scheduleCall(t, r, h.p, changed); SafeFailure(err).Code != "conflict" {
+ t.Fatal("changed workflow accepted", err)
+ }
+ })
+ }
+}
+func TestScheduleAuthorityAndProvenance(t *testing.T) {
+ for _, mode := range []string{"missing-scope", "scope-revoked", "revoked-after-agenda", "foreign-url", "missing-after-completion"} {
+ t.Run(mode, func(t *testing.T) {
+ h := newScheduleHarness(t)
+ switch mode {
+ case "missing-scope":
+ h.p.Scopes = []string{"calls:write", "calendar:write"}
+ case "scope-revoked":
+ h.credentials.denied = "calendar:read"
+ case "revoked-after-agenda":
+ h.revokeAfter = "docs_create"
+ case "foreign-url":
+ h.foreign = "docs_create"
+ }
+ r := h.gateway(t)
+ out, err := scheduleCall(t, r, h.p, scheduleArgs())
+ if mode == "foreign-url" {
+ if err != nil || out.Status != "partial" || out.Steps[0].Resource != nil || h.effects["calls_create_meeting"] != 0 {
+ t.Fatal(out, err)
+ }
+ return
+ }
+ if mode == "missing-after-completion" {
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.objects = map[string]map[string]any{}
+ raw, _ := json.Marshal(scheduleArgs())
+ if err = r.ScheduleResponseGuard(t.Context(), h.p, "calls_schedule", raw, out); SafeFailure(err).Code != "not_found" {
+ t.Fatal("deleted resource emitted", err)
+ }
+ return
+ }
+ if err == nil {
+ t.Fatal("unauthorized workflow returned", out)
+ }
+ if h.effects["calls_create_meeting"] != 0 {
+ t.Fatal("effect after authority failure")
+ }
+ })
+ }
+}
+func TestScheduleTimesAndIdentifiers(t *testing.T) {
+ for _, v := range []struct {
+ start, end, tz string
+ valid bool
+ }{{"2026-11-02T10:00:00Z", "2026-11-02T11:00:00Z", "Europe/Dublin", true}, {"2026-10-25T01:30:00+01:00", "2026-10-25T02:30:00Z", "Europe/Dublin", false}, {"2026-03-29T01:30:00Z", "2026-03-29T02:30:00+01:00", "Europe/Dublin", false}, {"2026-11-02T10:00:01Z", "2026-11-02T11:00:00Z", "UTC", false}, {"2026-11-02T11:00:00Z", "2026-11-02T10:00:00Z", "UTC", false}} {
+ _, _, err := scheduleTimes(scheduleInput{Start: v.start, End: v.end, TZ: v.tz})
+ if (err == nil) != v.valid {
+ t.Fatal(v, err)
+ }
+ }
+ a, b := scheduleID("root", "agenda"), scheduleID("root", "meeting")
+ if a == b || a != scheduleID("root", "agenda") || uuid.MustParse(a).Version() != 5 {
+ t.Fatal(a, b)
+ }
+}
+
+func TestScheduleMalformedUnicodeNoEffects(t *testing.T) {
+ for _, bad := range []string{`\ud800`, string([]byte{255})} {
+ h := newScheduleHarness(t)
+ args := scheduleArgs()
+ args["title"] = "REPLACE"
+ raw, _ := json.Marshal(args)
+ raw = []byte(strings.Replace(string(raw), "REPLACE", bad, 1))
+ if _, err := h.gateway(t).Call(t.Context(), h.p, "calls_schedule", raw); SafeFailure(err).Code != "invalid" {
+ t.Fatal(err)
+ }
+ if len(h.receipts) != 0 {
+ t.Fatal("invalid Unicode reserved workflow")
+ }
+ }
+}
+func TestScheduleMCPFinalResponseGuard(t *testing.T) {
+ h := newScheduleHarness(t)
+ r := h.gateway(t)
+ entry := r.operations["calls_schedule"]
+ invoke := entry.op.Invoke
+ entry.op.Invoke = func(ctx context.Context, p Principal, raw json.RawMessage) (any, error) {
+ out, err := invoke(ctx, p, raw)
+ h.credentials.mu.Lock()
+ h.credentials.revoked = true
+ h.credentials.mu.Unlock()
+ return out, err
+ }
+ r.operations["calls_schedule"] = entry
+ server := httptest.NewServer(r.MCP(VerifyFunc(func(context.Context, string) (Principal, error) { return h.p, nil })))
+ defer server.Close()
+ client := mcp.NewClient(&mcp.Implementation{Name: "test", Version: "1"}, nil)
+ session, err := client.Connect(t.Context(), &mcp.StreamableClientTransport{Endpoint: server.URL, HTTPClient: &http.Client{Transport: headerTransport{base: http.DefaultTransport}}}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer session.Close()
+ out, err := session.CallTool(t.Context(), &mcp.CallToolParams{Name: "calls_schedule", Arguments: scheduleArgs()})
+ if err != nil || !out.IsError || out.StructuredContent != nil {
+ t.Fatal("MCP emitted revoked result", out, err)
+ }
+}
+
+func TestScheduleFinalAndCompositeAuthority(t *testing.T) {
+ for _, mode := range []string{"final-revoke", "completed-scope-revoked", "missing-confirmed"} {
+ t.Run(mode, func(t *testing.T) {
+ h := newScheduleHarness(t)
+ switch mode {
+ case "final-revoke":
+ h.revokeAfter = "calendar_create_event"
+ case "completed-scope-revoked":
+ h.denyAfter = "docs_create"
+ case "missing-confirmed":
+ h.fail = "docs_get"
+ }
+ if _, err := scheduleCall(t, h.gateway(t), h.p, scheduleArgs()); err == nil {
+ t.Fatal("unverified result returned")
+ }
+ if mode == "completed-scope-revoked" && h.effects["calls_create_meeting"] != 0 {
+ t.Fatal("later write after completed app scope removed")
+ }
+ })
+ }
+}
+func TestScheduleReferencesCannotEscapeMemberRoutes(t *testing.T) {
+ h := newScheduleHarness(t)
+ r := h.gateway(t)
+ for _, id := range []string{"..", ".", "x%2fy", "/evil", "abcdef2345?", ""} {
+ if _, err := r.schedule.reference("acme", "agenda", map[string]any{"id": id, "url": h.server.URL + "/d/" + id}); err == nil {
+ t.Fatal("invalid member id", id)
+ }
+ }
+ out, err := scheduleCall(t, r, h.p, scheduleArgs())
+ if err != nil {
+ t.Fatal(err)
+ }
+ out.Steps[0].Resource.URL = "https://foreign.test/d/ghjkmnpqrs"
+ raw, _ := json.Marshal(scheduleArgs())
+ if err = r.ScheduleResponseGuard(t.Context(), h.p, "calls_schedule", raw, out); err == nil {
+ t.Fatal("guard accepted substituted URL")
+ }
+}
diff --git a/scripts/suite-interop.py b/scripts/suite-interop.py
new file mode 100644
index 0000000..fb685f5
--- /dev/null
+++ b/scripts/suite-interop.py
@@ -0,0 +1,50 @@
+#!/usr/bin/env python3
+"""Run opt-in, private-store HTTPS acceptance across sibling app worktrees."""
+import argparse
+import json
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+import time
+
+parser = argparse.ArgumentParser(description=__doc__)
+parser.add_argument('--workspace', type=Path, default=Path(__file__).resolve().parents[2])
+args = parser.parse_args()
+runtime = Path(__file__).resolve().parents[1]
+env = dict(os.environ, GOTOOLCHAIN='go1.26.5', CGO_ENABLED='0')
+with tempfile.TemporaryDirectory(prefix='oficina-suite-interop-') as temporary:
+ directory = Path(temporary)
+ binaries = {}
+ for app in ('docs', 'calls', 'calendar'):
+ binary = directory / (app + '.test')
+ subprocess.run(['go', 'test', '-c', '-o', str(binary), './internal/' + app], cwd=args.workspace / (app + '-agent-access'), env=env, check=True)
+ binaries[app] = binary
+ env['OFICINA_INTEROP_DIR'] = str(directory)
+ processes = []
+ logs = []
+ try:
+ for app, binary in binaries.items():
+ log = (directory / (app + '.log')).open('w+')
+ logs.append((app, log))
+ processes.append(subprocess.Popen([str(binary), '-test.run=^TestSuiteInteropFixture$', '-test.v'], cwd=args.workspace / (app + '-agent-access'), env=env, stdout=log, stderr=subprocess.STDOUT))
+ deadline = time.monotonic() + 30
+ while not all((directory / (app + '.json')).exists() for app in binaries):
+ if time.monotonic() >= deadline or any(p.poll() is not None for p in processes):
+ raise RuntimeError('An app fixture did not start')
+ time.sleep(.1)
+ subprocess.run(['go', 'test', '.', '-run', '^TestSuiteSchedulingInterop$', '-count=1', '-v'], cwd=runtime, env=env, check=True)
+ finally:
+ (directory / 'stop').touch()
+ for process in processes:
+ try:
+ process.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ process.terminate()
+ process.wait(timeout=10)
+ for app, log in logs:
+ log.seek(0)
+ print(f'{app}:\n{log.read()}')
+ log.close()
+ if any(p.returncode for p in processes):
+ raise RuntimeError('An app fixture failed')