fix: complete direct isolation evidence and funding checks
Co-Authored-By: Astra <noreply@openai.com>
18 files changed,
+732
−15
docs/live-gate.md+7 −0docs/superpowers/plans/CONTROLLER-REPORT-direct-isolation-checks.md+219 −0docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+2 −0internal/directlive/claude_hooks.go+158 −0internal/directlive/coordinator.go+3 −0internal/directlive/driver.go+13 −2internal/directlive/driver_test.go+1 −1internal/directlive/observations.go+4 −1internal/directlive/probes.go+8 −2internal/directlive/readback.go+1 −1internal/directlive/recovery.go+8 −1internal/directlive/round3_test.go+185 −0internal/directlive/subscription.go+68 −0internal/directlive/testdata/fake-cli.py+1 −1internal/directlive/turn.go+8 −0internal/equipo/copy.go+3 −3internal/tryequipo/funding_test.go+38 −0internal/tryequipo/run.go+5 −3
CI failed — run details
diff --git a/docs/live-gate.md b/docs/live-gate.md| index a9a625d2..e7913cae 100644 |
| --- a/docs/live-gate.md |
| +++ b/docs/live-gate.md |
| @@ -45,6 +45,13 @@ project and team token headroom. Enter your own limits where needed. These are |
| bounds on calls, tokens and duration; subscription usage has no hard currency |
| cap. Type `RUN LIVE GATE` to authorize that run. |
| +The proposed limits are 500 calls, 50 million input tokens, 2 million output |
| +tokens and 7200 seconds, with 5,750,000 input tokens and 230,000 output tokens |
| +for the job and each project/team headroom value. The guide proposes these |
| +values again when you saved the older defaults, keeps custom limits, and prints |
| +the exact funding values to enter if the measured job or period headroom is too |
| +small. |
| + |
| The guide creates a disposable Git repository and sentinels. The live driver |
| checks each provider's policies, approvals, recovery and isolation. The runner |
| checks synthetic markers directly through the production namespace and the |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-direct-isolation-checks.md b/docs/superpowers/plans/CONTROLLER-REPORT-direct-isolation-checks.md| index c56b75de..8a2ae34e 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-direct-isolation-checks.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-direct-isolation-checks.md |
| @@ -1,5 +1,224 @@ |
| # Direct isolation checks |
| +## Round 3 |
| + |
| +Codex clean resume passed live. Claude's mounted-settings and complete-stream |
| +hook evidence passed live and again against the final parser. Both authorized |
| +subscription bindings pass the currency-cap check after replay corrected a |
| +false match on `concurrency_limit`. The guide now proposes enough job funding |
| +for the measured maximum, with margin, and larger calibration totals for the |
| +full exercise family. No full live gate, certificate, index or manifest candidate |
| +was created. Full certification remains unproven outside this debugging scope. |
| + |
| +### C1: subscription limits |
| + |
| +Design sections 6.8 and 7 and plan 2b Task 11 distinguish subscription allowance |
| +from metered API spending. Plan 2b explicitly requires calls, tokens, duration, |
| +twice-max reservations and period headroom without a hard subscription currency |
| +cap. This agrees with the controller's interpretation. |
| + |
| +The check now requires every configured certification binding to match exactly |
| +one runner binding by ID, provider, account, source home and model, with Kind |
| +`subscription`. It records the binding kinds and the authorized funding fields. |
| +Missing, duplicate, mismatched, API or unknown bindings fail. Funding has only |
| +call, token and time fields. Structured currency-cap configuration or provider |
| +cap events fail the check; display-only `total_cost_usd` does not. Configuration, |
| +settings, launch flags and captured streams, including recovery, contribute to |
| +this evidence. No credential files are inspected by the evidence reader. |
| + |
| +The first live implementation matched the word currency inside concurrency. |
| +Claude's result frames contain `subagent_stats.refused.concurrency_limit`, which |
| +made the currency verdict fail. A failing regression test reproduced this. |
| +The final parser checks named currency-cap keys and the pinned |
| +`error_max_budget_usd` subtype. Replay of both complete captured streams passes. |
| +The replay made no model request and did not replace the original observations. |
| + |
| +### C2: Claude hooks and plugins |
| + |
| +The trusted driver reads the actual mounted settings through the provider |
| +namespace at every open, including resume. It records their SHA-256, the |
| +expected policy-settings SHA-256 and the failed write-open proving immutability. |
| +The two live readbacks matched and were read-only. The settings require |
| +`disableAllHooks: true`, both built-in plugins explicitly false, no enabled |
| +plugin and no `hooks` key. Missing or null evidence fails. |
| + |
| +The pinned Claude 2.1.312 binary contains stream emitters with |
| +`type: system` and subtypes `hook_started`, `hook_progress`, `hook_response`. |
| +The adjacent fields include hook_id, hook_name and hook_event; progress and |
| +response also carry output. These were identified in the installed pinned |
| +executable, without running another provider command. The checker rejects all |
| +`hook_` system events, including these three known types. |
| + |
| +Every init frame must report version 2.1.312 and explicit empty arrays for |
| +plugins, skills and slash_commands. The live tuple had ten init frames, all |
| +valid, and no hook event. Finalization reads the whole journal after provider |
| +shutdown, so later resume or generation turns cannot leave an earlier pass |
| +intact. Recovery adds its mounted readback and durable frames to the same |
| +observation. Tests inject each hook subtype during recovery and require the |
| +previous passing verdict to fail. Recovery itself was not exercised live. |
| + |
| +A fixture caught a storage bug during implementation: indenting a JSON settings |
| +value changed the bytes used for its digest on recovery readback. Settings now |
| +persist as exact bytes, encoded by JSON, preserving their original hash. The |
| +full fake Engineering exercise passed after this correction. |
| + |
| +### C3: funding arithmetic |
| + |
| +| Tuple measured in this round | Completed turns | Maximum input | Maximum output | Total input | Total output | |
| +|---|---:|---:|---:|---:|---:| |
| +| Claude Engineering, authorized exercise phases | 10 | 60,446 | 2,323 | 375,353 | 12,798 | |
| +| Codex Engineering, initial turn and clean resume | 2 | 4,387 | 6 | 7,924 | 11 | |
| + |
| +Claude input includes ordinary input, cache reads and cache creation once. |
| +The combined debug usage was 383,277 input and 12,809 output tokens. |
| +Codex's two-turn sample does not measure its entire exercise family. |
| + |
| +The measured Claude reservation is ceil(2 × 60,446 / 1,000) × 1,000 = 121,000 |
| +input and ceil(2 × 2,323 / 1,000) × 1,000 = 5,000 output. The job floor is |
| +23 × 121,000 = 2,783,000 input and 23 × 5,000 = 115,000 output. The former |
| +2,300,000 input default would fail on this run too. |
| + |
| +The new job proposal is 23 × 250,000 = 5,750,000 input and |
| +23 × 10,000 = 230,000 output. This gives more than twice the measured required |
| +input reservation and twice the output reservation. Project and team headroom |
| +use the same proposed job amounts. Output job funding therefore stays at the |
| +old default; input increases. |
| + |
| +Calibration totals also need to cover all roles and the deliberately unknown |
| +recovery and identity-guard charges. A conservative planning allowance is |
| +16 completed turns for each of 17 specialist tuples, plus two coordinator |
| +turns: 274 completed turns. Allow another two full admission reservations per |
| +specialist: 34 reservations. Using twice the measured maximum rounded to 1,000 |
| +for every completed turn gives 274 × 121,000 + 34 × 250,000 = 41,654,000 input |
| +and 274 × 5,000 + 34 × 10,000 = 1,710,000 output. This deliberately overcounts |
| +some turns to allow margin. Proposed calibration totals are therefore |
| +50,000,000 input and 2,000,000 output, within the unchanged 500 calls and 7,200 |
| +seconds. This is a funding estimate for the full family, not an observation that |
| +all roles have already run or a guarantee against larger future usage. |
| + |
| +Saved values equal to the old defaults are re-proposed in the guide's prompts. |
| +Custom values remain selected, and each prompt still accepts another value. |
| +The final funding display and `RUN LIVE GATE` authorization remain mandatory. |
| +No current run raises its configured limits. Insufficient job or period |
| +headroom now returns the six exact values to enter on the next run. The new |
| +message lives in `internal/equipo/copy.go` as `CopyCalibrationFunding`, marked |
| +COPY REVIEW REQUIRED before release. No copy-review server was started. |
| + |
| +### C4: live launch log and replay |
| + |
| +Both launches used production leases, policy construction, launchers, the Go |
| +namespace helper and direct isolation probes. A temporary test overlay omitted |
| +human controls, generation, accountChange, identity tampering and recovery. |
| +Codex used an initial short turn and the production cleanResume path; Claude |
| +ran the original probes, workspace control, both routing turns, namespace |
| +checks, resume, lifetime checks, inventory and calibration. Policies, launch |
| +flags and sandbox settings were unchanged. Source-home markers were synthetic |
| +scratch fixtures, as in Round 2; the harness never read account-home contents. |
| +Only production lease staging handled credentials. |
| + |
| +| UTC on 2026-11-05 | Tuple | Admissions | Outcome | |
| +|---|---|---:|---| |
| +| 11:57:09–11:57:31 | Codex Engineering, paul@tito.io, codex | 2 | Initial turn and same-session resume completed; direct isolation passed | |
| +| 11:57:31–11:59:50 | Claude Engineering, paul@tito.io, claude-a | 10 | Authorized exercise completed; direct isolation, mounted hook evidence and resume passed | |
| + |
| +Exactly 12 of 12 admissions were used, sequentially. There were no rejected |
| +launches or additional model requests. The fixed debug bounds were 12 calls, |
| +10,000,000 input, 1,000,000 output and 1,800 seconds; job and period funding |
| +were 9,200,000 input and 920,000 output. Those bounds were chosen before launch |
| +and were never increased. They are separate from the guide's new proposals. |
| + |
| +The Claude routing turn also exposed an existing parser gap: ask_person |
| +received an extra path field and returned Equipo's exact schema-refusal text, |
| +with a matching tool-use ID, is_error true and zero approval questions. |
| +The original parser left this unverified. The narrow fix recognizes the existing |
| +`CopyToolRejected` value only for a correlated Equipo MCP call. Unmatched IDs, |
| +success replies, generic errors and any human question still cannot certify |
| +automatic refusal. A failing test preceded the fix; captured-frame replay passed. |
| + |
| +| Check | Codex Engineering | Claude Engineering | |
| +|---|---|---| |
| +| clean-session-resume | live pass, same session ID | live pass | |
| +| direct-isolation | live pass | live pass | |
| +| no-hooks-plugins | live pass | live pass and final-parser replay pass | |
| +| no-subscription-currency-cap | live pass and replay pass | final-parser replay pass | |
| +| 23-reservations-per-job | live pass with fixed debug funding | live pass with fixed debug funding | |
| +| tool-routing | not exercised in this round | original verdict not-certified; all routing observations pass or decline after the correlated refusal replay | |
| + |
| +Human approval controls, crash recovery, generation and account-change behavior |
| +remain live-unproven in this scope. No replay or fixture is labelled as a full |
| +passing certification. Paul's separately authorized full run is still required. |
| + |
| +### C5: verification and cleanup |
| + |
| +New tests first failed compilation for the missing evidence helpers. Subsequent |
| +assertion failures reproduced the concurrency false match, unrecognized schema |
| +refusal, old funding defaults and recovery settings-byte mismatch. Restored |
| +targeted tests passed. The fake CLI Engineering exercise passed in 28.668s, |
| +including initial/resumed mounted readbacks, recovery and both new checks. |
| + |
| +Commands used, with CGO disabled: |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/directlive ./internal/tryequipo -run 'TestSubscriptionCurrencyEvidence|TestClaudeHookEvidence|TestClaudeRecoveryHook|TestClaudeEquipoSchemaDenial|TestCalibration|TestDriverCalibration|TestFundingProposedDefaults|TestToolRouting|TestPolicyEvidence' -count=1 |
| +CGO_ENABLED=0 go test ./internal/directlive -run '^TestDirectDriverFakeCLI/Engineering$' -count=1 |
| +CGO_ENABLED=0 go test -overlay <replay-overlay> ./internal/directlive -run '^TestRound3Replay$' -count=1 -v |
| +make budget |
| +make -k ci |
| +``` |
| + |
| +Thirteen temporary source mutations each failed an assertion with exit 1 using |
| +`CGO_ENABLED=0 go test -overlay <mutation-overlay> <package> -run <test> -count=1`. |
| +No mutation touched the working source, and all overlays were removed. |
| + |
| +| Deliberate break | Failing test | |
| +|---|---| |
| +| Accept API binding kinds | TestSubscriptionCurrencyEvidence | |
| +| Ignore observed currency caps | TestSubscriptionCurrencyEvidence/observed | |
| +| Accept writable settings | TestClaudeHookEvidence/writable | |
| +| Ignore mounted or expected digest mismatch | TestClaudeHookEvidence/hash, expected | |
| +| Allow a hooks key | TestClaudeHookEvidence/hooks | |
| +| Ignore disableAllHooks false | TestClaudeHookEvidence/hooks-enabled | |
| +| Accept enabled plugins | TestClaudeHookEvidence/enabled | |
| +| Ignore hook stream events | TestClaudeHookEvidence | |
| +| Accept null/nonempty init arrays | TestClaudeHookEvidence | |
| +| Omit recovery frames from hook proof | TestClaudeRecoveryHookInvalidatesEarlierPass | |
| +| Suppress exact insufficient-funding error | TestCalibrationFundingRerun | |
| +| Restore old proposed input funding | TestFundingProposedDefaults | |
| +| Ignore a schema refusal's tool-use ID | TestClaudeEquipoSchemaDenial | |
| + |
| +The size gate initially caught three extra root-package lines. The new runtime |
| +message now occupies one individually marked line in the existing copy block, |
| +using one existing blank line. All 38 directories fit the unchanged budgets. |
| + |
| +The initial full gate failed staticcheck ST1005 because the new funding error |
| +started with a capital letter, and the Plan 3 release-boundary inventory test |
| +because the pending message lacked its review-inventory row. Both are fixed: the |
| +error starts in lowercase and the exact pending text is in the existing Plan 3 |
| +copy inventory. No review requirement was waived. The test step ran 27 packages |
| +uncached in 5m27.005s, with one package failure. Local timing warnings were |
| +provider 20.104s/15s, Claude 46.936s/45s and Codex 39.960s/35s. |
| + |
| +The second full `make -k ci` exited 0 on the final code. All 28 test packages |
| +ran uncached and passed in 5m26.457s. Build, vet, formatting, staticcheck, |
| +vulnerability and secret scans, reference checks, size budgets, provider and |
| +namespace checks, migration and performance all passed. Cold boot measured |
| +107ms against 500ms; all screen measurements stayed within 150ms. Final local |
| +timing warnings were provider 19.953s/15s, Claude 45.296s/45s and Codex |
| +38.609s/35s. These warnings would fail with CI timing enforcement enabled; no |
| +passing remote gate is claimed. There were exactly two full invocations, the |
| +initial gate and one rerun. |
| + |
| +All task scratch, debug binaries, captures, replay and mutation overlays and |
| +logs were removed after the results were recorded here. No task process or |
| +server remains. No copy-review server ran. Saved account bindings, setup state |
| +and runner environment were unchanged, and the user worktree was retained. |
| +Safe changes are committed and pushed on `direct-isolation-checks`; no merge, |
| +default-branch push, deployment or certification bundle was made. |
| + |
| +No implementation decision is blocked. Before release, the controller still |
| +needs to review the pending `CopyCalibrationFunding` message; Paul must run |
| +the separately authorized full live gate for the excluded checks. |
| + |
| ## Round 2 |
| The two boundaries now have separate evidence. Both providers hid every tested |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index 75d9d303..f2e6fabf 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -5158,6 +5158,8 @@ records to satisfy a gate. Release remains blocked while any row is pending. |
| | `live.check-allow` | Equipo is checking one-time approval. Type Allow once. | Guided live probe controls | COPY ACCEPTED FOR NOW (Paul, 2026-11-05; live-probe brief) | |
| | `live.check-question` | Equipo is checking that your answer reaches the agent. Enter an answers JSON object. | Guided live probe controls | COPY ACCEPTED FOR NOW (Paul, 2026-11-05; live-probe brief) | |
| +| `CopyCalibrationFunding` | calibration funding is too low; rerun with JobInput=%d JobOutput=%d ProjectInputHeadroom=%d ProjectOutputHeadroom=%d TeamInputHeadroom=%d TeamOutputHeadroom=%d: %w | Direct isolation Round 3 | COPY REVIEW REQUIRED | |
| + |
| ## Task 21 |
| Status: DONE_WITH_CONCERNS. Offline 3b acceptance, the complete person API contract |
diff --git a/internal/directlive/claude_hooks.go b/internal/directlive/claude_hooks.go| new file mode 100644 |
| index 00000000..4aede1ea |
| --- /dev/null |
| +++ b/internal/directlive/claude_hooks.go |
| @@ -0,0 +1,158 @@ |
| +package directlive |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "os" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| +) |
| + |
| +type claudeSettingsReadback struct { |
| + Attempt, SHA256, ExpectedSHA256 string |
| + ReadOnly bool |
| + Settings []byte |
| +} |
| + |
| +type claudeHookEvidence struct { |
| + MountedSettings []claudeSettingsReadback `json:"mounted_settings"` |
| + Frames []json.RawMessage `json:"frames"` |
| + HookEventSubtypes []string `json:"hook_event_subtypes"` |
| + Scope string `json:"scope"` |
| +} |
| + |
| +func (x *exercise) readClaudeSettings(ctx context.Context) error { |
| + if x.launch.Selection.Provider != "claude" { |
| + return nil |
| + } |
| + records, err := x.manager.Records(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + for _, record := range records { |
| + if record.AttemptKey != x.session.AttemptKey { |
| + continue |
| + } |
| + path := "/proc/" + strconv.Itoa(record.HostPID) + "/root" + provider.SettingsPath |
| + raw, err := os.ReadFile(path) |
| + if err != nil { |
| + return err |
| + } |
| + f, writeErr := os.OpenFile(path, os.O_WRONLY, 0) |
| + if writeErr == nil { |
| + f.Close() |
| + } |
| + readonly := os.IsPermission(writeErr) |
| + // A read-only mount returns EROFS rather than a permission error. |
| + if errors.Is(writeErr, syscall.EROFS) { |
| + readonly = true |
| + } |
| + x.claudeSettings = append(x.claudeSettings, claudeSettingsReadback{Attempt: x.session.AttemptKey, Settings: raw, SHA256: provider.DigestDirectEvidence(raw), ExpectedSHA256: provider.DigestDirectEvidence(x.launch.Policy.Settings), ReadOnly: readonly}) |
| + return nil |
| + } |
| + return provider.ErrUncertain |
| +} |
| + |
| +func claudeHooksAbsent(frames []json.RawMessage, mounts []claudeSettingsReadback) bool { |
| + if len(mounts) == 0 { |
| + return false |
| + } |
| + for _, m := range mounts { |
| + if !m.ReadOnly || m.SHA256 != provider.DigestDirectEvidence(m.Settings) || m.SHA256 != m.ExpectedSHA256 { |
| + return false |
| + } |
| + var s map[string]json.RawMessage |
| + if json.Unmarshal(m.Settings, &s) != nil || string(s["disableAllHooks"]) != "true" { |
| + return false |
| + } |
| + if _, exists := s["hooks"]; exists { |
| + return false |
| + } |
| + var plugins map[string]json.RawMessage |
| + if json.Unmarshal(s["enabledPlugins"], &plugins) != nil { |
| + return false |
| + } |
| + for _, key := range []string{"agents-md@builtin", "plugin-authoring@builtin"} { |
| + if enabled, exists := plugins[key]; !exists || string(enabled) != "false" { |
| + return false |
| + } |
| + } |
| + for _, enabled := range plugins { |
| + if string(enabled) != "false" { |
| + return false |
| + } |
| + } |
| + } |
| + init := false |
| + for _, raw := range frames { |
| + var f struct { |
| + Type, Subtype string |
| + Version string `json:"claude_code_version"` |
| + Plugins, Skills json.RawMessage |
| + Commands json.RawMessage `json:"slash_commands"` |
| + } |
| + if json.Unmarshal(raw, &f) != nil { |
| + return false |
| + } |
| + if f.Type != "system" { |
| + continue |
| + } |
| + // Pinned 2.1.312 emits hook_started, hook_progress and hook_response. |
| + if strings.HasPrefix(f.Subtype, "hook_") { |
| + return false |
| + } |
| + if f.Subtype != "init" { |
| + continue |
| + } |
| + init = true |
| + if f.Version != provider.ClaudeVersion { |
| + return false |
| + } |
| + for _, field := range []json.RawMessage{f.Plugins, f.Skills, f.Commands} { |
| + var entries []json.RawMessage |
| + if json.Unmarshal(field, &entries) != nil || entries == nil || len(entries) != 0 { |
| + return false |
| + } |
| + } |
| + } |
| + return init |
| +} |
| + |
| +func (x *exercise) finishClaudeHooks(frames []json.RawMessage) error { |
| + if x.evidence.Provider != "claude" { |
| + return nil |
| + } |
| + return x.check("no-hooks-plugins", claudeHooksAbsent(frames, x.claudeSettings), claudeHookEvidence{x.claudeSettings, frames, []string{"hook_started", "hook_progress", "hook_response"}, "all tuple streams including resume"}) |
| +} |
| + |
| +func extendRecoveryHooks(root string, e *provider.DirectEvidence, mounts []claudeSettingsReadback, frames []json.RawMessage) error { |
| + if e.Provider != "claude" { |
| + return nil |
| + } |
| + old := e.Checks["no-hooks-plugins"] |
| + if err := provider.VerifyDirectObservation(root, old, old.Status); err != nil { |
| + return err |
| + } |
| + path := root + "/" + old.Artifact |
| + raw, err := os.ReadFile(path) |
| + if err != nil { |
| + return err |
| + } |
| + var proof claudeHookEvidence |
| + if err = json.Unmarshal(raw, &proof); err != nil { |
| + return err |
| + } |
| + proof.MountedSettings = append(proof.MountedSettings, mounts...) |
| + proof.Frames = append(proof.Frames, frames...) |
| + proof.Scope = "all tuple streams including resume and recovery" |
| + ok := old.Status == "pass" && len(mounts) > 0 && claudeHooksAbsent(proof.Frames, proof.MountedSettings) |
| + if err = os.Remove(path); err != nil { |
| + return err |
| + } |
| + x := exercise{root: root, evidence: *e} |
| + return x.check("no-hooks-plugins", ok, proof) |
| +} |
diff --git a/internal/directlive/coordinator.go b/internal/directlive/coordinator.go| index 567e1c29..f53c3a33 100644 |
| --- a/internal/directlive/coordinator.go |
| +++ b/internal/directlive/coordinator.go |
| @@ -39,6 +39,9 @@ func (x *exercise) coordinatorFixture(ctx context.Context) (provider.DirectEvide |
| return x.evidence, fmt.Errorf("coordinator launcher open: %w", err) |
| } |
| defer x.launcher.Close(context.Background(), x.session) |
| + if err = x.readClaudeSettings(ctx); err != nil { |
| + return x.evidence, err |
| + } |
| if err = x.check("account-version-readback", true, x.session); err != nil { |
| return x.evidence, err |
| } |
diff --git a/internal/directlive/driver.go b/internal/directlive/driver.go| index ece0689e..fa3a491e 100644 |
| --- a/internal/directlive/driver.go |
| +++ b/internal/directlive/driver.go |
| @@ -27,6 +27,7 @@ func EnvironmentPaths(getenv func(string) string) Paths { |
| } |
| type driver struct { |
| + currencyCap bool |
| policyPaths PolicyPaths |
| workerRoot string |
| worker bool |
| @@ -75,7 +76,7 @@ func runRoles(ctx context.Context, c provider.DirectLiveConfig, config []byte, p |
| if _, e := os.Stat(homes); os.IsNotExist(e) { |
| defer os.Remove(homes) |
| } |
| - d := &driver{policyPaths: policyPaths, cfg: c, paths: p, configHash: provider.DigestDirectEvidence(config), source: source, root: root, answer: answer} |
| + d := &driver{currencyCap: currencyCapSignal(config), policyPaths: policyPaths, cfg: c, paths: p, configHash: provider.DigestDirectEvidence(config), source: source, root: root, answer: answer} |
| d.hashes, err = p.verify() |
| if err != nil { |
| return err |
| @@ -176,6 +177,7 @@ func (p Paths) verify() (map[string]string, error) { |
| func marshal(v any) []byte { raw, _ := json.Marshal(v); return raw } |
| type exercise struct { |
| + claudeSettings []claudeSettingsReadback |
| inputs provider.PolicyInputs |
| mu sync.Mutex |
| answers map[string]int |
| @@ -226,7 +228,10 @@ func (d *driver) exercise(ctx context.Context, b provider.DirectLiveBinding, rol |
| defer j.Close() |
| defer func() { |
| frames, e := j.CaptureEvidence(context.Background()) |
| - err = errors.Join(err, e, save(root, "capture.json", frames)) |
| + for _, frame := range frames { |
| + d.currencyCap = d.currencyCap || currencyCapSignal(frame) |
| + } |
| + err = errors.Join(err, e, x.finishClaudeHooks(frames), save(root, "capture.json", frames)) |
| }() |
| phase = "containment" |
| x.manager, err = containment.New(containment.Config{Binary: d.paths.Bwrap, RunnerBinary: d.paths.Runner, ScratchRoot: d.policyPaths.ScratchRoot, ProviderNetworks: []provider.NetworkContract{{Provider: b.Binding.Provider, AuthHost: b.AuthHost}}}) |
| @@ -330,6 +335,9 @@ func (d *driver) exercise(ctx context.Context, b provider.DirectLiveBinding, rol |
| observed["inner-sandbox-enabled"] = x.evidence.Checks["direct-isolation"].Status == "pass" && observed["effective-policy-readback"] |
| for check, ok := range observed { |
| + if check == "no-hooks-plugins" && x.evidence.Provider == "claude" { |
| + continue |
| + } |
| if err = x.check(check, ok, map[string]any{"frames": captured, "checks": observed, "codex_policy": readback}); err != nil { |
| return e, err |
| } |
| @@ -365,6 +373,9 @@ func (d *driver) exercise(ctx context.Context, b provider.DirectLiveBinding, rol |
| } |
| for _, group := range []string{"Contract", "Isolation", "Recovery", "Calibration"} { |
| for _, check := range provider.DirectRequirements(group) { |
| + if check == "no-hooks-plugins" && x.evidence.Provider == "claude" { |
| + continue |
| + } |
| if _, ok := x.evidence.Checks[check]; !ok { |
| if err = x.check(check, false, map[string]string{"result": "not-certified"}); err != nil { |
| return e, err |
diff --git a/internal/directlive/driver_test.go b/internal/directlive/driver_test.go| index 9175abd4..b98f766d 100644 |
| --- a/internal/directlive/driver_test.go |
| +++ b/internal/directlive/driver_test.go |
| @@ -246,7 +246,7 @@ func TestDirectDriverFakeWorker(t *testing.T) { |
| if e.Checks["tuple-completed"].Status == "not-certified" || e.Checks["complete-input-output"].Status != "pass" { |
| t.Fatal("specialist contaminated by coordinator", name) |
| } |
| - for _, check := range []string{"person-native-approval", "real-question-answer", "policy-escalation-denied", "equipo-broker-approval", "stale-broker-denied", "invalid-broker-denied", "clean-session-resume", "mid-turn-runner-kill", "durable-replay", "no-redispatch", "unknown-usage-retained", "pidfd-exit", "same-identity-generation-fresh-preflight-bind", "same-identity-continued-availability", "identity-marker-tamper-denied", "changed-identity-stops-step", "exact-tool-inventory", "tool-inventory-complete"} { |
| + for _, check := range []string{"no-hooks-plugins", "no-subscription-currency-cap", "person-native-approval", "real-question-answer", "policy-escalation-denied", "equipo-broker-approval", "stale-broker-denied", "invalid-broker-denied", "clean-session-resume", "mid-turn-runner-kill", "durable-replay", "no-redispatch", "unknown-usage-retained", "pidfd-exit", "same-identity-generation-fresh-preflight-bind", "same-identity-continued-availability", "identity-marker-tamper-denied", "changed-identity-stops-step", "exact-tool-inventory", "tool-inventory-complete"} { |
| if e.Checks[check].Status != "pass" { |
| t.Fatalf("%s did not exercise %s: %+v", name, check, e.Checks[check]) |
| } |
diff --git a/internal/directlive/observations.go b/internal/directlive/observations.go| index 98b30a69..39b1cd1f 100644 |
| --- a/internal/directlive/observations.go |
| +++ b/internal/directlive/observations.go |
| @@ -1,6 +1,7 @@ |
| package directlive |
| import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| "encoding/json" |
| "strings" |
| ) |
| @@ -31,7 +32,9 @@ func observedRead(name string, frames [][]byte, tool, path string, denied bool) |
| calls[b.ID] = true |
| } |
| if v.Type == "user" && b.Type == "tool_result" && calls[b.ToolUseID] && b.IsError == denied && len(b.Content) > 0 { |
| - return !denied || denial(string(b.Content)) |
| + var message string |
| + equipoRefusal := strings.HasPrefix(tool, "mcp__equipo__") && json.Unmarshal(b.Content, &message) == nil && message == equipo.CopyToolRejected |
| + return !denied || denial(string(b.Content)) || equipoRefusal |
| } |
| } |
| } else { |
diff --git a/internal/directlive/probes.go b/internal/directlive/probes.go| index 45675198..4b0135ce 100644 |
| --- a/internal/directlive/probes.go |
| +++ b/internal/directlive/probes.go |
| @@ -1,6 +1,7 @@ |
| package directlive |
| import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| "context" |
| "encoding/json" |
| @@ -179,13 +180,18 @@ func (x *exercise) calibration() error { |
| maxOutput = max(maxOutput, sample.Output) |
| } |
| bounded := x.d.calls > 0 && x.d.calls <= f.Calls && x.d.input <= f.InputTokens && x.d.output <= f.OutputTokens |
| - checks := map[string]bool{"separate-bounded-admission": bounded, "complete-input-output": complete, "usage-unknowns-recorded": complete && x.evidence.Checks["unknown-usage-retained"].Status == "pass", "twice-max-rounded-1000": in == ((2*maxInput+999)/1000)*1000 && out == ((2*maxOutput+999)/1000)*1000, "23-reservations-per-job": f.JobInput >= 23*in && f.JobOutput >= 23*out, "project-period-headroom": f.ProjectInputHeadroom >= f.JobInput && f.ProjectOutputHeadroom >= f.JobOutput, "team-period-headroom": f.TeamInputHeadroom >= f.JobInput && f.TeamOutputHeadroom >= f.JobOutput, "configured-limits-unchanged": x.evidence.Funding == x.d.cfg.Funding, "no-subscription-currency-cap": false} |
| + currencyOK, currencyEvidence := x.d.subscriptionCurrencyEvidence() |
| + checks := map[string]bool{"separate-bounded-admission": bounded, "complete-input-output": complete, "usage-unknowns-recorded": complete && x.evidence.Checks["unknown-usage-retained"].Status == "pass", "twice-max-rounded-1000": in == ((2*maxInput+999)/1000)*1000 && out == ((2*maxOutput+999)/1000)*1000, "23-reservations-per-job": f.JobInput >= 23*in && f.JobOutput >= 23*out, "project-period-headroom": f.ProjectInputHeadroom >= f.JobInput && f.ProjectOutputHeadroom >= f.JobOutput, "team-period-headroom": f.TeamInputHeadroom >= f.JobInput && f.TeamOutputHeadroom >= f.JobOutput, "configured-limits-unchanged": x.evidence.Funding == x.d.cfg.Funding, "no-subscription-currency-cap": currencyOK} |
| for name, ok := range checks { |
| - if err = x.check(name, ok, map[string]any{"input_reservation": in, "output_reservation": out, "funding": f, "usage": x.evidence.Usage, "charged_calls": x.d.calls, "charged_input": x.d.input, "charged_output": x.d.output, "currency_cap_observed": false}); err != nil { |
| + if err = x.check(name, ok, map[string]any{"input_reservation": in, "output_reservation": out, "funding": f, "usage": x.evidence.Usage, "charged_calls": x.d.calls, "charged_input": x.d.input, "charged_output": x.d.output, "subscription_currency_evidence": currencyEvidence}); err != nil { |
| return err |
| } |
| } |
| + if !checks["23-reservations-per-job"] || !checks["project-period-headroom"] || !checks["team-period-headroom"] { |
| + jobIn, jobOut := max(f.JobInput, 23*in), max(f.JobOutput, 23*out) |
| + return fmt.Errorf(equipo.CopyCalibrationFunding, jobIn, jobOut, max(f.ProjectInputHeadroom, jobIn), max(f.ProjectOutputHeadroom, jobOut), max(f.TeamInputHeadroom, jobIn), max(f.TeamOutputHeadroom, jobOut), provider.ErrPolicy) |
| + } |
| return nil |
| } |
diff --git a/internal/directlive/readback.go b/internal/directlive/readback.go| index 2a79c961..019451cb 100644 |
| --- a/internal/directlive/readback.go |
| +++ b/internal/directlive/readback.go |
| @@ -29,7 +29,7 @@ func observedPolicy(frames []json.RawMessage, l provider.Launch) (map[string]boo |
| if l.Selection.Provider == "claude" && frame.Type == "system" && frame.Subtype == "init" { |
| checks["effective-policy-readback"] = frame.Version == l.Binding.Expected.ProviderVersion && frame.Model == l.Selection.Model && frame.PermissionMode == "default" |
| checks["strict-mcp"] = len(frame.MCP) == 1 && frame.MCP[0].Name == "equipo" && frame.MCP[0].Status == "connected" |
| - // Init exposes plugins and skills but no effective hook settings. |
| + // Claude hook evidence is finalized from all streams and mounted settings. |
| checks["no-hooks-plugins"] = false |
| } |
| if policy != nil && len(frame.Result) > 0 { |
diff --git a/internal/directlive/recovery.go b/internal/directlive/recovery.go| index cbbfbf0a..5b8f2c4c 100644 |
| --- a/internal/directlive/recovery.go |
| +++ b/internal/directlive/recovery.go |
| @@ -25,6 +25,7 @@ type workerPlan struct { |
| Role, Root string |
| } |
| type dispatched struct { |
| + ClaudeSettings []claudeSettingsReadback |
| RuntimeHome, ConfigHome string |
| Session provider.Session |
| Turn provider.Turn |
| @@ -72,7 +73,7 @@ func (x *exercise) waitForKill(ctx context.Context) error { |
| if err = json.Unmarshal(x.launch.Policy.Manifest, &concrete); err != nil { |
| return err |
| } |
| - if err = save(x.d.workerRoot, "dispatched.json", dispatched{RuntimeHome: x.launch.Binding.Home, ConfigHome: concrete.ConfigHome, Session: x.session, Turn: turn, Record: r}); err != nil { |
| + if err = save(x.d.workerRoot, "dispatched.json", dispatched{ClaudeSettings: x.claudeSettings, RuntimeHome: x.launch.Binding.Home, ConfigHome: concrete.ConfigHome, Session: x.session, Turn: turn, Record: r}); err != nil { |
| return err |
| } |
| <-ctx.Done() |
| @@ -199,6 +200,12 @@ func (d *driver) recover(ctx context.Context, b provider.DirectLiveBinding, role |
| if err != nil { |
| return err |
| } |
| + for _, frame := range after { |
| + d.currencyCap = d.currencyCap || currencyCapSignal(frame) |
| + } |
| + if err = extendRecoveryHooks(root, e, ready.ClaudeSettings, after); err != nil { |
| + return err |
| + } |
| polls := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}} |
| _, err = unix.Poll(polls, 0) |
| if err != nil { |
diff --git a/internal/directlive/round3_test.go b/internal/directlive/round3_test.go| new file mode 100644 |
| index 00000000..aa60e455 |
| --- /dev/null |
| +++ b/internal/directlive/round3_test.go |
| @@ -0,0 +1,185 @@ |
| +package directlive |
| + |
| +import ( |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| +) |
| + |
| +func TestSubscriptionCurrencyEvidence(t *testing.T) { |
| + b := provider.DirectLiveBinding{Binding: provider.Binding{ID: "one", Provider: "claude", AccountID: "fixture", Home: "/fixture"}, Model: "model"} |
| + row := runner.AccountBinding{ID: "one", Provider: "claude", AccountID: "fixture", ProviderHome: "/fixture", Model: "model", Kind: "subscription"} |
| + path := filepath.Join(t.TempDir(), "bindings.json") |
| + d := &driver{cfg: provider.DirectLiveConfig{Bindings: []provider.DirectLiveBinding{b}}, policyPaths: PolicyPaths{AccountBindingsPath: path}} |
| + for _, kind := range []string{"subscription", "api", ""} { |
| + row.Kind = kind |
| + if err := os.WriteFile(path, marshal([]runner.AccountBinding{row}), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + ok, _ := d.subscriptionCurrencyEvidence() |
| + if ok != (kind == "subscription") { |
| + t.Fatalf("kind %q certified=%v", kind, ok) |
| + } |
| + } |
| + row.Kind = "subscription" |
| + for _, bad := range []string{"missing", "duplicate", "identity", "observed", "configured"} { |
| + t.Run(bad, func(t *testing.T) { |
| + r := row |
| + rows := []runner.AccountBinding{r} |
| + switch bad { |
| + case "missing": |
| + rows = nil |
| + case "duplicate": |
| + rows = append(rows, r) |
| + case "identity": |
| + rows[0].AccountID = "other" |
| + } |
| + if err := os.WriteFile(path, marshal(rows), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + d.currencyCap = bad == "observed" || bad == "configured" |
| + if ok, _ := d.subscriptionCurrencyEvidence(); ok { |
| + t.Fatal("bad currency evidence certified") |
| + } |
| + }) |
| + } |
| + if !currencyCapSignal(json.RawMessage(`{"type":"result","subtype":"error_max_budget_usd"}`)) || !currencyCapSignal(json.RawMessage(`{"max_budget_usd":1}`)) { |
| + t.Fatal("currency cap missed") |
| + } |
| + if currencyCapSignal(json.RawMessage(`{"total_cost_usd":1,"message":"max_budget_usd"}`)) { |
| + t.Fatal("display cost or model prose treated as cap") |
| + } |
| + if currencyCapSignal(json.RawMessage(`{"subagent_stats":{"refused":{"concurrency_limit":0}}}`)) { |
| + t.Fatal("concurrency mistaken for currency") |
| + } |
| +} |
| + |
| +func TestClaudeEquipoSchemaDenial(t *testing.T) { |
| + call := []byte(`{"type":"assistant","message":{"content":[{"type":"tool_use","id":"one","name":"mcp__equipo__ask_person","input":{"request_id":"probe","question":"Check","path":"/home/runner/sentinel"}}]}}`) |
| + result := []byte(`{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"one","is_error":true,"content":"This tool request could not be accepted."}]}}`) |
| + if routingStatus("claude", [][]byte{call, result}, "mcp__equipo__ask_person", "/home/runner/sentinel", true) != "denied" { |
| + t.Fatal("Equipo schema refusal unrecognized") |
| + } |
| + for _, change := range []struct{ old, new string }{{`"one"`, `"other"`}, {`"is_error":true`, `"is_error":false`}, {"This tool request could not be accepted.", "Unexpected error"}} { |
| + bad := []byte(strings.Replace(string(result), change.old, change.new, 1)) |
| + if routingStatus("claude", [][]byte{call, bad}, "mcp__equipo__ask_person", "/home/runner/sentinel", true) == "denied" { |
| + t.Fatal("unrelated response accepted") |
| + } |
| + } |
| +} |
| + |
| +func TestClaudeHookEvidence(t *testing.T) { |
| + settings := json.RawMessage(`{"disableAllHooks":true,"enabledPlugins":{"agents-md@builtin":false,"plugin-authoring@builtin":false}}`) |
| + mount := claudeSettingsReadback{Settings: settings, SHA256: provider.DigestDirectEvidence(settings), ExpectedSHA256: provider.DigestDirectEvidence(settings), ReadOnly: true} |
| + init := json.RawMessage(`{"type":"system","subtype":"init","claude_code_version":"2.1.312","plugins":[],"skills":[],"slash_commands":[]}`) |
| + if !claudeHooksAbsent([]json.RawMessage{init}, []claudeSettingsReadback{mount}) { |
| + t.Fatal("complete hook evidence refused") |
| + } |
| + for _, event := range []string{"hook_started", "hook_progress", "hook_response"} { |
| + frames := []json.RawMessage{init, marshal(map[string]string{"type": "system", "subtype": event}), init} |
| + if claudeHooksAbsent(frames, []claudeSettingsReadback{mount}) { |
| + t.Fatal("late hook hidden by later init", event) |
| + } |
| + } |
| + for _, field := range []string{"plugins", "skills", "slash_commands"} { |
| + for _, value := range []string{"null", `["unexpected"]`} { |
| + bad := json.RawMessage(strings.Replace(string(init), `"`+field+`":[]`, `"`+field+`":`+value, 1)) |
| + if claudeHooksAbsent([]json.RawMessage{init, bad}, []claudeSettingsReadback{mount}) { |
| + t.Fatal("invalid init accepted", field, value) |
| + } |
| + } |
| + bad := json.RawMessage(strings.Replace(string(init), `,"`+field+`":[]`, "", 1)) |
| + if claudeHooksAbsent([]json.RawMessage{bad}, []claudeSettingsReadback{mount}) { |
| + t.Fatal("missing init field accepted", field) |
| + } |
| + } |
| + for _, bad := range []string{"hash", "expected", "writable", "hooks", "hooks-enabled", "enabled", "null-plugin", "missing-builtin", "missing-settings", "version", "no-init"} { |
| + t.Run(bad, func(t *testing.T) { |
| + m := mount |
| + frames := []json.RawMessage{init} |
| + switch bad { |
| + case "hash": |
| + m.SHA256 = "wrong" |
| + case "expected": |
| + m.ExpectedSHA256 = "wrong" |
| + case "writable": |
| + m.ReadOnly = false |
| + case "hooks": |
| + m.Settings = json.RawMessage(strings.Replace(string(settings), `"disableAllHooks":true`, `"disableAllHooks":true,"hooks":{}`, 1)) |
| + case "hooks-enabled": |
| + m.Settings = json.RawMessage(strings.Replace(string(settings), `"disableAllHooks":true`, `"disableAllHooks":false`, 1)) |
| + case "enabled": |
| + m.Settings = json.RawMessage(strings.Replace(string(settings), "false", "true", 1)) |
| + case "null-plugin": |
| + m.Settings = json.RawMessage(strings.Replace(string(settings), "false", "null", 1)) |
| + case "missing-builtin": |
| + m.Settings = json.RawMessage(`{"disableAllHooks":true,"enabledPlugins":{}}`) |
| + case "missing-settings": |
| + m.Settings = nil |
| + case "version": |
| + frames = []json.RawMessage{json.RawMessage(strings.Replace(string(init), "2.1.312", "other", 1))} |
| + case "no-init": |
| + frames = nil |
| + } |
| + if bad != "hash" && bad != "expected" { |
| + m.SHA256 = provider.DigestDirectEvidence(m.Settings) |
| + m.ExpectedSHA256 = m.SHA256 |
| + } |
| + if claudeHooksAbsent(frames, []claudeSettingsReadback{m}) { |
| + t.Fatal("incomplete hook evidence accepted") |
| + } |
| + }) |
| + } |
| + if claudeHooksAbsent([]json.RawMessage{init}, nil) { |
| + t.Fatal("missing mounted readback accepted") |
| + } |
| +} |
| + |
| +func TestCalibrationFundingRerun(t *testing.T) { |
| + f := provider.LiveFunding{Calls: 500, InputTokens: 10000000, OutputTokens: 1000000, Seconds: 7200, JobInput: 2300000, JobOutput: 230000, ProjectInputHeadroom: 2300000, ProjectOutputHeadroom: 230000, TeamInputHeadroom: 2300000, TeamOutputHeadroom: 230000} |
| + x := &exercise{root: t.TempDir(), d: &driver{cfg: provider.DirectLiveConfig{Funding: f}, calls: 1}, evidence: provider.DirectEvidence{Funding: f, Usage: []provider.LiveUsage{{Input: 80001, Output: 6001, Complete: true}}, Checks: map[string]provider.LiveObservation{}}} |
| + err := x.calibration() |
| + if err == nil { |
| + t.Fatal("insufficient funding did not print rerun values") |
| + } |
| + for _, part := range []string{"JobInput=3703000", "JobOutput=299000", "ProjectInputHeadroom=3703000", "ProjectOutputHeadroom=299000", "TeamInputHeadroom=3703000", "TeamOutputHeadroom=299000"} { |
| + if !strings.Contains(err.Error(), part) { |
| + t.Fatal("missing exact rerun value", part, err) |
| + } |
| + } |
| + if x.d.cfg.Funding != f { |
| + t.Fatal("limits changed automatically") |
| + } |
| +} |
| + |
| +func TestClaudeRecoveryHookInvalidatesEarlierPass(t *testing.T) { |
| + for _, subtype := range []string{"hook_started", "hook_progress", "hook_response", ""} { |
| + t.Run(subtype, func(t *testing.T) { |
| + settings := json.RawMessage(`{"disableAllHooks":true,"enabledPlugins":{"agents-md@builtin":false,"plugin-authoring@builtin":false}}`) |
| + mount := claudeSettingsReadback{Settings: settings, ReadOnly: true, SHA256: provider.DigestDirectEvidence(settings), ExpectedSHA256: provider.DigestDirectEvidence(settings)} |
| + init := json.RawMessage(`{"type":"system","subtype":"init","claude_code_version":"2.1.312","plugins":[],"skills":[],"slash_commands":[]}`) |
| + x := exercise{root: t.TempDir(), claudeSettings: []claudeSettingsReadback{mount}, evidence: provider.DirectEvidence{Provider: "claude", Checks: map[string]provider.LiveObservation{}}} |
| + if err := x.finishClaudeHooks([]json.RawMessage{init}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if x.evidence.Checks["no-hooks-plugins"].Status != "pass" { |
| + t.Fatal("initial hook evidence failed") |
| + } |
| + frames := []json.RawMessage{init} |
| + if subtype != "" { |
| + frames = append(frames, marshal(map[string]string{"type": "system", "subtype": subtype})) |
| + } |
| + if err := extendRecoveryHooks(x.root, &x.evidence, []claudeSettingsReadback{mount}, frames); err != nil { |
| + t.Fatal(err) |
| + } |
| + if (x.evidence.Checks["no-hooks-plugins"].Status == "pass") != (subtype == "") { |
| + t.Fatal("recovery hook verdict wrong", subtype) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/directlive/subscription.go b/internal/directlive/subscription.go| new file mode 100644 |
| index 00000000..6a5c6877 |
| --- /dev/null |
| +++ b/internal/directlive/subscription.go |
| @@ -0,0 +1,68 @@ |
| +package directlive |
| + |
| +import ( |
| + "encoding/json" |
| + "os" |
| + "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/runner" |
| +) |
| + |
| +func (d *driver) subscriptionCurrencyEvidence() (bool, any) { |
| + raw, err := os.ReadFile(d.policyPaths.AccountBindingsPath) |
| + var rows []runner.AccountBinding |
| + ok := err == nil && json.Unmarshal(raw, &rows) == nil && len(d.cfg.Bindings) > 0 && !d.currencyCap && !currencyCapSignal(raw) |
| + bindings := map[string]string{} |
| + for _, entry := range d.cfg.Bindings { |
| + matches := 0 |
| + for _, row := range rows { |
| + b := entry.Binding |
| + if row.ID != b.ID { |
| + continue |
| + } |
| + matches++ |
| + bindings[b.ID] = row.Kind |
| + ok = ok && row.Kind == "subscription" && row.Provider == b.Provider && row.AccountID == b.AccountID && row.ProviderHome == b.Home && row.Model == entry.Model |
| + } |
| + ok = ok && matches == 1 |
| + } |
| + // The authorized funding schema contains only call, token and time bounds. |
| + funding := marshal(d.cfg.Funding) |
| + ok = ok && !currencyCapSignal(funding) |
| + return ok, map[string]any{"binding_kinds": bindings, "funding": d.cfg.Funding, "currency_cap_observed_or_configured": d.currencyCap || currencyCapSignal(raw), "funding_has_currency_field": currencyCapSignal(funding)} |
| +} |
| + |
| +// Costs reported for display do not impose a cap. Inspect structured keys and |
| +// provider result subtypes, never model prose that happens to mention a cap. |
| +func currencyCapSignal(raw json.RawMessage) bool { |
| + var value any |
| + if json.Unmarshal(raw, &value) != nil { |
| + return true |
| + } |
| + var walk func(any) bool |
| + walk = func(v any) bool { |
| + switch node := v.(type) { |
| + case map[string]any: |
| + for key, child := range node { |
| + k := strings.ToLower(strings.NewReplacer("_", "", "-", "").Replace(key)) |
| + if k == "currency" || k == "currencycap" || k == "currencylimit" || k == "maxcurrency" || k == "maxbudgetusd" || k == "budgetusd" || k == "costcap" || k == "costlimit" || k == "maxcost" { |
| + return true |
| + } |
| + if key == "subtype" && child == "error_max_budget_usd" { |
| + return true |
| + } |
| + if walk(child) { |
| + return true |
| + } |
| + } |
| + case []any: |
| + for _, child := range node { |
| + if walk(child) { |
| + return true |
| + } |
| + } |
| + } |
| + return false |
| + } |
| + return walk(value) |
| +} |
diff --git a/internal/directlive/testdata/fake-cli.py b/internal/directlive/testdata/fake-cli.py| index ed376b07..7a0056bc 100644 |
| --- a/internal/directlive/testdata/fake-cli.py |
| +++ b/internal/directlive/testdata/fake-cli.py |
| @@ -81,7 +81,7 @@ for line in sys.stdin: |
| session=req['session_id'] |
| prompt=req['message']['content'] |
| tools=[name for name in sys.argv[sys.argv.index('--tools')+1].split(',') if name]+mcp() |
| - emit({'type':'system','subtype':'init','session_id':session,'claude_code_version':'2.1.312','model':'fixture-model','permissionMode':'default','tools':[t for t in tools if t!='mcp__equipo__permission'],'skills':[],'plugins':[],'mcp_servers':[{'name':'equipo','status':'connected'}]}) |
| + emit({'type':'system','subtype':'init','session_id':session,'claude_code_version':'2.1.312','model':'fixture-model','permissionMode':'default','tools':[t for t in tools if t!='mcp__equipo__permission'],'skills':[],'plugins':[],'slash_commands':[],'mcp_servers':[{'name':'equipo','status':'connected'}]}) |
| if 'Certification action: native-' in prompt: |
| allow='native-allow' in prompt |
| command='printf equipo-cert-'+('allow' if allow else 'deny') |
diff --git a/internal/directlive/turn.go b/internal/directlive/turn.go| index 41079f5a..8c1da3d6 100644 |
| --- a/internal/directlive/turn.go |
| +++ b/internal/directlive/turn.go |
| @@ -10,6 +10,7 @@ import ( |
| "context" |
| "encoding/json" |
| "fmt" |
| + "strings" |
| "time" |
| ) |
| @@ -61,6 +62,12 @@ func (x *exercise) open(ctx context.Context, tool string) error { |
| x.proxy.Close() |
| return err |
| } |
| + if err = x.readClaudeSettings(ctx); err != nil { |
| + x.launcher.Close(context.Background(), x.session) |
| + x.proxy.Close() |
| + return err |
| + } |
| + x.d.currencyCap = x.d.currencyCap || currencyCapSignal(x.launch.Policy.Settings) || strings.Contains(string(x.launch.Policy.Manifest), "--max-budget-usd") |
| x.events, err = x.launcher.Events(ctx, x.session) |
| x.binding.Session = x.session |
| x.binding.Agent.AgentID = x.session.AttemptKey |
| @@ -93,6 +100,7 @@ func (x *exercise) turn(ctx context.Context, prompt string) ([][]byte, error) { |
| return frames, fmt.Errorf("turn-%d-ended: %w", x.sequence, provider.ErrUncertain) |
| } |
| frames = append(frames, append([]byte(nil), ev.Payload...)) |
| + d.currencyCap = d.currencyCap || currencyCapSignal(ev.Payload) |
| usage, err := x.journal.ObserveDirect(ctx, x.session, ev) |
| if err != nil { |
| return frames, err |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 36e8b9d6..4846eb79 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -11,6 +11,7 @@ import ( |
| // App-owned runtime strings belong here, including boot diagnostics. |
| // Existing copy accepted for now by Paul, 2026-11-04; new entries stay marked pending. |
| const ( |
| + CopyCalibrationFunding = "calibration funding is too low; rerun with JobInput=%d JobOutput=%d ProjectInputHeadroom=%d ProjectOutputHeadroom=%d TeamInputHeadroom=%d TeamOutputHeadroom=%d: %w" // COPY REVIEW REQUIRED: Round 3 funding guidance. |
| copyObserverFailure = "The live update could not be sent. The change was saved." |
| copyDecisionOwnerAssigned = "Reassign this person's project decisions before removing them." |
| copyBindingInUse = "Another project uses this repository and app. Choose a different pair." |
| @@ -20,9 +21,8 @@ const ( |
| copyMissingStage = "The sign-in layout is missing. Check the Rastrillo installation." |
| copyInvalidRoot = "The app handler is missing. Configure the Equipo app before serving." |
| - copyRunnerPending = "Waiting for you to approve this machine in your browser." |
| - copyRunnerRateLimited = "Too many attempts. Wait before trying again." |
| - |
| + copyRunnerPending = "Waiting for you to approve this machine in your browser." |
| + copyRunnerRateLimited = "Too many attempts. Wait before trying again." |
| copyBrand = "Equipo" |
| copyRenderFailure = "Something went wrong. Try again." |
| copyMissingKey = "EQUIPO_INSTANCE_KEY is required." |
diff --git a/internal/tryequipo/funding_test.go b/internal/tryequipo/funding_test.go| new file mode 100644 |
| index 00000000..cb9b80e3 |
| --- /dev/null |
| +++ b/internal/tryequipo/funding_test.go |
| @@ -0,0 +1,38 @@ |
| +package tryequipo |
| + |
| +import ( |
| + "bytes" |
| + "os" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestFundingProposedDefaults(t *testing.T) { |
| + for _, saved := range []string{"fresh", "legacy", "custom"} { |
| + t.Run(saved, func(t *testing.T) { |
| + values := map[string]string{} |
| + if saved == "legacy" { |
| + values = map[string]string{"InputTokens": "10000000", "OutputTokens": "1000000", "JobInput": "2300000", "ProjectInputHeadroom": "2300000", "TeamInputHeadroom": "2300000"} |
| + } |
| + if saved == "custom" { |
| + values["JobInput"] = "3000000" |
| + } |
| + w := Wizard{Root: t.TempDir(), Input: strings.NewReader(strings.Repeat("\n", 10)), Output: &bytes.Buffer{}, State: State{Values: values}} |
| + if err := os.Chmod(w.Root, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + w.init() |
| + f, err := w.funding() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := int64(5750000) |
| + if saved == "custom" { |
| + want = 3000000 |
| + } |
| + if f.JobInput != want || f.ProjectInputHeadroom != 5750000 || f.TeamInputHeadroom != 5750000 || f.JobOutput != 230000 || f.InputTokens != 50000000 || f.OutputTokens != 2000000 || f.Calls != 500 || f.Seconds != 7200 { |
| + t.Fatalf("funding: %+v", f) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/tryequipo/run.go b/internal/tryequipo/run.go| index 54ca8ef4..65a9c78f 100644 |
| --- a/internal/tryequipo/run.go |
| +++ b/internal/tryequipo/run.go |
| @@ -219,13 +219,15 @@ func (w *Wizard) funding() (provider.LiveFunding, error) { |
| Key string |
| Value *int64 |
| Default int64 |
| + Legacy int64 |
| }{ |
| - {"Calls", &f.Calls, 500}, {"InputTokens", &f.InputTokens, 10000000}, {"OutputTokens", &f.OutputTokens, 1000000}, {"Seconds", &f.Seconds, 7200}, |
| - {"JobInput", &f.JobInput, 2300000}, {"JobOutput", &f.JobOutput, 230000}, {"ProjectInputHeadroom", &f.ProjectInputHeadroom, 2300000}, {"ProjectOutputHeadroom", &f.ProjectOutputHeadroom, 230000}, {"TeamInputHeadroom", &f.TeamInputHeadroom, 2300000}, {"TeamOutputHeadroom", &f.TeamOutputHeadroom, 230000}, |
| + {"Calls", &f.Calls, 500, 0}, {"InputTokens", &f.InputTokens, 50000000, 10000000}, {"OutputTokens", &f.OutputTokens, 2000000, 1000000}, {"Seconds", &f.Seconds, 7200, 0}, |
| + {"JobInput", &f.JobInput, 5750000, 2300000}, {"JobOutput", &f.JobOutput, 230000, 0}, {"ProjectInputHeadroom", &f.ProjectInputHeadroom, 5750000, 2300000}, {"ProjectOutputHeadroom", &f.ProjectOutputHeadroom, 230000, 0}, {"TeamInputHeadroom", &f.TeamInputHeadroom, 5750000, 2300000}, {"TeamOutputHeadroom", &f.TeamOutputHeadroom, 230000, 0}, |
| } |
| for _, e := range entries { |
| def := strconv.FormatInt(e.Default, 10) |
| - if v := w.State.Values[e.Key]; v != "" { |
| + // Re-propose the old defaults in the prompt; custom limits remain selected. |
| + if v := w.State.Values[e.Key]; v != "" && (e.Legacy == 0 || v != strconv.FormatInt(e.Legacy, 10)) { |
| def = v |
| } |
| v, err := w.ask(e.Key, def) |