From 2ee80d06e0d552ad64d4c9c337bb6fc9bcaeeffa Mon Sep 17 00:00:00 2001 From: zhoushoujian Date: Fri, 27 Nov 2026 18:04:57 +0800 Subject: [PATCH] feat(execution): add managed context handoff Co-authored-by: multica-agent --- docs/context-execution.md | 123 +++++ docs/execution-pkg.md | 3 + internal/worker/codex_app_server.go | 47 +- internal/worker/environment.go | 13 +- internal/worker/worker.go | 49 +- pkg/execution/context_contract.go | 357 +++++++++++++++ pkg/execution/context_run.go | 575 +++++++++++++++++++++++ pkg/execution/context_run_test.go | 684 ++++++++++++++++++++++++++++ pkg/execution/context_skills.go | 135 ++++++ pkg/execution/context_store.go | 249 ++++++++++ pkg/execution/execution.go | 44 +- 11 files changed, 2254 insertions(+), 25 deletions(-) create mode 100644 docs/context-execution.md create mode 100644 pkg/execution/context_contract.go create mode 100644 pkg/execution/context_run.go create mode 100644 pkg/execution/context_run_test.go create mode 100644 pkg/execution/context_skills.go create mode 100644 pkg/execution/context_store.go diff --git a/docs/context-execution.md b/docs/context-execution.md new file mode 100644 index 0000000..4743559 --- /dev/null +++ b/docs/context-execution.md @@ -0,0 +1,123 @@ +# AGH context execution + +Use [the execution SDK](execution-pkg.md) and set `Request.Context` to +`ContextExecution` to dispatch an AGH context envelope. Existing callers can +keep using their current `Client.Run` requests. The managed path owns the local +execution journal. AGH owns authorization, knowledge assembly, checkpoint +acceptance, credential policy and the broker. + +## Dispatch and receipt + +1. Open a private, canonical local journal directory (mode `0700`) with + `OpenContextStore`. Use the same directory for all processes handling the + task. Keep the journal's dispatch keys for the whole supported retry window. +2. Resolve the authorized project, resource roots, native executable and Skill + sources to absolute paths. Populate the envelope with the current AGH scope, + versions and capability requirements. Hash task and instruction bytes with + `ContextContentDigest`. Preset descriptors use the uppercase preset name, + source ID, classification, original byte count and digest. Pass the actual + bytes in the SDK request. Ordinary MCP server descriptors pin the digest of + their resolved `MCPServer` configuration. +3. Seal with `envelope.Digest()` and place the result in `EnvelopeDigest`. + Seal each binding with `binding.Digest()` before sealing the envelope. The + version is `1.0`. Top-level optional extensions survive JSON forwarding + within major version 1. Digests use compact Go JSON with ordered object + keys and preserved number tokens. Credential values travel outside the + envelope. +4. Supply an `Authorize` callback that checks current grants. Offload invokes + it before claiming the dispatch and again immediately before opening the + native process. When authorizing a handoff, check each checkpoint reference + against the receiving Agent, scope, audience and current policy. Use the + run's context to cancel a dispatched turn if AGH revokes its access. +5. Read `Result.ContextReceipt` on success and error. The injection evidence is + produced after native launch for Claude and after an acknowledged Codex + turn start. It includes the actual cwd, configured roots, pinned Skill + snapshots, tool versions, compiled instruction digest and byte count, and + per-document digests and byte counts. Resource-root digests are authorized + metadata for caller-managed directories. AGH validates any corresponding + snapshot or revision. The receipt contains no instruction or document text, + broker configuration or credential values. + +A terminal receipt distinguishes `completed` execution, pre-dispatch +`rejected` execution and an `unknown` outcome after launch. Completion is +execution evidence. AGH separately confirms the task and its side effects. +The journal persists only receipts and reference metadata. Private native +session files live beside the journal and have the provider's retention and +format. AGH owns journal and runtime retention. + +A replay of the same still-authorized envelope returns +`dispatch_already_recorded` with the prior receipt and executes no native turn. +Key reuse with changed input yields `idempotency_conflict`. A claimed dispatch +without a terminal receipt yields `dispatch_unknown`, including an interrupted +process or an in-flight concurrent request. Reconcile side effects before +assigning a new dispatch key. Separate machines must share the same dispatch +owner or use AGH's own durable claim system. + +## Runtime capabilities + +| Capability | Claude stream-json | Codex app-server | +| --- | --- | --- | +| Clean home, config, cwd and explicit instructions | Yes | Yes | +| Explicit ambient runtime | Yes, fresh invocation | Pre-dispatch rejection | +| Additional workspace roots | Native `--add-dir` | Thread and turn workspace roots | +| Exact Skill snapshots | Pre-dispatch rejection | Verified staged copies | +| Tool-scoped credential broker | MCP | MCP | +| Managed native resume | Same clean runtime and compatible fingerprint | Same clean runtime and compatible fingerprint | +| Explicit task checkpoint handoff | Yes | Yes | + +`RequiredCapabilities` accepts `clean`, `ambient`, `preset_documents`, +`resource_roots`, `native_resume`, `exact_skills`, `mcp`, `credential_broker` +and `checkpoint`. Unknown or unavailable requirements fail before launch. + +Clean is the default. Offload creates a private native home and empty cwd with +the primary project as the first workspace root. Only selected roots go into +the native protocol. The boot environment keeps PATH and locale and sets fresh +home/config/cache/data locations. Claude clean mode uses an explicit gateway +token in the selected profile. Codex clean mode uses a caller-supplied +`ContextExecution.CodexAPIKey` and an empty native authentication directory at +first launch. The selected profile and executable are explicit in both cases. +Set `Runtime.AuthVersion` to the provider credential version and change it on +rotation. + +Claude ambient mode additionally requires explicit authorization in the +envelope and in `Authorize`. Its cwd is the primary project. The receipt +identifies the inherited HOME, Claude configuration, Skill/plugin roots and +environment classes. A clean setup failure ends the dispatch. + +Workspace roots constrain native context selection. Filesystem access still +depends on the caller's OS permissions. Requests that require an enforced +per-root mode, such as read-only, fail before dispatch. +The declared tools select MCP servers. Native built-in tool behavior follows +the adapter's permission policy. Claude supports explicit tool-free execution +through `Runtime.ToolsDisabled`. + +Resume requires the `NativeSessionRef` from the latest successful receipt and +the same subject, task, scope, authorization, runtime and injected context +fingerprint. The next turn may supply a new task message. One successor can +claim a receipt. Use reference-based handoff after uncertain native execution, +when native state is absent, or when the receiving configuration changes. +Credential-bound turns start fresh and have no reusable managed session. + +## Checkpoints and tool leases + +Call `ContextStore.SaveCheckpoint` with the source run and the explicitly +confirmed steps, independent evidence references, pending/unknown step IDs and +artifact references. Repeating an identical save returns the same reference. +The receiving Agent supplies that reference in a new envelope. AGH selects and +assembles the authorized facts or artifacts into that request. It can allow a +different audience, scope or backend after independently authorizing the +references. Offload never reads the producer's native transcript to assemble +the receiver's context. + +Version 1 supports `broker` and `mcp` credential delivery. Offload validates an +opaque, time-limited binding against its Run and declared MCP tool. The broker +installs a dedicated endpoint with non-secret configuration. It authenticates +the tool process, enforces allowed operations, redemption counts, expiry and +revocation, and scrubs results before returning them to the native harness. +Secret values are never passed to Offload by this interface. + +Offload bounds the run by the earliest envelope, checkpoint or lease expiry. +It calls broker release on success, error and cancellation, including partial +activation. A release failure is visible in the receipt. The broker owns expiry +and revocation after process death. Unsupported delivery methods such as direct +environment values or temporary secret files fail before native launch. diff --git a/docs/execution-pkg.md b/docs/execution-pkg.md index 4a1c3ac..909b4d1 100644 --- a/docs/execution-pkg.md +++ b/docs/execution-pkg.md @@ -67,6 +67,9 @@ a normalized or complete UI transcript. [API, compatibility and validation details](execution-pkg-detail.md). +For authorization-bound runtime setup, injection receipts and reference-based +handoff, see [AGH context execution](context-execution.md). + ## Embedding a full Host Optional `Request.Native` controls let an embedding Host preserve Claude session diff --git a/internal/worker/codex_app_server.go b/internal/worker/codex_app_server.go index f044606..47d3905 100644 --- a/internal/worker/codex_app_server.go +++ b/internal/worker/codex_app_server.go @@ -31,20 +31,21 @@ type jsonRPCMessage struct { } type appServerParser struct { - mu sync.Mutex - w io.WriteCloser - nextID int - pending map[string]chan jsonRPCMessage - done chan struct{} - doneOnce sync.Once - err error - s streamSummary - threadID string - turnID string - report strings.Builder - completedReport string - skillConfig []appServerSkillConfig - o Opts + mu sync.Mutex + w io.WriteCloser + nextID int + turnStartRequest string + pending map[string]chan jsonRPCMessage + done chan struct{} + doneOnce sync.Once + err error + s streamSummary + threadID string + turnID string + report strings.Builder + completedReport string + skillConfig []appServerSkillConfig + o Opts } func newAppServerParser(w io.WriteCloser, o Opts) *appServerParser { @@ -76,6 +77,15 @@ func (p *appServerParser) feed(line []byte) { p.mu.Lock() ch := p.pending[key] delete(p.pending, key) + if ch != nil && p.o.Context != nil && key == p.turnStartRequest && len(m.Error) == 0 { + var response struct { + Turn struct{ ID string } `json:"turn"` + } + if json.Unmarshal(m.Result, &response) == nil && response.Turn.ID != "" { + p.turnID = response.Turn.ID + p.o.Context.Injected() + } + } p.mu.Unlock() if ch == nil { p.fail(errors.New("Codex app-server returned an unknown JSON-RPC id")) @@ -247,6 +257,9 @@ func (p *appServerParser) request(method string, params any) (json.RawMessage, e ch := make(chan jsonRPCMessage, 1) p.pending[id] = ch requestID := p.nextID + if p.o.Context != nil && method == "turn/start" { + p.turnStartRequest = id + } p.mu.Unlock() if err := p.write(map[string]any{"jsonrpc": "2.0", "id": requestID, "method": method, "params": params}); err != nil { return nil, err @@ -303,6 +316,9 @@ func (p *appServerParser) initialize() error { if json.Unmarshal(threadRaw, &thread) != nil || thread.Thread.ID == "" { return errors.New("Codex app-server returned an invalid thread") } + if p.o.Context != nil && p.o.Resume != "" && thread.Thread.ID != p.o.Resume { + return errors.New("Codex app-server acknowledged a different native thread") + } p.mu.Lock() p.threadID, p.s.Session = thread.Thread.ID, thread.Thread.ID p.s.ObservedModel = firstNonEmpty(thread.Model, thread.Thread.Model) @@ -313,6 +329,9 @@ func (p *appServerParser) initialize() error { _ = json.Unmarshal([]byte(p.o.Native.JSONSchema), &schema) turn["outputSchema"] = schema } + if p.o.Context != nil { + p.o.Context.Dispatched() + } turnRaw, err := p.request("turn/start", turn) if err != nil { return err diff --git a/internal/worker/environment.go b/internal/worker/environment.go index 14a4976..280a34a 100644 --- a/internal/worker/environment.go +++ b/internal/worker/environment.go @@ -173,7 +173,12 @@ func (o *Opts) prepareEnvironment(sourceHome string) (func() error, error) { return nil, err } o.environment = []string{"HOME=" + filepath.Join(root, "home"), "XDG_CONFIG_HOME=" + filepath.Join(root, "config"), "XDG_CACHE_HOME=" + filepath.Join(root, "cache"), "XDG_DATA_HOME=" + filepath.Join(root, "data"), "XDG_STATE_HOME=" + filepath.Join(root, "data"), "CLAUDE_CONFIG_DIR=" + filepath.Join(root, "claude")} - for _, key := range []string{"PATH", "TMPDIR", "LANG", "LC_ALL", "SSL_CERT_FILE", "SSL_CERT_DIR"} { + keys := []string{"PATH", "TMPDIR", "LANG", "LC_ALL", "SSL_CERT_FILE", "SSL_CERT_DIR"} + if o.Context != nil && o.Context.Clean { + keys = []string{"PATH", "LANG", "LC_ALL"} + o.environment = append(o.environment, "TMPDIR="+filepath.Join(root, "cache")) + } + for _, key := range keys { if value, ok := os.LookupEnv(key); ok { o.environment = append(o.environment, key+"="+value) } @@ -193,6 +198,12 @@ func (o *Opts) prepareEnvironment(sourceHome string) (func() error, error) { return nil, errors.New("native session is not recorded in this isolated environment") } } + if o.Context != nil && o.Context.Clean { + if _, err := os.Lstat(filepath.Join(destination, "auth.json")); !errors.Is(err, os.ErrNotExist) { + return nil, errors.New("clean Codex context requires an absent native auth.json") + } + return func() error { return nil }, nil + } target := filepath.Join(destination, "auth.json") source := filepath.Join(sourceHome, "auth.json") if st, err := os.Lstat(source); err == nil && st.Mode()&os.ModeSymlink != 0 { diff --git a/internal/worker/worker.go b/internal/worker/worker.go index 344be79..dc3bbcd 100644 --- a/internal/worker/worker.go +++ b/internal/worker/worker.go @@ -54,6 +54,7 @@ var errIdle = errors.New("worker idle") // Opts is one worker run. type Opts struct { EnvironmentDirectory string + Context *ContextDispatch environment []string // EnvSet and EnvUnset are per-run caller changes to the child environment, // applied before Offload's own credential and account variables. @@ -102,6 +103,15 @@ type Opts struct { Limits config.Limits } +// ContextDispatch carries the managed launch policy and evidence hooks. +type ContextDispatch struct { + Clean bool + Executable string + BeforeStart func(context.Context) error + Dispatched func() + Injected func() +} + // Capture is structurally shared with the public execution package, keeping // recorder ownership outside the native worker without creating an import cycle. type Capture interface { @@ -279,7 +289,7 @@ func childEnv(base []string, o Opts, token string) []string { env = append(env, "CLAUDE_CONFIG_DIR="+o.Native.ProfileDirectory) } env = append(env, "CLAUDE_CODE_DISABLE_AUTO_MEMORY=1") - if !o.Native.Extraction && !o.Native.RestrictedReadOnly && len(o.AddDirs) > 0 { + if o.Context == nil && !o.Native.Extraction && !o.Native.RestrictedReadOnly && len(o.AddDirs) > 0 { env = append(env, "CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1") } for k, v := range o.Native.StreamEnvironment { @@ -364,11 +374,11 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) { return rec, fmt.Errorf("session managed account home changed") } o.CodexHome = accountHome - } else if o.Profile.BackendName() == "codex" && o.CodexHome == "" { + } else if o.Profile.BackendName() == "codex" && o.CodexHome == "" && o.Context == nil { o.CodexHome = codexHome() } sourceHome := o.CodexHome - if o.EnvironmentDirectory != "" && o.Profile.BackendName() == "codex" && o.Profile.CodexAccount == "" { + if o.EnvironmentDirectory != "" && o.Profile.BackendName() == "codex" && o.Profile.CodexAccount == "" && o.Context == nil { sourceHome = codexHome() if o.CodexHome != "" && o.CodexHome != sourceHome && o.CodexHome != filepath.Join(o.EnvironmentDirectory, "codex") { return rec, errors.New("isolated Codex account home changed") @@ -491,7 +501,11 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) { switch rec.Backend { case "codex": rec.ErrorKind = "launch" - bin, err = codexBin() + if o.Context != nil { + bin = o.Context.Executable + } else { + bin, err = codexBin() + } if err != nil { return rec, fmt.Errorf("codex CLI not found: %w", err) } @@ -515,7 +529,9 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) { } } rec.ErrorKind = "launch" - if o.Native != nil && o.Native.Executable != "" { + if o.Context != nil { + bin = o.Context.Executable + } else if o.Native != nil && o.Native.Executable != "" { bin = o.Native.Executable } else { bin, err = claudeBin() @@ -551,6 +567,10 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) { hooks := hooks{starting: slot.Starting, startFailed: slot.StartFailed, started: func(g proc.Group) { slot.Track(g); pub.group(g) }, cleaning: func() { pub.phase(live.Cleaning) }, cleaned: slot.Clear} a := runAttempt(ctx, bin, o, promptPath, token, o.Timeout, pub.update, hooks) + if a.contextErr != nil { + rec.ErrorKind = "context_denied" + return rec, a.contextErr + } if a.gateErr != nil { rec.ErrorKind = ErrorKind(a.gateErr) return rec, a.gateErr @@ -565,6 +585,13 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) { leftover = a.leftover } s := a.s + if o.Context != nil && o.Resume != "" && s.Result != nil { + observed := firstNonEmpty(s.Result.SessionID, s.Session) + if observed != o.Resume || s.Session != "" && s.Session != o.Resume { + rec.ErrorKind = "session_incompatible" + return rec, errors.New("native harness did not confirm the requested continuation") + } + } if rec.Backend == "agy" { rec.ObservedModel = s.ObservedModel rec.Model = firstNonEmpty(s.ObservedModel, o.Model) @@ -734,6 +761,7 @@ func Run(ctx context.Context, o Opts) (rec history.Record, err error) { // attempt is the outcome of one worker process. type attempt struct { + contextErr error gateErr error // admission failure before any backend process starts baseline *history.TokenUsage baselineError string @@ -911,6 +939,14 @@ func runAttempt(ctx context.Context, bin string, o Opts, promptPath, token strin if err := config.CheckEnabled(); err != nil { return attempt{runErr: err, gateErr: err} } + if o.Context != nil { + if err := o.Context.BeforeStart(ctx); err != nil { + return attempt{contextErr: err} + } + if err := ctx.Err(); err != nil { + return attempt{contextErr: err} + } + } kind := transcript.AttemptKindRun if o.Salvage { kind = transcript.AttemptKindReport @@ -929,6 +965,9 @@ func runAttempt(ctx context.Context, bin string, o Opts, promptPath, token strin } if appServer != nil { appServer.start() + } else if o.Context != nil { + o.Context.Dispatched() + o.Context.Injected() } if acp != nil { acp.start(o, acpPrompt) diff --git a/pkg/execution/context_contract.go b/pkg/execution/context_contract.go new file mode 100644 index 0000000..03ffd99 --- /dev/null +++ b/pkg/execution/context_contract.go @@ -0,0 +1,357 @@ +package execution + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "strings" + "time" +) + +const ContextSchemaVersion = "1.0" + +type RuntimeMode string + +const ( + RuntimeClean RuntimeMode = "clean" + RuntimeAmbient RuntimeMode = "ambient" +) + +// ContextEnvelope freezes AGH's authorization and assembly input. The caller +// resolves project, root and Skill references to trusted local paths before +// sealing. Instruction and task bytes travel separately in Request. +type ContextEnvelope struct { + SchemaVersion string `json:"schema_version"` + EnvelopeID string `json:"envelope_id"` + CreatedAt time.Time `json:"created_at"` + ExpiresAt time.Time `json:"expires_at"` + TenantID string `json:"tenant_id"` + RunID string `json:"run_id"` + TaskID string `json:"task_id"` + Caller string `json:"caller"` + Subject ContextSubject `json:"subject"` + Scope []string `json:"scope"` + Project ContextProject `json:"project"` + Runtime ContextRuntime `json:"runtime"` + ResourceRoots []ContextRoot `json:"resource_roots,omitempty"` + KnowledgeManifest KnowledgeManifest `json:"knowledge_manifest"` + TaskDigest string `json:"task_digest"` + InstructionsDigest string `json:"instructions_digest"` + PresetDocuments []ContextDocument `json:"preset_documents,omitempty"` + Skills []ContextSkill `json:"skills,omitempty"` + Tools []ContextTool `json:"tools,omitempty"` + CredentialBindings []CredentialBinding `json:"credential_bindings,omitempty"` + CheckpointRef *CheckpointRef `json:"checkpoint_ref,omitempty"` + RequiredCapabilities []string `json:"required_capabilities,omitempty"` + IdempotencyKey string `json:"idempotency_key"` + EnvelopeDigest string `json:"envelope_digest,omitempty"` + Extensions map[string]json.RawMessage `json:"-"` +} + +type ContextSubject struct { + UserID string `json:"user_id"` + AgentID string `json:"agent_id"` + RoleIDs []string `json:"role_ids,omitempty"` + Audience string `json:"audience"` +} + +type ContextProject struct { + PrimaryID string `json:"primary_id"` + WorkspaceRef string `json:"workspace_ref"` + Revision string `json:"revision,omitempty"` +} + +type ContextRuntime struct { + Mode RuntimeMode `json:"mode,omitempty"` + Adapter string `json:"adapter"` + Profile string `json:"profile"` + Model string `json:"model,omitempty"` + Executable string `json:"executable"` + ExecutableDigest string `json:"executable_digest"` + AuthVersion string `json:"auth_version"` + PermissionMode string `json:"permission_mode"` + ToolsDisabled bool `json:"tools_disabled,omitempty"` + NativeSessionRef *NativeSessionRef `json:"native_session_ref,omitempty"` +} + +type NativeSessionRef struct { + ID string `json:"id"` + SourceRunID string `json:"source_run_id"` + IdempotencyKey string `json:"idempotency_key"` + RuntimeFingerprint string `json:"runtime_fingerprint"` +} + +type ContextRoot struct { + ID string `json:"id"` + PathRef string `json:"path_ref"` + // "workspace" is a native working root. It does not assert OS containment. + Access string `json:"access"` + Digest string `json:"digest,omitempty"` +} + +type KnowledgeManifest struct { + GenerationID string `json:"generation_id"` + NoteSnapshotVersion string `json:"note_snapshot_version"` + AuthorizationVersion string `json:"authorization_version"` + Digest string `json:"digest"` +} + +type ContextDocument struct { + Name string `json:"name"` + ContentRef string `json:"content_ref"` + Digest string `json:"digest"` + Bytes int `json:"bytes"` + Classification string `json:"classification"` +} + +type ContextSkill struct { + StableID string `json:"stable_id"` + Revision string `json:"revision"` + Digest string `json:"digest"` + MountRef string `json:"mount_ref"` +} + +type ContextTool struct { + ID string `json:"id"` + Version string `json:"version"` + CapabilityDigest string `json:"capability_digest"` + PolicyRef string `json:"policy_ref"` +} + +// CredentialBinding carries only opaque metadata. The AGH broker owns tool +// authorization, redemption and lease recovery after crashes. +type CredentialBinding struct { + BindingID string `json:"binding_id"` + BindingVersion string `json:"binding_version"` + PolicyFingerprint string `json:"policy_fingerprint"` + ToolID string `json:"tool_id"` + TargetEnvironment string `json:"target_environment"` + Purpose string `json:"purpose"` + RunID string `json:"run_id"` + Delivery string `json:"delivery"` + AllowedOperations []string `json:"allowed_operations"` + IssuedAt time.Time `json:"issued_at"` + NotAfter time.Time `json:"not_after"` + MaxRedemptions int `json:"max_redemptions"` + CleanupRequired bool `json:"cleanup_required"` + MetadataDigest string `json:"metadata_digest,omitempty"` +} + +type CredentialReceipt struct { + BindingID string `json:"binding_id"` + BindingVersion string `json:"binding_version"` + ToolID string `json:"tool_id"` + LeaseState string `json:"lease_state"` + RedeemedAt *time.Time `json:"redeemed_at,omitempty"` + ExpiredAt *time.Time `json:"expired_at,omitempty"` + CleanupState string `json:"cleanup_state"` + CleanupErrorCode string `json:"cleanup_error_code,omitempty"` +} + +// ContextAuthority evaluates current grants, including explicit ambient +// permission and every checkpoint item. It must honor cancellation and must +// not mutate the input. Offload calls it again at the native launch boundary. +type ContextAuthority func(context.Context, ContextEnvelope, *TaskCheckpoint) error + +// CredentialBroker installs a dedicated MCP endpoint for this Run and tool. +// Activate returns only an executable and non-secret arguments. The server +// authenticates at its tool boundary, redacts tool results before returning +// them to the model, and enforces TTL, revocation and redemption limits. +// Release is idempotent, including after partial activation. Implementations +// honor cancellation and recover leases after Offload process death. +type CredentialBroker interface { + Activate(context.Context, CredentialBinding) (MCPServer, error) + Release(context.Context, CredentialBinding) (LeaseOutcome, error) +} + +type LeaseOutcome struct { + State string + RedeemedAt *time.Time +} + +// ContextExecution carries caller-owned services and resolved MCP configs. +// CodexAPIKey is a clean-mode provider credential passed only to the native +// child's environment. Tool credentials use the broker. +type ContextExecution struct { + Envelope ContextEnvelope + Store *ContextStore `json:"-"` + Authorize ContextAuthority `json:"-"` + Broker CredentialBroker `json:"-"` + MCPServers []MCPServer `json:"-"` + CodexAPIKey string `json:"-"` +} + +type ContextReceipt struct { + SchemaVersion string `json:"schema_version"` + EnvelopeID string `json:"envelope_id"` + RunID string `json:"run_id"` + AcceptedEnvelopeDigest string `json:"accepted_envelope_digest,omitempty"` + RuntimeFingerprint string `json:"runtime_fingerprint,omitempty"` + AdapterCapabilitiesDigest string `json:"adapter_capabilities_digest"` + Mode RuntimeMode `json:"mode"` + Workspace string `json:"workspace,omitempty"` + Ambient *AmbientSources `json:"ambient,omitempty"` + KnowledgeManifest *KnowledgeManifest `json:"knowledge_manifest,omitempty"` + MountedRoots []ContextRoot `json:"mounted_roots,omitempty"` + InjectedDocuments []InjectedDocument `json:"injected_documents,omitempty"` + InstructionsDigest string `json:"instructions_digest,omitempty"` + InstructionsBytes int `json:"instructions_bytes"` + MountedSkills []MountedSkill `json:"mounted_skills,omitempty"` + ToolBindings []ToolBinding `json:"tool_bindings,omitempty"` + CredentialReceipts []CredentialReceipt `json:"credential_receipts,omitempty"` + NativeSessionRef *NativeSessionRef `json:"native_session_ref,omitempty"` + CheckpointRef *CheckpointRef `json:"checkpoint_ref,omitempty"` + EvidenceRefs []string `json:"evidence_refs,omitempty"` + StartedAt time.Time `json:"started_at"` + CompletedAt time.Time `json:"completed_at"` + Status string `json:"status"` + ErrorCode string `json:"error_code,omitempty"` +} + +type InjectedDocument struct { + Name string `json:"name"` + Digest string `json:"digest"` + Bytes int `json:"bytes"` +} + +type MountedSkill struct { + StableID string `json:"stable_id"` + Revision string `json:"revision"` + Digest string `json:"digest"` + Path string `json:"path"` +} + +type ToolBinding struct { + ID string `json:"id"` + Version string `json:"version"` +} + +// AmbientSources describes inherited paths and environment classes without +// logging environment values. +type AmbientSources struct { + Home string `json:"home"` + NativeConfig string `json:"native_config"` + SkillRoots []string `json:"skill_roots"` + EnvironmentClasses []string `json:"environment_classes"` +} + +type AdapterCapabilities struct { + Clean, Ambient, PresetDocuments, ResourceRoots, NativeResume, ExactSkills, MCP, CredentialBroker, Checkpoint bool +} + +func ContextCapabilities(adapter string) AdapterCapabilities { + switch adapter { + case "claude", "codex": + return AdapterCapabilities{ + Clean: true, Ambient: adapter == "claude", PresetDocuments: true, ResourceRoots: true, + NativeResume: true, ExactSkills: adapter == "codex", MCP: true, CredentialBroker: true, Checkpoint: true, + } + default: + return AdapterCapabilities{} + } +} + +type envelopeFields ContextEnvelope + +// MarshalJSON preserves optional extension fields when forwarding an envelope. +func (e ContextEnvelope) MarshalJSON() ([]byte, error) { + raw, err := json.Marshal(envelopeFields(e)) + if err != nil || len(e.Extensions) == 0 { + return raw, err + } + var fields map[string]json.RawMessage + _ = json.Unmarshal(raw, &fields) + known := knownEnvelopeFields() + for key, value := range e.Extensions { + if known[strings.ToLower(key)] { + return nil, errors.New("context extension conflicts with a known field") + } + fields[key] = value + } + return json.Marshal(fields) +} + +func (e *ContextEnvelope) UnmarshalJSON(raw []byte) error { + var decoded envelopeFields + if err := json.Unmarshal(raw, &decoded); err != nil { + return err + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(raw, &fields); err != nil { + return err + } + for key := range knownEnvelopeFields() { + delete(fields, key) + } + *e = ContextEnvelope(decoded) + if len(fields) != 0 { + e.Extensions = fields + } + return nil +} + +func knownEnvelopeFields() map[string]bool { + const names = "schema_version envelope_id created_at expires_at tenant_id run_id task_id caller subject scope project runtime resource_roots knowledge_manifest task_digest instructions_digest preset_documents skills tools credential_bindings checkpoint_ref required_capabilities idempotency_key envelope_digest" + fields := make(map[string]bool) + for _, name := range strings.Fields(names) { + fields[name] = true + } + return fields +} + +func ContextContentDigest(content []byte) string { + sum := sha256.Sum256(content) + return hex.EncodeToString(sum[:]) +} + +// ContextDigest hashes compact Go JSON with ordered object keys, preserving +// number tokens. Envelope digests omit the envelope_digest field. +func ContextDigest(value any) (string, error) { + raw, err := json.Marshal(value) + if err != nil { + return "", err + } + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.UseNumber() + var canonical any + if err := decoder.Decode(&canonical); err != nil { + return "", err + } + raw, err = json.Marshal(canonical) + if err != nil { + return "", err + } + return ContextContentDigest(raw), nil +} + +func (e ContextEnvelope) Digest() (string, error) { + e.EnvelopeDigest = "" + return ContextDigest(e) +} + +func (b CredentialBinding) Digest() (string, error) { + b.MetadataDigest = "" + return ContextDigest(b) +} + +func readerDigest(r io.Reader) (string, error) { + h := sha256.New() + if _, err := io.Copy(h, r); err != nil { + return "", err + } + return hex.EncodeToString(h.Sum(nil)), nil +} + +func validDigest(value string) bool { + _, err := hex.DecodeString(value) + return len(value) == 64 && err == nil && strings.ToLower(value) == value +} + +func validContextVersion(version string) bool { + major, minor, ok := strings.Cut(version, ".") + return ok && major == "1" && minor != "" && strings.Trim(minor, "0123456789") == "" +} diff --git a/pkg/execution/context_run.go b/pkg/execution/context_run.go new file mode 100644 index 0000000..b19a5fd --- /dev/null +++ b/pkg/execution/context_run.go @@ -0,0 +1,575 @@ +package execution + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "slices" + "strings" + "sync/atomic" + "time" + "unicode/utf8" +) + +type activeContextRun struct { + mode RuntimeMode + executable, codexAPIKey string + authorize func(context.Context) error + dispatched, injected atomic.Bool +} + +type contextPlan struct { + mode RuntimeMode + roots []ContextRoot + instructions []byte + native *NativeControls + ambient *AmbientSources + fingerprint string +} + +func (c *Client) runContext(ctx context.Context, req Request) (result Result, resultErr error) { + services := *req.Context + e, err := snapshotEnvelope(services.Envelope) + mode := e.Runtime.Mode + if mode == "" { + mode = RuntimeClean + } + capabilities := ContextCapabilities(c.profile.BackendName()) + capabilityDigest, _ := ContextDigest(capabilities) + receipt := &ContextReceipt{ + SchemaVersion: ContextSchemaVersion, EnvelopeID: e.EnvelopeID, RunID: e.RunID, + AdapterCapabilitiesDigest: capabilityDigest, Mode: mode, StartedAt: time.Now().UTC(), + } + fail := func(kind, message string) (Result, error) { + return Result{RunID: e.RunID, Profile: c.cfg.ProfileName, Backend: c.profile.BackendName(), + Status: "error", ErrorKind: kind, Error: message, ExitCode: 2}, + &RunError{Kind: kind, Status: "error", ExitCode: 2, Cause: errors.New(message)} + } + defer func() { + if result.ContextReceipt == nil { + finishContextReceipt(receipt, result, "rejected") + result.ContextReceipt = receipt + } + }() + if err != nil || services.Store == nil || services.Store.root == "" || services.Authorize == nil { + return fail("context_invalid", "context requires a valid envelope, journal and authorization callback") + } + plan, kind, err := c.planContext(req, e, mode, capabilities, services) + if err != nil { + return fail(kind, err.Error()) + } + store := services.Store + var checkpoint *TaskCheckpoint + if e.CheckpointRef != nil { + checkpoint, err = store.loadCheckpoint(e.TenantID, e.TaskID, *e.CheckpointRef) + if err != nil { + return fail("checkpoint_invalid", "checkpoint reference is missing or has changed") + } + } + deadline := e.ExpiresAt + if checkpoint != nil && checkpoint.ExpiresAt.Before(deadline) { + deadline = checkpoint.ExpiresAt + } + for _, binding := range e.CredentialBindings { + if binding.NotAfter.Before(deadline) { + deadline = binding.NotAfter + } + } + ctx, cancel := context.WithDeadline(ctx, deadline) + defer cancel() + authorize := func(ctx context.Context) error { + if ctx.Err() != nil { + return errors.New("managed context is canceled or expired") + } + if err := services.Authorize(ctx, e, checkpoint); err != nil || ctx.Err() != nil { + return errors.New("current context authorization was denied") + } + return nil + } + if err := authorize(ctx); err != nil { + return fail("context_denied", err.Error()) + } + entry := store.entry(e.TenantID, e.TaskID, e.IdempotencyKey) + if _, err := os.Lstat(entry); err == nil { + return readContextRetry(entry, e, receipt) + } else if !errors.Is(err, os.ErrNotExist) { + return fail("context_journal", "cannot inspect the dispatch journal") + } + environment, sourceEntry, err := store.contextEnvironment(e, plan, entry) + if err != nil { + return fail("session_incompatible", err.Error()) + } + if err := store.claim(e, entry); err != nil { + if errors.Is(err, errRunClaimed) { + return fail("idempotency_conflict", err.Error()) + } + if _, statErr := os.Lstat(entry); statErr != nil { + return fail("context_journal", "cannot create the dispatch journal claim") + } + return readContextRetry(entry, e, receipt) + } + active := &activeContextRun{mode: mode, executable: e.Runtime.Executable, codexAPIKey: services.CodexAPIKey} + nativeCompleted := false + receipt.AcceptedEnvelopeDigest = e.EnvelopeDigest + receipt.CheckpointRef = e.CheckpointRef + receipt.RuntimeFingerprint, _ = ContextDigest([]string{plan.fingerprint, environment}) + defer func() { + if active.dispatched.Load() { + receipt.EvidenceRefs = []string{e.RunID} + } + if active.injected.Load() { + manifest := e.KnowledgeManifest + receipt.KnowledgeManifest = &manifest + receipt.Workspace, receipt.Ambient = req.Directory, plan.ambient + receipt.MountedRoots = plan.roots + for _, doc := range e.PresetDocuments { + receipt.InjectedDocuments = append(receipt.InjectedDocuments, InjectedDocument{Name: doc.Name, Digest: doc.Digest, Bytes: doc.Bytes}) + } + for index, skill := range e.Skills { + receipt.MountedSkills = append(receipt.MountedSkills, MountedSkill{ + StableID: skill.StableID, Revision: skill.Revision, Digest: skill.Digest, Path: plan.native.SkillRoots[index], + }) + } + for _, tool := range e.Tools { + receipt.ToolBindings = append(receipt.ToolBindings, ToolBinding{ID: tool.ID, Version: tool.Version}) + } + receipt.InstructionsDigest, receipt.InstructionsBytes = ContextContentDigest(plan.instructions), len(plan.instructions) + } + status := "rejected" + if active.dispatched.Load() { + status = "unknown" + } + if nativeCompleted && active.injected.Load() { + status = "completed" + if mode == RuntimeClean && len(e.CredentialBindings) == 0 && validIDs(result.NativeSessionID) { + receipt.NativeSessionRef = &NativeSessionRef{result.NativeSessionID, e.RunID, e.IdempotencyKey, receipt.RuntimeFingerprint} + } + } + finishContextReceipt(receipt, result, status) + if err := publishContextFile(filepath.Join(entry, "receipt.json"), contextCompletion{Receipt: *receipt, Environment: environment}); err != nil { + receipt.NativeSessionRef = nil + resultErr = errors.Join(resultErr, &RunError{Kind: "context_journal", Status: status, ExitCode: result.ExitCode}) + } + result.ContextReceipt = receipt + }() + if sourceEntry != "" { + if err := publishContextFile(filepath.Join(sourceEntry, "successor.json"), e.RunID); err != nil { + return fail("session_incompatible", "native session source already has a continuation") + } + } + if mode == RuntimeClean { + if sourceEntry == "" { + if _, err := NewEnvironmentAt(environment); err != nil { + return fail("context_environment", "could not create the clean runtime") + } + } + req.EnvironmentDirectory = environment + req.Directory = filepath.Join(environment, "workspace") + } else { + req.Directory = e.Project.WorkspaceRef + } + if e.Runtime.NativeSessionRef != nil { + req.NativeSessionID = e.Runtime.NativeSessionRef.ID + } + plan.native.SkillRoots, err = stageContextSkills(e.Skills, environment, sourceEntry != "") + if err != nil { + return fail("context_material", "could not verify or stage exact Skill snapshots") + } + req.AdditionalDirectories = make([]string, 0, len(plan.roots)) + for _, root := range plan.roots { + req.AdditionalDirectories = append(req.AdditionalDirectories, root.PathRef) + } + if mode == RuntimeAmbient { + plan.native.ProfileDirectory = plan.ambient.NativeConfig + } + active.authorize = func(ctx context.Context) error { + if err := authorize(ctx); err != nil { + return err + } + if err := verifyContextExecutable(e.Runtime); err != nil { + return err + } + for _, root := range plan.roots { + if !contextDirectory(root.PathRef) { + return errors.New("authorized resource root changed before dispatch") + } + } + if mode == RuntimeAmbient && !contextDirectory(e.Project.WorkspaceRef) { + return errors.New("authorized working directory changed before dispatch") + } + return nil + } + // Register cleanup before activation. Release is safe after partial activation + // and runs before the terminal receipt is published, even after cancellation. + activeBindings := 0 + defer func() { + for index := activeBindings - 1; index >= 0; index-- { + binding := e.CredentialBindings[index] + state := &receipt.CredentialReceipts[index] + releaseCtx, releaseCancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + outcome, err := services.Broker.Release(releaseCtx, binding) + releaseCancel() + expired := !time.Now().Before(binding.NotAfter) + if expired { + state.ExpiredAt = &binding.NotAfter + } + if err != nil || !validLeaseOutcome(outcome, binding) { + state.CleanupState, state.CleanupErrorCode = "failed", "broker_release_failed" + resultErr = errors.Join(resultErr, &RunError{Kind: "credential_cleanup", Status: result.Status, ExitCode: result.ExitCode}) + if result.ErrorKind == "" { + result.ErrorKind = "credential_cleanup" + } + continue + } + state.LeaseState, state.RedeemedAt, state.CleanupState = outcome.State, outcome.RedeemedAt, "released" + } + }() + for _, binding := range e.CredentialBindings { + if ctx.Err() != nil { + return fail("context_denied", "managed context expired before credential activation") + } + receipt.CredentialReceipts = append(receipt.CredentialReceipts, CredentialReceipt{ + BindingID: binding.BindingID, BindingVersion: binding.BindingVersion, ToolID: binding.ToolID, + LeaseState: "activation_unknown", CleanupState: "pending", + }) + activeBindings++ + server, err := services.Broker.Activate(ctx, binding) + if err != nil || server.Name != binding.ToolID { + return fail("credential_binding", "broker could not activate the authorized MCP tool") + } + receipt.CredentialReceipts[activeBindings-1].LeaseState = "active" + plan.native.MCPServers = append(plan.native.MCPServers, cloneContextServer(server)) + } + req.Context = nil + req.RunID, req.Caller, req.Model = e.RunID, e.Caller, e.Runtime.Model + req.Native, req.Instructions, req.PresetDocuments = plan.native, plan.instructions, nil + req.ToolsDisabled = e.Runtime.ToolsDisabled + result, resultErr = c.run(ctx, req, active) + nativeCompleted = resultErr == nil && result.Status == "ok" + return result, resultErr +} + +func snapshotEnvelope(e ContextEnvelope) (ContextEnvelope, error) { + raw, err := json.Marshal(e) + if err != nil || len(raw) > 256<<10 { + return ContextEnvelope{}, errors.New("invalid or oversized envelope") + } + var snapshot ContextEnvelope + err = json.Unmarshal(raw, &snapshot) + return snapshot, err +} + +func finishContextReceipt(receipt *ContextReceipt, result Result, status string) { + receipt.Status, receipt.ErrorCode = status, result.ErrorKind + receipt.CompletedAt = time.Now().UTC() +} + +func readContextRetry(entry string, e ContextEnvelope, receipt *ContextReceipt) (Result, error) { + result := Result{RunID: e.RunID, Status: "error", ExitCode: 2, ContextReceipt: receipt} + var claim contextClaim + var done contextCompletion + switch { + case readContextFile(filepath.Join(entry, "claim.json"), &claim) != nil: + result.ErrorKind = "dispatch_unknown" + case claim.EnvelopeDigest != e.EnvelopeDigest || claim.RunID != e.RunID: + result.ErrorKind = "idempotency_conflict" + case readContextFile(filepath.Join(entry, "receipt.json"), &done) != nil: + result.ErrorKind = "dispatch_unknown" + default: + result.ErrorKind, result.ContextReceipt = "dispatch_already_recorded", &done.Receipt + } + if result.ContextReceipt == receipt { + finishContextReceipt(receipt, result, "unknown") + } + return result, &RunError{Kind: result.ErrorKind, Status: result.Status, ExitCode: result.ExitCode} +} + +func (s *ContextStore) contextEnvironment(e ContextEnvelope, plan contextPlan, entry string) (environment, sourceEntry string, err error) { + if plan.mode == RuntimeAmbient { + return "", "", nil + } + session := e.Runtime.NativeSessionRef + if session == nil { + return filepath.Join(entry, "runtime"), "", nil + } + sourceEntry = s.entry(e.TenantID, e.TaskID, session.IdempotencyKey) + var source contextCompletion + if err := readContextFile(filepath.Join(sourceEntry, "receipt.json"), &source); err != nil || source.Receipt.NativeSessionRef == nil { + return "", "", errors.New("native session source receipt is unavailable") + } + expected, _ := ContextDigest([]string{plan.fingerprint, source.Environment}) + if *source.Receipt.NativeSessionRef != *session || expected != session.RuntimeFingerprint || source.Environment == "" { + return "", "", errors.New("native session was issued for a different runtime or authorization") + } + return source.Environment, sourceEntry, nil +} + +func validLeaseOutcome(outcome LeaseOutcome, binding CredentialBinding) bool { + if outcome.RedeemedAt != nil && (outcome.RedeemedAt.Before(binding.IssuedAt) || !outcome.RedeemedAt.Before(binding.NotAfter)) { + return false + } + switch outcome.State { + case "unused", "expired", "revoked": + return true + case "redeemed": + return outcome.RedeemedAt != nil + default: + return false + } +} + +func (c *Client) planContext(req Request, e ContextEnvelope, mode RuntimeMode, capabilities AdapterCapabilities, services ContextExecution) (contextPlan, string, error) { + plan := contextPlan{mode: mode} + invalid := func(message string) (contextPlan, string, error) { return plan, "context_invalid", errors.New(message) } + unsupported := func(message string) (contextPlan, string, error) { + return plan, "unsupported_controls", errors.New(message) + } + now := time.Now() + if !validContextVersion(e.SchemaVersion) || !validIDs(e.EnvelopeID, e.TenantID, e.TaskID, e.RunID, e.IdempotencyKey, + e.Subject.UserID, e.Subject.AgentID, e.Subject.Audience, e.Project.PrimaryID, e.Runtime.AuthVersion, + e.KnowledgeManifest.GenerationID, e.KnowledgeManifest.NoteSnapshotVersion, e.KnowledgeManifest.AuthorizationVersion) || + len(e.Scope) == 0 || !validIDs(e.Scope...) || !validIDs(e.Subject.RoleIDs...) || + e.Caller != "agh" || e.CreatedAt.IsZero() || e.CreatedAt.After(now) || !e.ExpiresAt.After(now) || + !validDigest(e.KnowledgeManifest.Digest) { + return invalid("invalid context identity, version, authorization scope or lifetime") + } + digest, err := e.Digest() + if err != nil || digest != e.EnvelopeDigest { + return invalid("envelope digest does not match") + } + if req.RunID != "" && req.RunID != e.RunID || req.Caller != "" && req.Caller != e.Caller || + req.Directory != "" && req.Directory != e.Project.WorkspaceRef || req.Model != "" && req.Model != e.Runtime.Model || + req.Native != nil || req.EnvironmentDirectory != "" || req.NativeSessionID != "" || req.CodexHome != "" || + len(req.AdditionalDirectories) != 0 || req.ProcessEnvironment != nil || req.InstructionsFile != "" || req.AllowSalvage || + req.ExecutionPolicy != "" || req.CodexSandbox != "" || req.AllowedTools != "" || req.DisallowedTools != "" || req.OnUnsupportedTools != "" || + req.ToolsDisabled && !e.Runtime.ToolsDisabled { + return invalid("run overrides conflict with managed context") + } + if e.Runtime.Adapter != c.profile.BackendName() || e.Runtime.Profile != c.cfg.ProfileName || + mode != RuntimeClean && mode != RuntimeAmbient { + return invalid("runtime adapter, profile or mode does not match the selected client") + } + if !capabilities.Clean || mode == RuntimeAmbient && !capabilities.Ambient || + len(e.Skills) > 0 && !capabilities.ExactSkills || + e.Runtime.NativeSessionRef != nil && (mode != RuntimeClean || len(e.CredentialBindings) > 0) { + return unsupported("selected adapter or runtime mode cannot honor the requested context") + } + if err := requireContextCapabilities(e.RequiredCapabilities, capabilities, mode); err != nil { + return unsupported(err.Error()) + } + if mode == RuntimeClean && (c.profile.UsesNativeAuth() || c.profile.TokenCmd != "" || c.profile.CodexAccount != "") { + return unsupported("clean context requires explicit provider credentials without native account or token-command inheritance") + } + if e.Runtime.Adapter == "codex" && (strings.TrimSpace(services.CodexAPIKey) == "" || strings.ContainsAny(services.CodexAPIKey, "\x00\r\n")) || + e.Runtime.Adapter != "codex" && services.CodexAPIKey != "" { + return invalid("clean Codex requires a caller-supplied provider API key") + } + if err := verifyContextExecutable(e.Runtime); err != nil { + return invalid(err.Error()) + } + if !contextDirectory(e.Project.WorkspaceRef) { + return invalid("primary project must resolve to a canonical absolute directory") + } + if mode == RuntimeClean { + plan.roots = append(plan.roots, ContextRoot{ID: e.Project.PrimaryID, PathRef: e.Project.WorkspaceRef, Access: "workspace"}) + } else { + plan.ambient, err = ambientClaudeSources() + if err != nil { + return invalid("cannot identify the ambient Claude home") + } + } + knownIDs := map[string]bool{e.Project.PrimaryID: true} + knownPaths := map[string]bool{e.Project.WorkspaceRef: true} + for _, root := range e.ResourceRoots { + if root.Access != "workspace" { + return unsupported("adapters cannot enforce the requested root access mode") + } + if !validIDs(root.ID) || !contextDirectory(root.PathRef) || knownIDs[root.ID] || knownPaths[root.PathRef] || + root.Digest != "" && !validDigest(root.Digest) { + return invalid("invalid or duplicate resource root") + } + knownIDs[root.ID], knownPaths[root.PathRef] = true, true + plan.roots = append(plan.roots, root) + } + if e.CheckpointRef != nil && (!validIDs(e.CheckpointRef.ID) || !validDigest(e.CheckpointRef.Digest)) { + return invalid("invalid checkpoint reference") + } + if session := e.Runtime.NativeSessionRef; session != nil && + (!validIDs(session.ID, session.SourceRunID, session.IdempotencyKey) || !validDigest(session.RuntimeFingerprint)) { + return invalid("invalid native session reference") + } + plan.instructions, err = contextInstructions(req, e) + if err != nil { + return invalid(err.Error()) + } + if err := validateContextSkills(e.Skills); err != nil { + return invalid(err.Error()) + } + for _, binding := range e.CredentialBindings { + if binding.Delivery != "mcp" && binding.Delivery != "broker" { + return unsupported("credential delivery requires a tool-bound MCP broker") + } + } + servers, err := contextTools(e, services, now) + if err != nil { + return invalid(err.Error()) + } + plan.native = &NativeControls{CallerContext: true, CodexAppServer: e.Runtime.Adapter == "codex", + PermissionMode: e.Runtime.PermissionMode, MCPServers: servers} + if err := nativeSnapshot(plan.native).Validate(e.Runtime.Adapter, "", e.Runtime.ToolsDisabled); err != nil || + e.Runtime.ToolsDisabled && (len(e.Tools) > 0 || len(e.Skills) > 0) { + return unsupported("selected adapter cannot enforce the requested native controls") + } + // Session compatibility excludes run identity and task bytes, but covers + // every versioned input that could change the context of a native thread. + runtime := e.Runtime + runtime.Mode, runtime.NativeSessionRef = mode, nil + plan.fingerprint, err = ContextDigest([]any{ + e.TenantID, e.TaskID, e.Subject, e.Scope, e.Project, runtime, plan.roots, + e.KnowledgeManifest, e.PresetDocuments, ContextContentDigest(plan.instructions), + e.Skills, e.Tools, e.CredentialBindings, e.CheckpointRef, e.RequiredCapabilities, + e.Extensions, capabilities, c.cfg.Profile, plan.ambient, + }) + if err != nil { + return invalid("cannot fingerprint managed runtime") + } + return plan, "", nil +} + +func requireContextCapabilities(required []string, c AdapterCapabilities, mode RuntimeMode) error { + known := map[string]bool{"clean": c.Clean && mode == RuntimeClean, "ambient": c.Ambient && mode == RuntimeAmbient, + "preset_documents": c.PresetDocuments, "resource_roots": c.ResourceRoots, + "native_resume": c.NativeResume && mode == RuntimeClean, "exact_skills": c.ExactSkills, + "mcp": c.MCP, "credential_broker": c.CredentialBroker, "checkpoint": c.Checkpoint} + for _, name := range required { + if !known[name] { + return errors.New("required context capability is unsupported") + } + } + return nil +} + +func verifyContextExecutable(runtime ContextRuntime) error { + if !filepath.IsAbs(runtime.Executable) || filepath.Clean(runtime.Executable) != runtime.Executable || !validDigest(runtime.ExecutableDigest) { + return errors.New("native executable requires an absolute path and pinned digest") + } + f, err := os.Open(runtime.Executable) + if err != nil { + return errors.New("cannot read the pinned native executable") + } + defer f.Close() + info, err := f.Stat() + if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0111 == 0 { + return errors.New("pinned native executable must be executable and regular") + } + digest, err := readerDigest(f) + if err != nil || digest != runtime.ExecutableDigest { + return errors.New("pinned native executable changed") + } + return nil +} + +func contextDirectory(dir string) bool { + if !filepath.IsAbs(dir) || filepath.Clean(dir) != dir { + return false + } + canonical, err := filepath.EvalSymlinks(dir) + if err != nil || canonical != dir { + return false + } + info, err := os.Stat(dir) + return err == nil && info.IsDir() +} + +func ambientClaudeSources() (*AmbientSources, error) { + home, err := os.UserHomeDir() + if err != nil || !filepath.IsAbs(home) { + return nil, errors.New("ambient user home is unavailable") + } + configDir := os.Getenv("CLAUDE_CONFIG_DIR") + if configDir == "" { + configDir = filepath.Join(home, ".claude") + } + if !filepath.IsAbs(configDir) || filepath.Clean(configDir) != configDir { + return nil, errors.New("ambient Claude configuration path is invalid") + } + return &AmbientSources{Home: home, NativeConfig: configDir, + SkillRoots: []string{filepath.Join(configDir, "skills"), filepath.Join(configDir, "plugins")}, + EnvironmentClasses: []string{"caller-process-environment", "native-profile-state"}}, nil +} + +func contextInstructions(req Request, e ContextEnvelope) ([]byte, error) { + if strings.TrimSpace(req.Task) == "" || !utf8.ValidString(req.Task) || strings.ContainsRune(req.Task, 0) || + len(req.Instructions) > 256<<10 || !utf8.Valid(req.Instructions) || + bytes.IndexByte(req.Instructions, 0) >= 0 || + ContextContentDigest([]byte(req.Task)) != e.TaskDigest || ContextContentDigest(req.Instructions) != e.InstructionsDigest || + len(req.PresetDocuments) != len(e.PresetDocuments) { + return nil, errors.New("task, instructions or preset payload does not match the envelope") + } + for _, document := range e.PresetDocuments { + index := slices.IndexFunc(req.PresetDocuments, func(payload PresetDocument) bool { + return strings.ToUpper(payload.Name) == document.Name + }) + if index < 0 || !validIDs(document.ContentRef, document.Classification) { + return nil, errors.New("invalid preset reference") + } + payload := req.PresetDocuments[index].Content + if len(payload) != document.Bytes || ContextContentDigest(payload) != document.Digest { + return nil, errors.New("preset digest or byte count changed") + } + } + if len(e.PresetDocuments) == 0 { + return bytes.Clone(req.Instructions), nil + } + seen := make(map[string]bool) + for _, document := range e.PresetDocuments { + if seen[document.Name] { + return nil, errors.New("duplicate preset reference") + } + seen[document.Name] = true + } + return compilePresetDocuments(req.Instructions, req.PresetDocuments) +} + +func contextTools(e ContextEnvelope, services ContextExecution, now time.Time) ([]MCPServer, error) { + tools := make(map[string]ContextTool, len(e.Tools)) + for _, tool := range e.Tools { + if !validIDs(tool.ID, tool.Version, tool.PolicyRef) || !validDigest(tool.CapabilityDigest) || tools[tool.ID].ID != "" { + return nil, errors.New("invalid or duplicate tool") + } + tools[tool.ID] = tool + } + provided, bindings := make(map[string]bool), make(map[string]bool) + for _, b := range e.CredentialBindings { + digest, _ := b.Digest() + if services.Broker == nil || !validIDs(b.BindingID, b.BindingVersion, b.ToolID, b.TargetEnvironment, b.Purpose) || + !validDigest(b.PolicyFingerprint) || b.MetadataDigest != digest || b.RunID != e.RunID || + tools[b.ToolID].ID == "" || bindings[b.BindingID] || provided[b.ToolID] || + len(b.AllowedOperations) == 0 || !validIDs(b.AllowedOperations...) || b.MaxRedemptions < 1 || + !b.CleanupRequired || b.IssuedAt.IsZero() || b.IssuedAt.After(now) || !b.NotAfter.After(now) { + return nil, errors.New("invalid, expired or mismatched credential binding") + } + provided[b.ToolID], bindings[b.BindingID] = true, true + } + servers := make([]MCPServer, 0, len(services.MCPServers)) + for _, server := range services.MCPServers { + digest, _ := ContextDigest(server) + if provided[server.Name] || tools[server.Name].CapabilityDigest != digest { + return nil, errors.New("MCP configuration does not match an authorized tool") + } + servers = append(servers, cloneContextServer(server)) + provided[server.Name] = true + } + if len(provided) != len(tools) { + return nil, errors.New("authorized tools lack resolved MCP endpoints") + } + return servers, nil +} + +func cloneContextServer(server MCPServer) MCPServer { + server.Args = slices.Clone(server.Args) + return server +} diff --git a/pkg/execution/context_run_test.go b/pkg/execution/context_run_test.go new file mode 100644 index 0000000..52c3988 --- /dev/null +++ b/pkg/execution/context_run_test.go @@ -0,0 +1,684 @@ +package execution + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "slices" + "strings" + "testing" + "time" +) + +const contextFixtureSession = "11111111-2222-4333-8444-555555555555" +const fixtureAPIKey = "synthetic-provider-key-8624" + +func TestContextCancellationReleasesActivatedBinding(t *testing.T) { + f := newContextFixture(t) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + broker := &fixtureBroker{failAfterActivation: cancel} + req := withFixtureBinding(t, f.request(t, "claude", "cancel"), broker) + result, err := f.clients["claude"].Run(ctx, req) + if !errors.Is(err, context.Canceled) || result.ContextReceipt.Status != "rejected" || + len(result.ContextReceipt.CredentialReceipts) != 1 || + result.ContextReceipt.CredentialReceipts[0].CleanupState != "released" || + !reflect.DeepEqual(broker.activated, broker.released) { + t.Fatalf("cancellation did not release the lease: %v %+v", err, result.ContextReceipt) + } +} + +func TestContextConcurrentRetryCannotClaimInFlightRun(t *testing.T) { + f := newContextFixture(t) + activated, finish := make(chan struct{}), make(chan struct{}) + broker := &fixtureBroker{failAfterActivation: func() { close(activated); <-finish }} + req := withFixtureBinding(t, f.request(t, "claude", "concurrent"), broker) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + type outcome struct { + result Result + err error + } + first := make(chan outcome, 1) + go func() { + result, err := f.clients["claude"].Run(ctx, req) + first <- outcome{result, err} + }() + select { + case <-activated: + case early := <-first: + t.Fatalf("run ended before activation: %v", early.err) + case <-ctx.Done(): + close(finish) + t.Fatal(ctx.Err()) + } + result, err := f.clients["claude"].Run(ctx, req) + close(finish) + done := <-first + if err == nil || result.ErrorKind != "dispatch_unknown" || + done.err != nil || done.result.ContextReceipt.Status != "completed" || + len(broker.activated) != 1 || len(broker.released) != 1 { + t.Fatalf("concurrent retry: %s %v, first: %v", result.ErrorKind, err, done.err) + } +} + +func TestContextResumeRequiresCompatibleCurrentRuntime(t *testing.T) { + for _, backend := range []string{"claude", "codex"} { + t.Run(backend, func(t *testing.T) { + f := newContextFixture(t) + req := f.request(t, backend, "original") + if backend == "codex" { + skillDir := filepath.Join(f.dir, "skill") + if err := os.Mkdir(skillDir, 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(skillDir, "SKILL.md"), []byte("exact approved skill"), 0600); err != nil { + t.Fatal(err) + } + digest, err := ContextSkillDigest(skillDir) + if err != nil { + t.Fatal(err) + } + req.Context.Envelope.Skills = []ContextSkill{{StableID: "exact", Revision: "v1", Digest: digest, MountRef: skillDir}} + req = sealContextRequest(t, req) + } + client := f.clients[backend] + first, err := client.Run(context.Background(), req) + if err != nil || first.ContextReceipt.NativeSessionRef == nil { + t.Fatalf("first dispatch: %v %s", err, first.Error) + } + if backend == "codex" { + mounted := first.ContextReceipt.MountedSkills + if len(mounted) != 1 || mounted[0].Digest != req.Context.Envelope.Skills[0].Digest || + !strings.HasPrefix(mounted[0].Path, first.EnvironmentDirectory+string(filepath.Separator)) { + t.Fatalf("skill receipt: %+v", mounted) + } + } + resume := func(id string) Request { + next := f.request(t, backend, id) + next.Task = "Continue the approved native task" + next.Context.Envelope.Skills = req.Context.Envelope.Skills + next.Context.Envelope.Runtime.NativeSessionRef = first.ContextReceipt.NativeSessionRef + return next + } + variants := map[string]func(*ContextEnvelope){ + "audience": func(e *ContextEnvelope) { e.Subject.Audience = "other" }, + "agent": func(e *ContextEnvelope) { e.Subject.AgentID = "agent-b" }, + "scope": func(e *ContextEnvelope) { e.Scope = []string{"project:write"} }, + "authorization": func(e *ContextEnvelope) { e.KnowledgeManifest.AuthorizationVersion = "grants-v2" }, + "credential": func(e *ContextEnvelope) { e.Runtime.AuthVersion = "login-v2" }, + "model": func(e *ContextEnvelope) { e.Runtime.Model = "another-model" }, + } + for change, changeEnvelope := range variants { + next := resume("changed-" + change) + changeEnvelope(&next.Context.Envelope) + r, err := client.Run(context.Background(), sealContextRequest(t, next)) + if err == nil || r.ErrorKind != "session_incompatible" || len(r.ContextReceipt.MountedRoots) != 0 { + t.Fatalf("%s allowed old session: %v %s", change, err, r.ErrorKind) + } + } + next := sealContextRequest(t, resume("resume")) + second, err := client.Run(context.Background(), next) + if err != nil || second.ContextReceipt.NativeSessionRef == nil || + first.ContextReceipt.RuntimeFingerprint != second.ContextReceipt.RuntimeFingerprint || + first.EnvironmentDirectory != second.EnvironmentDirectory || f.observe(t, backend).Resume != first.NativeSessionID { + t.Fatalf("compatible session did not resume: %v %s %+v", err, second.Error, second.ContextReceipt) + } + stale, err := client.Run(context.Background(), sealContextRequest(t, resume("stale-source"))) + if err == nil || stale.ErrorKind != "session_incompatible" { + t.Fatalf("old session source issued another continuation: %v %s", err, stale.ErrorKind) + } + }) + } +} + +func TestContextRejectsUnsupportedOrUnapprovedDispatch(t *testing.T) { + f := newContextFixture(t) + for _, tc := range []struct { + name, backend, kind string + change func(*Request) + }{ + {"unknown-capability", "claude", "unsupported_controls", func(r *Request) { r.Context.Envelope.RequiredCapabilities = []string{"future"} }}, + {"ambient-codex", "codex", "unsupported_controls", func(r *Request) { r.Context.Envelope.Runtime.Mode = RuntimeAmbient }}, + {"tool-free-codex", "codex", "unsupported_controls", func(r *Request) { r.Context.Envelope.Runtime.ToolsDisabled = true }}, + {"exact-skills-claude", "claude", "unsupported_controls", func(r *Request) { r.Context.Envelope.Skills = []ContextSkill{{}} }}, + {"root-readonly", "codex", "unsupported_controls", func(r *Request) { r.Context.Envelope.ResourceRoots[0].Access = "read-only" }}, + {"unknown-major", "claude", "context_invalid", func(r *Request) { r.Context.Envelope.SchemaVersion = "2.0" }}, + {"expired-envelope", "claude", "context_invalid", func(r *Request) { r.Context.Envelope.ExpiresAt = time.Now().Add(-time.Second) }}, + {"altered-doc", "claude", "context_invalid", func(r *Request) { r.PresetDocuments[0].Content = []byte("unapproved") }}, + } { + t.Run(tc.name, func(t *testing.T) { + req := f.request(t, tc.backend, tc.name) + tc.change(&req) + outcome, err := f.clients[tc.backend].Run(context.Background(), sealContextRequest(t, req)) + if err == nil || outcome.ErrorKind != tc.kind || len(outcome.ContextReceipt.MountedRoots) != 0 { + t.Fatalf("dispatch should fail before native launch: %s %v", outcome.ErrorKind, err) + } + if _, err := os.Stat(filepath.Join(f.dir, tc.backend+"-observed.json")); !os.IsNotExist(err) { + t.Fatal("unsupported request launched the provider") + } + }) + } + ambient := f.request(t, "claude", "explicit-ambient") + ambient.Context.Envelope.Runtime.Mode = RuntimeAmbient + ambient.Context.Envelope.RequiredCapabilities = []string{"ambient"} + outcome, err := f.clients["claude"].Run(context.Background(), sealContextRequest(t, ambient)) + if err != nil { + t.Fatalf("explicit ambient: %v %s", err, outcome.Error) + } + seen := f.observe(t, "claude") + receipt := outcome.ContextReceipt + if seen.Cwd != f.project || !seen.Ambient || receipt.Ambient == nil || receipt.Ambient.Home != seen.Home || + receipt.Ambient.NativeConfig != seen.Config || receipt.Mode != RuntimeAmbient || receipt.NativeSessionRef != nil { + t.Fatalf("wrong ambient selection or audit: %+v, %+v", receipt, seen) + } +} + +func TestContextLeaseFailsClosedAndCleansUp(t *testing.T) { + f := newContextFixture(t) + for _, tc := range []struct { + name, kind string + modify func(Request, *fixtureBroker) + activated, failed bool + }{ + {"expired", "context_invalid", func(req Request, _ *fixtureBroker) { + req.Context.Envelope.CredentialBindings[0].NotAfter = time.Now().Add(-time.Second) + }, false, false}, + {"wrong-run", "context_invalid", func(req Request, _ *fixtureBroker) { + req.Context.Envelope.CredentialBindings[0].RunID = "other-run" + }, false, false}, + {"unsafe-delivery", "unsupported_controls", func(req Request, _ *fixtureBroker) { + req.Context.Envelope.CredentialBindings[0].Delivery = "process_env" + }, false, false}, + {"partial-activation", "credential_binding", func(_ Request, b *fixtureBroker) { + b.activateErr = errors.New("broker detail must not enter receipt") + }, true, false}, + {"revoked-before-start", "context_denied", func(req Request, b *fixtureBroker) { + allowed := true + req.Context.Authorize = func(context.Context, ContextEnvelope, *TaskCheckpoint) error { + if !allowed { + return errors.New("revoked") + } + return nil + } + b.failAfterActivation = func() { allowed = false } + }, true, false}, + {"release-failed", "credential_binding", func(_ Request, b *fixtureBroker) { + b.activateErr, b.releaseErr = errors.New("partial"), errors.New("broker detail must not enter receipt") + }, true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + b := &fixtureBroker{} + req := withFixtureBinding(t, f.request(t, "codex", tc.name), b) + tc.modify(req, b) + result, err := f.clients["codex"].Run(context.Background(), sealContextRequest(t, req)) + if err == nil || result.ErrorKind != tc.kind || len(result.ContextReceipt.MountedRoots) != 0 || + (len(b.activated) != 0) != tc.activated || !reflect.DeepEqual(b.activated, b.released) { + t.Fatalf("failed binding: %s %v %+v", result.ErrorKind, err, result.ContextReceipt) + } + if tc.activated { + receipt := result.ContextReceipt.CredentialReceipts[0] + if (receipt.CleanupState == "failed") != tc.failed { + t.Fatalf("unexpected cleanup state: %+v", receipt) + } + } + if _, err := os.Stat(filepath.Join(f.dir, "codex-observed.json")); !os.IsNotExist(err) { + t.Fatal("failed authorization or lease launched the provider") + } + }) + } +} + +func TestContextUnknownAndConflictingDispatchDoNotReplay(t *testing.T) { + f := newContextFixture(t) + req := f.request(t, "codex", "unknown") + req.Task = "simulate unknown" + req = sealContextRequest(t, req) + first, err := f.clients["codex"].Run(context.Background(), req) + if err == nil || first.ContextReceipt.Status != "unknown" || first.ContextReceipt.NativeSessionRef != nil { + t.Fatalf("failed provider was treated as completed: %v %+v", err, first.ContextReceipt) + } + seenPath := filepath.Join(f.dir, "codex-observed.json") + if err := os.Remove(seenPath); err != nil { + t.Fatal(err) + } + retry, err := f.clients["codex"].Run(context.Background(), req) + if err == nil || retry.ErrorKind != "dispatch_already_recorded" || !reflect.DeepEqual(first.ContextReceipt, retry.ContextReceipt) { + t.Fatalf("unknown outcome was lost or replayed: %v %+v", err, retry.ContextReceipt) + } + req.Task = "unapproved substitution" + conflict, err := f.clients["codex"].Run(context.Background(), sealContextRequest(t, req)) + if err == nil || conflict.ErrorKind != "idempotency_conflict" { + t.Fatalf("modified envelope bypassed idempotency: %v %+v", err, conflict.ContextReceipt) + } + req.Context.Envelope.IdempotencyKey = "second-key" + conflict, err = f.clients["codex"].Run(context.Background(), sealContextRequest(t, req)) + if err == nil || conflict.ErrorKind != "idempotency_conflict" { + t.Fatalf("second key reused an existing Run: %v %+v", err, conflict.ContextReceipt) + } + req = f.request(t, "codex", "crash") + e := req.Context.Envelope + if err := f.store.claim(e, f.store.entry(e.TenantID, e.TaskID, e.IdempotencyKey)); err != nil { + t.Fatal(err) + } + reopened, err := OpenContextStore(f.store.root) + if err != nil { + t.Fatal(err) + } + req.Context.Store = reopened + crash, err := f.clients["codex"].Run(context.Background(), req) + if err == nil || crash.ErrorKind != "dispatch_unknown" || crash.ContextReceipt.Status != "unknown" { + t.Fatalf("interrupted dispatch was retried: %v %+v", err, crash.ContextReceipt) + } + if _, err := os.Stat(seenPath); !os.IsNotExist(err) { + t.Fatal("unexpected repeated native dispatch") + } +} + +func TestContextEnvelopeMinorExtensionsArePreserved(t *testing.T) { + f := newContextFixture(t) + req := f.request(t, "claude", "minor-version") + req.Context.Envelope.SchemaVersion = "1.2" + req.Context.Envelope.Extensions = map[string]json.RawMessage{"optional": json.RawMessage(`{"sequence":9007199254740993}`)} + req = sealContextRequest(t, req) + e := req.Context.Envelope + snapshot, err := snapshotEnvelope(e) + if err != nil || !reflect.DeepEqual(e.Extensions, snapshot.Extensions) { + t.Fatalf("lost extension: %v", err) + } + digest, err := snapshot.Digest() + if err != nil || digest != e.EnvelopeDigest { + t.Fatalf("extension changed digest: %v", err) + } +} + +type contextFixture struct { + store *ContextStore + project, resource, dir string + clients map[string]*Client + bins map[string]string +} + +func newContextFixture(t *testing.T) contextFixture { + t.Helper() + dir, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + f := contextFixture{dir: dir, project: filepath.Join(dir, "project"), resource: filepath.Join(dir, "resource"), + clients: make(map[string]*Client), bins: make(map[string]string)} + for _, path := range []string{f.project, f.resource, filepath.Join(dir, "journal"), filepath.Join(dir, "ambient"), filepath.Join(dir, "config")} { + if err := os.Mkdir(path, 0700); err != nil { + t.Fatal(err) + } + } + f.store, err = OpenContextStore(filepath.Join(dir, "journal")) + if err != nil { + t.Fatal(err) + } + t.Setenv("HOME", filepath.Join(dir, "ambient")) + t.Setenv("CLAUDE_CONFIG_DIR", filepath.Join(dir, "ambient")) + t.Setenv("CODEX_HOME", filepath.Join(dir, "ambient")) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config")) + t.Setenv("OFFLOAD_MAX_WORKERS", "-1") + t.Setenv("TEST_AMBIENT", "ambient-marker") + if err := os.WriteFile(filepath.Join(dir, "ambient", "auth.json"), []byte("ambient login must not be copied"), 0600); err != nil { + t.Fatal(err) + } + gateway := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + t.Cleanup(gateway.Close) + for _, backend := range []string{"claude", "codex"} { + profile := Profile{Backend: backend, Model: "fixture"} + if backend == "claude" { + profile.Token, profile.BaseURL = "synthetic-gateway-token", gateway.URL + } + client, err := New(Config{ProfileName: backend + "-fixture", Profile: profile}) + if err != nil { + t.Fatal(err) + } + f.clients[backend] = client + f.bins[backend] = filepath.Join(dir, backend) + script := fmt.Sprintf("#!/bin/sh\nexec %s -test.run '^TestContextHarnessHelper$' -- %s %s \"$@\"\n", shellFixtureArg(os.Args[0]), backend, shellFixtureArg(dir)) + if err := os.WriteFile(f.bins[backend], []byte(script), 0700); err != nil { + t.Fatal(err) + } + } + return f +} + +func shellFixtureArg(value string) string { + return "'" + strings.ReplaceAll(value, "'", "'\"'\"'") + "'" +} + +func (f contextFixture) request(t *testing.T, backend, id string) Request { + t.Helper() + executable, err := os.ReadFile(f.bins[backend]) + if err != nil { + t.Fatal(err) + } + timeout := 10 * time.Second + req := Request{Task: "Do the confirmed task", Instructions: []byte("Authorized instructions"), + PresetDocuments: []PresetDocument{{Name: "MEMORY.md", Content: []byte("Authorized projection")}}, Timeout: &timeout} + req.Context = &ContextExecution{Store: f.store, Authorize: func(context.Context, ContextEnvelope, *TaskCheckpoint) error { return nil }} + if backend == "codex" { + req.Context.CodexAPIKey = fixtureAPIKey + } + now := time.Now().UTC() + req.Context.Envelope = ContextEnvelope{ + SchemaVersion: ContextSchemaVersion, EnvelopeID: "envelope-" + id, TenantID: "tenant", TaskID: "shared", Caller: "agh", + RunID: "run-" + id, IdempotencyKey: "dispatch-" + id, CreatedAt: now, ExpiresAt: now.Add(time.Minute), + Subject: ContextSubject{UserID: "owner", AgentID: "agent-a", Audience: "private"}, Scope: []string{"project:read"}, + Project: ContextProject{PrimaryID: "project", WorkspaceRef: f.project, Revision: "revision"}, + Runtime: ContextRuntime{Adapter: backend, Profile: backend + "-fixture", AuthVersion: "provider-v1", + PermissionMode: "bypassPermissions", Executable: f.bins[backend], ExecutableDigest: ContextContentDigest(executable)}, + ResourceRoots: []ContextRoot{{ID: "resource", PathRef: f.resource, Access: "workspace"}}, + KnowledgeManifest: KnowledgeManifest{GenerationID: "generation", NoteSnapshotVersion: "snapshot", + AuthorizationVersion: "grants-v1", Digest: ContextContentDigest([]byte("manifest"))}, + PresetDocuments: []ContextDocument{{Name: "MEMORY.MD", ContentRef: "projection-id", Classification: "private", + Digest: ContextContentDigest(req.PresetDocuments[0].Content), Bytes: len(req.PresetDocuments[0].Content)}}, + } + return sealContextRequest(t, req) +} + +func sealContextRequest(t *testing.T, req Request) Request { + t.Helper() + e := &req.Context.Envelope + e.TaskDigest, e.InstructionsDigest = ContextContentDigest([]byte(req.Task)), ContextContentDigest(req.Instructions) + for i := range e.CredentialBindings { + var err error + e.CredentialBindings[i].MetadataDigest, err = e.CredentialBindings[i].Digest() + if err != nil { + t.Fatal(err) + } + } + var err error + e.EnvelopeDigest, err = e.Digest() + if err != nil { + t.Fatal(err) + } + return req +} + +type fixtureBroker struct { + activated, released []CredentialBinding + activateErr, releaseErr error + failAfterActivation func() +} + +func (b *fixtureBroker) Activate(_ context.Context, binding CredentialBinding) (MCPServer, error) { + b.activated = append(b.activated, binding) + if b.failAfterActivation != nil { + b.failAfterActivation() + } + return MCPServer{Name: binding.ToolID, Command: "/bin/echo", Args: []string{"opaque-binding", binding.BindingID, binding.RunID}}, b.activateErr +} + +func (b *fixtureBroker) Release(ctx context.Context, binding CredentialBinding) (LeaseOutcome, error) { + b.released = append(b.released, binding) + if ctx.Err() != nil { + return LeaseOutcome{}, ctx.Err() + } + return LeaseOutcome{State: "revoked"}, b.releaseErr +} + +func withFixtureBinding(t *testing.T, req Request, broker *fixtureBroker) Request { + t.Helper() + req.Context.Broker = broker + e := &req.Context.Envelope + e.Tools = []ContextTool{{ID: "fixture_tool", Version: "v1", PolicyRef: "policy", CapabilityDigest: ContextContentDigest([]byte("tool-capabilities"))}} + e.CredentialBindings = []CredentialBinding{{ + BindingID: "binding-" + e.RunID, BindingVersion: "v1", PolicyFingerprint: ContextContentDigest([]byte("tool-policy")), + ToolID: "fixture_tool", TargetEnvironment: "fixture", Purpose: "observe", RunID: e.RunID, + Delivery: "mcp", AllowedOperations: []string{"inspect"}, IssuedAt: e.CreatedAt, NotAfter: e.ExpiresAt, + MaxRedemptions: 1, CleanupRequired: true, + }} + return sealContextRequest(t, req) +} + +type contextFixtureObservation struct { + Cwd, Home, Config, Task, Instructions, Resume string + Ambient, AmbientAuthCopied, AmbientInstructions, ExplicitProviderAuth bool + Roots, TurnRoots []string + Tools json.RawMessage +} + +func (f contextFixture) observe(t *testing.T, backend string) contextFixtureObservation { + t.Helper() + raw, err := os.ReadFile(filepath.Join(f.dir, backend+"-observed.json")) + if err != nil { + t.Fatal(err) + } + var seen contextFixtureObservation + if err := json.Unmarshal(raw, &seen); err != nil { + t.Fatal(err) + } + return seen +} + +func TestContextDispatchHandoffAndLeaseReceipt(t *testing.T) { + f := newContextFixture(t) + claudeBroker := &fixtureBroker{} + claudeReq := withFixtureBinding(t, f.request(t, "claude", "produce"), claudeBroker) + first, err := f.clients["claude"].Run(context.Background(), claudeReq) + if err != nil { + t.Fatalf("Claude: %v, %s, %s", err, first.Error, first.NativeStderr) + } + firstSeen := f.observe(t, "claude") + checkFixtureDispatch(t, f, claudeReq, first, firstSeen, claudeBroker) + firstEnv := claudeReq.Context.Envelope + source := SourceRun{firstEnv.TenantID, firstEnv.TaskID, firstEnv.RunID, firstEnv.IdempotencyKey} + checkpoint := TaskCheckpoint{ + SchemaVersion: ContextSchemaVersion, CheckpointID: "checkpoint", TenantID: source.TenantID, + TaskID: source.TaskID, RunID: source.RunID, ProducerAgentID: firstEnv.Subject.AgentID, Audience: firstEnv.Subject.Audience, + ProjectID: firstEnv.Project.PrimaryID, EnvelopeDigest: firstEnv.EnvelopeDigest, + AuthorizationVersion: firstEnv.KnowledgeManifest.AuthorizationVersion, + CompletedSteps: []ConfirmedStep{{ID: "confirmed", EvidenceRef: "evidence-1"}}, PendingSteps: []string{"unknown"}, + ArtifactRefs: []string{"artifact-1"}, CreatedAt: time.Now().UTC(), ExpiresAt: time.Now().Add(time.Minute).UTC(), + } + ref, err := f.store.SaveCheckpoint(source, checkpoint) + if err != nil { + t.Fatal(err) + } + if again, err := f.store.SaveCheckpoint(source, checkpoint); err != nil || again != ref { + t.Fatalf("checkpoint retry: %v %v", again, err) + } + var allowed bool + checks := 0 + codexBroker := &fixtureBroker{} + codexReq := withFixtureBinding(t, f.request(t, "codex", "consume"), codexBroker) + e := &codexReq.Context.Envelope + e.CheckpointRef, e.Subject.AgentID, e.Subject.Audience = &ref, "agent-b", "shared-review" + e.KnowledgeManifest.AuthorizationVersion = "grants-v2" + e.Scope = []string{"project:review"} + codexReq.Task = "Continue independently using artifact-1" + codexReq.Context.Authorize = func(_ context.Context, envelope ContextEnvelope, cp *TaskCheckpoint) error { + checks++ + if cp == nil || !reflect.DeepEqual(cp, &checkpoint) || envelope.Subject.AgentID != "agent-b" || + envelope.KnowledgeManifest.AuthorizationVersion != "grants-v2" || !allowed { + return errors.New("references are not authorized for this recipient") + } + return nil + } + codexReq = sealContextRequest(t, codexReq) + rejected, err := f.clients["codex"].Run(context.Background(), codexReq) + if err == nil || rejected.ErrorKind != "context_denied" || len(codexBroker.activated) != 0 { + t.Fatalf("unauthorized handoff: %+v %v", rejected, err) + } + allowed = true + second, err := f.clients["codex"].Run(context.Background(), codexReq) + if err != nil { + t.Fatalf("Codex: %v, %s, %s", err, second.Error, second.NativeStderr) + } + secondSeen := f.observe(t, "codex") + checkFixtureDispatch(t, f, codexReq, second, secondSeen, codexBroker) + if !slices.Equal(secondSeen.TurnRoots, append([]string{secondSeen.Cwd}, firstSeen.Roots...)) || + firstSeen.Instructions != secondSeen.Instructions || secondSeen.Resume != "" || + firstSeen.Home == secondSeen.Home || checks != 3 || second.ContextReceipt.CheckpointRef == nil { + t.Fatalf("handoff did not start a fresh Codex thread: %+v, checks=%d", secondSeen, checks) + } + retry, err := f.clients["codex"].Run(context.Background(), codexReq) + if err == nil || retry.ErrorKind != "dispatch_already_recorded" || !reflect.DeepEqual(retry.ContextReceipt, second.ContextReceipt) || len(codexBroker.activated) != 1 { + t.Fatalf("retry re-executed or lost receipt: %s %v", retry.ErrorKind, err) + } + allowed = false + retry, err = f.clients["codex"].Run(context.Background(), codexReq) + if err == nil || retry.ErrorKind != "context_denied" || retry.ContextReceipt.AcceptedEnvelopeDigest != "" { + t.Fatal("revoked recipient retrieved cached dispatch") + } +} + +func checkFixtureDispatch(t *testing.T, f contextFixture, req Request, result Result, seen contextFixtureObservation, broker *fixtureBroker) { + t.Helper() + receipt := result.ContextReceipt + e := req.Context.Envelope + if receipt == nil || receipt.Status != "completed" || receipt.AcceptedEnvelopeDigest != e.EnvelopeDigest || + receipt.KnowledgeManifest == nil || *receipt.KnowledgeManifest != e.KnowledgeManifest || receipt.Workspace != seen.Cwd || + seen.Cwd != filepath.Join(result.EnvironmentDirectory, "workspace") || seen.Home != filepath.Join(result.EnvironmentDirectory, "home") || + !slices.Equal(seen.Roots, []string{f.project, f.resource}) || seen.Ambient || seen.AmbientAuthCopied || seen.AmbientInstructions || + !seen.ExplicitProviderAuth || !slices.Equal(receipt.InjectedDocuments, []InjectedDocument{{Name: e.PresetDocuments[0].Name, Digest: e.PresetDocuments[0].Digest, Bytes: e.PresetDocuments[0].Bytes}}) || + receipt.InstructionsBytes != len(seen.Instructions) || ContextContentDigest([]byte(seen.Instructions)) != receipt.InstructionsDigest || + !strings.Contains(seen.Instructions, "Authorized instructions") || !strings.Contains(seen.Instructions, "Authorized projection") || + seen.Task != req.Task || !strings.Contains(string(seen.Tools), e.CredentialBindings[0].BindingID) || + !strings.Contains(string(seen.Tools), e.RunID) || len(receipt.MountedRoots) != 2 || + len(receipt.CredentialReceipts) != 1 || receipt.CredentialReceipts[0].CleanupState != "released" || + receipt.CredentialReceipts[0].LeaseState != "revoked" || len(broker.activated) != 1 || + !reflect.DeepEqual(broker.activated, broker.released) || broker.activated[0].RunID != e.RunID { + t.Fatalf("dispatch evidence does not match: %+v, %+v", receipt, seen) + } + raw, err := json.Marshal(result) + if err != nil || bytes.Contains(raw, []byte(fixtureAPIKey)) || bytes.Contains(raw, []byte("synthetic-gateway-token")) { + t.Fatal("provider credential entered the result") + } +} + +// Invoked by the fake CLI wrappers in an isolated child process. +func TestContextHarnessHelper(t *testing.T) { + split := slices.Index(os.Args, "--") + if split < 0 { + return + } + args := os.Args[split+1:] + backend, output := args[0], filepath.Join(args[1], args[0]+"-observed.json") + cwd, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + seen := contextFixtureObservation{Cwd: cwd, Home: os.Getenv("HOME"), Ambient: os.Getenv("TEST_AMBIENT") != ""} + if backend == "claude" { + seen.Config = os.Getenv("CLAUDE_CONFIG_DIR") + seen.AmbientInstructions = os.Getenv("CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD") != "" + seen.ExplicitProviderAuth = os.Getenv("ANTHROPIC_AUTH_TOKEN") == "synthetic-gateway-token" + for i, arg := range args[2:] { + switch arg { + case "--add-dir": + seen.Roots = append(seen.Roots, args[i+3]) + case "--append-system-prompt-file": + raw, err := os.ReadFile(args[i+3]) + if err != nil { + t.Fatal(err) + } + seen.Instructions = string(raw) + case "--resume": + seen.Resume = args[i+3] + case "--mcp-config": + seen.Tools = json.RawMessage(args[i+3]) + } + } + raw, _ := io.ReadAll(os.Stdin) + seen.Task = string(raw) + saveFixtureObservation(t, output, seen) + fmt.Printf("{\"type\":\"result\",\"subtype\":\"success\",\"session_id\":%q,\"result\":\"fixture done\"}\n", contextFixtureSession) + os.Exit(0) + } + seen.Config = os.Getenv("CODEX_HOME") + _, err = os.Stat(filepath.Join(seen.Config, "auth.json")) + seen.AmbientAuthCopied = !os.IsNotExist(err) + seen.ExplicitProviderAuth = os.Getenv("OPENAI_API_KEY") == fixtureAPIKey + fakeContextCodex(t, output, seen) + os.Exit(0) +} + +func saveFixtureObservation(t *testing.T, output string, seen contextFixtureObservation) { + t.Helper() + raw, err := json.Marshal(seen) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(output, raw, 0600); err != nil { + t.Fatal(err) + } +} + +func fakeContextCodex(t *testing.T, output string, seen contextFixtureObservation) { + t.Helper() + scanner := bufio.NewScanner(os.Stdin) + var selected []string + for scanner.Scan() { + var frame struct { + ID json.RawMessage + Method string + Params struct { + Cwd, DeveloperInstructions, ThreadID string + RuntimeWorkspaceRoots, ExtraRoots []string + Config map[string]json.RawMessage + Input []struct{ Text string } + } + } + if err := json.Unmarshal(scanner.Bytes(), &frame); err != nil { + t.Fatal(err) + } + respond := func(value any) { + _ = json.NewEncoder(os.Stdout).Encode(map[string]any{"id": frame.ID, "result": value}) + } + p := frame.Params + switch frame.Method { + case "initialized": + continue + case "skills/extraRoots/set": + selected = p.ExtraRoots + respond(struct{}{}) + case "skills/list": + skills := make([]map[string]any, 0, len(selected)) + for _, root := range selected { + skills = append(skills, map[string]any{"path": filepath.Join(root, "SKILL.md"), "enabled": true, "pluginId": nil}) + } + respond(map[string]any{"data": []any{map[string]any{"errors": []any{}, "skills": skills}}}) + case "skills/config/write": + respond(map[string]bool{"effectiveEnabled": true}) + case "thread/start", "thread/resume": + seen.Roots, seen.Instructions, seen.Resume = p.RuntimeWorkspaceRoots[1:], p.DeveloperInstructions, p.ThreadID + seen.AmbientInstructions = string(p.Config["project_doc_max_bytes"]) != "0" || p.Cwd != seen.Cwd + seen.Tools = p.Config["mcp_servers"] + respond(map[string]any{"thread": map[string]string{"id": contextFixtureSession}}) + case "turn/start": + seen.Task, seen.TurnRoots = p.Input[0].Text, p.RuntimeWorkspaceRoots + saveFixtureObservation(t, output, seen) + fixtureSessionDir := filepath.Join(seen.Config, "sessions") + if err := os.MkdirAll(fixtureSessionDir, 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(fixtureSessionDir, "rollout-"+contextFixtureSession+".jsonl"), nil, 0600); err != nil { + t.Fatal(err) + } + respond(map[string]any{"turn": map[string]string{"id": "turn"}}) + fmt.Printf("{\"method\":\"turn/started\",\"params\":{\"threadId\":%q,\"turn\":{\"id\":\"turn\"}}}\n", contextFixtureSession) + if seen.Task == "simulate unknown" { + return + } + fmt.Printf("{\"method\":\"turn/completed\",\"params\":{\"threadId\":%q,\"turn\":{\"id\":\"turn\",\"status\":\"completed\",\"items\":[{\"type\":\"agentMessage\",\"text\":%q}]}}}\n", + contextFixtureSession, "fixture done "+fixtureAPIKey) + return + default: + respond(struct{}{}) + } + } +} diff --git a/pkg/execution/context_skills.go b/pkg/execution/context_skills.go new file mode 100644 index 0000000..f68ff52 --- /dev/null +++ b/pkg/execution/context_skills.go @@ -0,0 +1,135 @@ +package execution + +import ( + "errors" + "io" + "io/fs" + "os" + "path/filepath" +) + +const maxSkillBytes = 16 << 20 +const maxSkillEntries = 1024 + +type skillEntry struct { + Path, Digest string + Executable bool + Directory bool +} + +// ContextSkillDigest hashes a regular-file Skill tree with relative portable +// paths. Symlinks, special files and trees above the snapshot limits fail. +func ContextSkillDigest(root string) (string, error) { + return snapshotSkill(root, "") +} + +func validateContextSkills(skills []ContextSkill) error { + ids, paths := make(map[string]bool), make(map[string]bool) + for _, skill := range skills { + if !validIDs(skill.StableID, skill.Revision) || !validDigest(skill.Digest) || + ids[skill.StableID] || paths[skill.MountRef] || !contextDirectory(skill.MountRef) { + return errors.New("invalid or duplicate Skill snapshot") + } + ids[skill.StableID], paths[skill.MountRef] = true, true + } + return nil +} + +func stageContextSkills(skills []ContextSkill, environment string, resume bool) ([]string, error) { + roots := make([]string, 0, len(skills)) + for index, skill := range skills { + // Derive filesystem names instead of using caller-provided identifiers. + folder, _ := ContextDigest([]any{index, skill.StableID}) + destination := filepath.Join(environment, "skills", folder) + var digest string + var err error + if resume { + digest, err = snapshotSkill(destination, "") + } else { + digest, err = snapshotSkill(skill.MountRef, destination) + } + if err != nil || digest != skill.Digest { + return nil, errors.New("Skill snapshot digest does not match") + } + roots = append(roots, destination) + } + return roots, nil +} + +func snapshotSkill(root, destination string) (string, error) { + marker, err := os.Lstat(filepath.Join(root, "SKILL.md")) + if err != nil || !marker.Mode().IsRegular() || !contextDirectory(root) { + return "", errors.New("Skill snapshot must have its own regular SKILL.md") + } + if destination != "" { + if err := os.MkdirAll(destination, 0700); err != nil { + return "", err + } + } + var entries []skillEntry + var size int64 + err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil || path == root { + return err + } + rel, err := filepath.Rel(root, path) + if err != nil || len(entries) >= maxSkillEntries { + return errors.New("Skill snapshot exceeds path limits") + } + entry := skillEntry{Path: filepath.ToSlash(rel), Directory: d.IsDir()} + target := "" + if destination != "" { + target = filepath.Join(destination, rel) + } + if d.IsDir() { + if target != "" { + if err := os.Mkdir(target, 0700); err != nil { + return err + } + } + } else { + info, err := d.Info() + if err != nil || !info.Mode().IsRegular() || info.Size() > maxSkillBytes-size { + return errors.New("Skill snapshot must contain bounded regular files") + } + data, err := readSkillFile(path, info, maxSkillBytes-size) + if err != nil { + return err + } + size += int64(len(data)) + entry.Digest, entry.Executable = ContextContentDigest(data), info.Mode().Perm()&0111 != 0 + if target != "" { + mode := os.FileMode(0600) + if entry.Executable { + mode = 0700 + } + if err := os.WriteFile(target, data, mode); err != nil { + return err + } + } + } + entries = append(entries, entry) + return nil + }) + if err != nil { + return "", err + } + return ContextDigest(entries) +} + +func readSkillFile(path string, expected fs.FileInfo, limit int64) ([]byte, error) { + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer file.Close() + info, err := file.Stat() + if err != nil || !os.SameFile(expected, info) { + return nil, errors.New("Skill file changed while opening") + } + data, err := io.ReadAll(io.LimitReader(file, limit+1)) + if err != nil || int64(len(data)) > limit { + return nil, errors.New("Skill snapshot exceeds byte limit") + } + return data, nil +} diff --git a/pkg/execution/context_store.go b/pkg/execution/context_store.go new file mode 100644 index 0000000..cda3482 --- /dev/null +++ b/pkg/execution/context_store.go @@ -0,0 +1,249 @@ +package execution + +import ( + "encoding/json" + "errors" + "io" + "os" + "path/filepath" + "time" +) + +// ContextStore is an owner-private local journal. Its entries contain receipts, +// reference-only checkpoints and clean native runtime state. Share a store +// between client processes that dispatch the same task. Retention belongs to +// the caller, including removal of any expired native runtime directories. +type ContextStore struct { + root string +} + +func OpenContextStore(root string) (*ContextStore, error) { + canonical, err := filepath.EvalSymlinks(root) + if err != nil || !filepath.IsAbs(root) || canonical != root { + return nil, errors.New("context store requires a canonical absolute directory") + } + info, err := os.Lstat(root) + if err != nil || !info.IsDir() || info.Mode().Perm()&0077 != 0 { + return nil, errors.New("context store directory must be private") + } + return &ContextStore{root: root}, nil +} + +type CheckpointRef struct { + ID string `json:"id"` + Digest string `json:"digest"` +} + +type ConfirmedStep struct { + ID string `json:"id"` + EvidenceRef string `json:"evidence_ref"` +} + +// TaskCheckpoint contains caller-confirmed facts only as references. Pending +// steps include uncertain outcomes; native output cannot complete a step. +type TaskCheckpoint struct { + SchemaVersion string `json:"schema_version"` + CheckpointID string `json:"checkpoint_id"` + TenantID string `json:"tenant_id"` + TaskID string `json:"task_id"` + RunID string `json:"run_id"` + ProducerAgentID string `json:"producer_agent_id"` + Audience string `json:"audience"` + ProjectID string `json:"project_id"` + EnvelopeDigest string `json:"envelope_digest"` + AuthorizationVersion string `json:"authorization_version"` + CompletedSteps []ConfirmedStep `json:"completed_steps,omitempty"` + PendingSteps []string `json:"pending_steps,omitempty"` + ArtifactRefs []string `json:"artifact_refs,omitempty"` + EvidenceRefs []string `json:"evidence_refs,omitempty"` + ToolResultRefs []string `json:"tool_result_refs,omitempty"` + IdempotencyState []string `json:"idempotency_state,omitempty"` + CreatedAt time.Time `json:"created_at"` + ExpiresAt time.Time `json:"expires_at"` +} + +// SaveCheckpoint publishes caller-confirmed references against a finished +// dispatch. Repeating the exact write returns the same reference. No data from +// the provider report or native transcript is promoted by this method. +func (s *ContextStore) SaveCheckpoint(source SourceRun, checkpoint TaskCheckpoint) (CheckpointRef, error) { + var empty CheckpointRef + entry := s.entry(source.TenantID, source.TaskID, source.IdempotencyKey) + var claim contextClaim + var done contextCompletion + if err := readContextFile(filepath.Join(entry, "claim.json"), &claim); err != nil { + return empty, errors.New("checkpoint source is missing") + } + if err := readContextFile(filepath.Join(entry, "receipt.json"), &done); err != nil || done.Receipt.AcceptedEnvelopeDigest == "" { + return empty, errors.New("checkpoint source has no accepted execution receipt") + } + if !validContextVersion(checkpoint.SchemaVersion) || !validIDs(checkpoint.CheckpointID, source.RunID) || + checkpoint.TenantID != source.TenantID || checkpoint.TaskID != source.TaskID || + checkpoint.RunID != source.RunID || source.RunID != claim.RunID || + checkpoint.ProducerAgentID != claim.AgentID || checkpoint.Audience != claim.Audience || + checkpoint.ProjectID != claim.ProjectID || checkpoint.EnvelopeDigest != claim.EnvelopeDigest || + checkpoint.AuthorizationVersion != claim.AuthorizationVersion || + checkpoint.CreatedAt.Before(done.Receipt.CompletedAt) || checkpoint.CreatedAt.After(time.Now()) || + !checkpoint.ExpiresAt.After(checkpoint.CreatedAt) { + return empty, errors.New("checkpoint provenance or lifetime does not match its source") + } + if err := validateCheckpointRefs(checkpoint); err != nil { + return empty, err + } + digest, err := ContextDigest(checkpoint) + if err != nil { + return empty, err + } + path := s.checkpointPath(source.TenantID, source.TaskID, checkpoint.CheckpointID) + if err := publishContextFile(path, checkpoint); errors.Is(err, os.ErrExist) { + existing, readErr := s.loadCheckpoint(source.TenantID, source.TaskID, CheckpointRef{checkpoint.CheckpointID, digest}) + if readErr != nil || existing == nil { + return empty, errors.New("checkpoint ID already holds different content") + } + } else if err != nil { + return empty, err + } + return CheckpointRef{checkpoint.CheckpointID, digest}, nil +} + +type SourceRun struct { + TenantID, TaskID, RunID, IdempotencyKey string +} + +func validateCheckpointRefs(cp TaskCheckpoint) error { + seen := make(map[string]bool) + for _, step := range cp.CompletedSteps { + if !validIDs(step.ID, step.EvidenceRef) || seen[step.ID] { + return errors.New("invalid or duplicate confirmed checkpoint step") + } + seen[step.ID] = true + } + for _, id := range cp.PendingSteps { + if !validIDs(id) || seen[id] { + return errors.New("invalid or duplicate pending checkpoint step") + } + seen[id] = true + } + for _, refs := range [][]string{cp.ArtifactRefs, cp.EvidenceRefs, cp.ToolResultRefs, cp.IdempotencyState} { + if !validIDs(refs...) { + return errors.New("invalid checkpoint reference") + } + } + return nil +} + +func (s *ContextStore) loadCheckpoint(tenant, task string, ref CheckpointRef) (*TaskCheckpoint, error) { + var cp TaskCheckpoint + if err := readContextFile(s.checkpointPath(tenant, task, ref.ID), &cp); err != nil { + return nil, err + } + digest, err := ContextDigest(cp) + if err != nil || digest != ref.Digest || cp.TenantID != tenant || cp.TaskID != task || cp.CheckpointID != ref.ID { + return nil, errors.New("checkpoint content changed") + } + return &cp, nil +} + +type contextClaim struct { + RunID, EnvelopeDigest, AgentID, Audience, ProjectID, AuthorizationVersion string +} + +type contextCompletion struct { + Receipt ContextReceipt + Environment string +} + +var errRunClaimed = errors.New("run ID already has a dispatch claim") + +func (s *ContextStore) entry(tenant, task, key string) string { + digest, _ := ContextDigest([]string{tenant, task, key}) + return filepath.Join(s.root, "dispatch-"+digest) +} + +func (s *ContextStore) checkpointPath(tenant, task, id string) string { + digest, _ := ContextDigest([]string{tenant, task, id}) + return filepath.Join(s.root, "checkpoint-"+digest+".json") +} + +// claim is exclusive across processes. A missing terminal receipt after an +// interruption means the outcome is unknown and must never be replayed. +func (s *ContextStore) claim(e ContextEnvelope, entry string) error { + if err := os.Mkdir(entry, 0700); err != nil { + return err + } + runDigest, _ := ContextDigest([]string{e.TenantID, e.RunID}) + if err := publishContextFile(filepath.Join(s.root, "run-"+runDigest+".json"), e.EnvelopeDigest); err != nil { + if errors.Is(err, os.ErrExist) { + _ = os.Remove(entry) + return errRunClaimed + } + return err + } + return publishContextFile(filepath.Join(entry, "claim.json"), contextClaim{ + RunID: e.RunID, EnvelopeDigest: e.EnvelopeDigest, AgentID: e.Subject.AgentID, + Audience: e.Subject.Audience, ProjectID: e.Project.PrimaryID, + AuthorizationVersion: e.KnowledgeManifest.AuthorizationVersion, + }) +} + +const contextFileLimit = 1 << 20 + +func publishContextFile(path string, value any) error { + raw, err := json.Marshal(value) + if err != nil || len(raw) > contextFileLimit { + return errors.New("context journal record exceeds encoding limits") + } + file, err := os.CreateTemp(filepath.Dir(path), ".record-") + if err != nil { + return err + } + defer os.Remove(file.Name()) + _, writeErr := file.Write(raw) + if writeErr == nil { + writeErr = file.Sync() + } + if err := errors.Join(writeErr, file.Close()); err != nil { + return err + } + if err := os.Link(file.Name(), path); err != nil { + return err + } + dir, err := os.Open(filepath.Dir(path)) + if err != nil { + return err + } + defer dir.Close() + return dir.Sync() +} + +func readContextFile(path string, dest any) error { + info, err := os.Lstat(path) + if err != nil { + return err + } + if !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 || info.Size() > contextFileLimit { + return errors.New("invalid context journal file") + } + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + actual, err := file.Stat() + if err != nil || !os.SameFile(info, actual) { + return errors.New("context journal file changed") + } + raw, err := io.ReadAll(io.LimitReader(file, contextFileLimit+1)) + if err != nil || len(raw) > contextFileLimit { + return errors.New("cannot read context journal file") + } + return json.Unmarshal(raw, dest) +} + +func validIDs(ids ...string) bool { + for _, id := range ids { + if !runIDPattern.MatchString(id) { + return false + } + } + return true +} diff --git a/pkg/execution/execution.go b/pkg/execution/execution.go index 6b5b7b4..6ab82ed 100644 --- a/pkg/execution/execution.go +++ b/pkg/execution/execution.go @@ -87,6 +87,8 @@ type ProcessEnvironment struct { type RunEvent = runevents.Event type Request struct { + // Context opts into AGH's versioned execution contract. + Context *ContextExecution `json:"context,omitempty"` // ProcessEnvironment optionally changes this run's child environment only. // Nil leaves the environment unchanged. ProcessEnvironment *ProcessEnvironment @@ -134,6 +136,7 @@ type Request struct { // Result is execution evidence, never task acceptance. Missing usage/cost stays // nil. RawRecord preserves the complete private CLI/history-compatible record. type Result struct { + ContextReceipt *ContextReceipt `json:"context_receipt,omitempty"` EnvironmentDirectory string MonitorError error NativeStderr string @@ -228,7 +231,14 @@ func LoadConfig(path, name string) (Config, error) { // Run owns one native invocation until cleanup completes. No Offload CLI is // launched. History is appended only when explicitly requested. Raw events are ordered; // observer errors stop this invocation. There are no retries/profile fallbacks. -func (c *Client) Run(ctx context.Context, req Request) (result Result, resultErr error) { +func (c *Client) Run(ctx context.Context, req Request) (Result, error) { + if req.Context != nil { + return c.runContext(ctx, req) + } + return c.run(ctx, req, nil) +} + +func (c *Client) run(ctx context.Context, req Request, managed *activeContextRun) (result Result, resultErr error) { started := req.StartedAt if started.IsZero() { started = time.Now() @@ -323,6 +333,13 @@ func (c *Client) Run(ctx context.Context, req Request) (result Result, resultErr if err != nil { return setupError("configuration", err) } + if managed != nil && managed.codexAPIKey != "" { + envSet = map[string]string{"OPENAI_API_KEY": managed.codexAPIKey} + } + redact := envSet + if managed != nil && c.profile.Token != "" { + redact = map[string]string{"ANTHROPIC_AUTH_TOKEN": c.profile.Token} + } o := worker.Opts{EnvSet: envSet, EnvUnset: envUnset, ProfileName: c.cfg.ProfileName, Profile: c.profile, Model: req.Model, EnvironmentDirectory: req.EnvironmentDirectory, Native: native, @@ -333,6 +350,13 @@ func (c *Client) Run(ctx context.Context, req Request) (result Result, resultErr ToolsDisabled: req.ToolsDisabled, AllowedTools: req.AllowedTools, DisallowedTools: req.DisallowedTools, OnUnsupportedTools: req.OnUnsupportedTools, Timeout: timeout, StartedAt: started, NoSalvage: !req.AllowSalvage, MaxWorkers: maxWorkers, Limits: c.limits, Transcript: req.Capture} + if managed != nil { + o.Context = &worker.ContextDispatch{ + Clean: managed.mode == RuntimeClean, Executable: managed.executable, + BeforeStart: managed.authorize, Dispatched: func() { managed.dispatched.Store(true) }, + Injected: func() { managed.injected.Store(true) }, + } + } if o.Model == "" { o.Model = c.profile.Model } @@ -384,7 +408,7 @@ func (c *Client) Run(ctx context.Context, req Request) (result Result, resultErr if c.profile.BackendName() == "agy" { protocol = worker.AgyProtocol } - err := req.OnEvent(RawEvent{RunID: id, CallerRunID: req.CallerRunID, Backend: c.profile.BackendName(), NativeProtocol: protocol, Data: redactEnvValues(line, envSet)}) + err := req.OnEvent(RawEvent{RunID: id, CallerRunID: req.CallerRunID, Backend: c.profile.BackendName(), NativeProtocol: protocol, Data: redactEnvValues(line, redact)}) observerErr = errors.Join(observerErr, err) if err != nil || progress == nil { return err @@ -403,9 +427,15 @@ func (c *Client) Run(ctx context.Context, req Request) (result Result, resultErr record.Transcript = "captured" } } - record.Result = string(redactEnvValues([]byte(record.Result), envSet)) - record.NativeStderr = string(redactEnvValues([]byte(record.NativeStderr), envSet)) - record.Error = string(redactEnvValues([]byte(record.Error), envSet)) + record.Result = string(redactEnvValues([]byte(record.Result), redact)) + record.NativeStderr = string(redactEnvValues([]byte(record.NativeStderr), redact)) + record.Error = string(redactEnvValues([]byte(record.Error), redact)) + if managed != nil && len(record.StructuredOutput) > 0 && len(redact) > 0 { + redacted := redactEnvValues(record.StructuredOutput, redact) + if !bytes.Equal(redacted, record.StructuredOutput) { + record.StructuredOutput = nil + } + } raw, encodeErr := json.Marshal(record) usage, _ := json.Marshal(record.Usage) if record.Usage == nil { @@ -491,6 +521,10 @@ func redactEnvValues(line []byte, set map[string]string) []byte { out := bytes.Clone(line) for _, v := range set { if v != "" { + escaped, _ := json.Marshal(v) + if len(escaped) > 2 && string(escaped[1:len(escaped)-1]) != v { + out = bytes.ReplaceAll(out, escaped[1:len(escaped)-1], []byte("[REDACTED]")) + } out = bytes.ReplaceAll(out, []byte(v), []byte("[REDACTED]")) } }