carlos / platform Public

Add reviewed team-service design and stabilize reload test

Squashed from team-service-design into main.
codex agent, operated by paul@keymail.dev 21738194abce6f8ff82c2d3fa49a90fd502ce905 parent 79d9d6a
5 files changed, +900 −3
  • docs/superpowers/plans/2026-11-01-team-service.md +286 −0
  • docs/superpowers/specs/2026-11-01-team-service-design.md +462 −0
  • docs/superpowers/specs/2026-11-01-team-service-integration-audit.md +59 −0
  • docs/superpowers/specs/2026-11-01-team-service-review.md +75 −0
  • internal/edge/localhold_probed_test.go +18 −3

CI passed — run details

diff --git a/docs/superpowers/plans/2026-11-01-team-service.md b/docs/superpowers/plans/2026-11-01-team-service.md
new file mode 100644
index 000000000..0a938b7a3
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-01-team-service.md
@@ -0,0 +1,286 @@
+# Team service implementation plan
+
+Status: independently reviewed; ready for the bounded local prototype.
+No implementation has started. Live milestones retain their explicit gates.
+Spec: [team service design](../specs/2026-11-01-team-service-design.md).
+
+This plan is for implementation agents. Complete one milestone before
+expanding authority. New paths and API names below are proposals; existing
+integration points must be revalidated against the implementation branch.
+All source changes use isolated branches and review requests. Follow the
+repository's current forge and CI configuration, not an obsolete remote name.
+
+Execution order: first M0, M1 and M5's fixture workflow, exposed through a
+local test driver. This is the bounded prototype. M2, M3 and M4 gate the live
+pilot; console UI and real connections do not delay the first fixture result.
+The local driver is a test harness, not a shipped box-local `carlos` command.
+
+## M0: contracts and integration fixtures
+
+Create `internal/team/model.go`, `policy.go` and fixture-only adapter
+interfaces. Add no public routes, real credentials or background jobs.
+
+Define typed Job, Step, Attempt, Action, Event, Artifact, Memory and Grant
+records from the spec. Model authorization results, typed waiting reasons,
+usage (including unknown usage) and adapter capability declarations. Specify
+versioned JSON shapes, maximum request/event/artifact sizes and schema
+migrations. Unknown versions, operations and policy fields fail closed.
+Define account-scoped conversation events separately from job events. Grants
+are authoritative in the console; local records contain only references and
+audit snapshots. The fake Authority supplies the same revocation contract.
+
+Define these interfaces around explicit account and job scope:
+
+| Interface | Contract |
+|---|---|
+| Authority | Validate actor/target/operation against a current grant; never resolve a service's minter as its authority |
+| Provider | Start bounded turn, consume events/usage, cancel, query outcome if supported; report actual model/effort |
+| Runner | Claim/renew/stop/status, confined execution and artifact export; fence on every request |
+| Action adapter | Classify replay safety, execute immutable request, reconcile receipt/key |
+| Work tracker | Read external work and publish milestones; does not own attempt leases |
+| Verifier | Evaluate immutable evidence against the exact candidate SHA |
+
+Implement fakes with deterministic clock, crash points, duplicate deliveries,
+lost replies, delayed billing and provider unavailability. The Oficina seam
+test uses a synthetic reconciliation task with evidence requirements and no
+Git/app fields. Do not build a business connector in this phase.
+
+Acceptance: schemas and policy tests prove cross-account requests and unknown
+actions are refused; both software and business-shaped fixtures use the same
+job contract. No live network needed.
+
+## M1: durable execution and budget ledger
+
+Create `internal/team/store.go`, `scheduler.go`, `budget.go`, `actions.go`
+and `outbox.go`, with focused tests. Use the module's existing SQLite driver.
+Keep transactions short and perform remote calls after intent persistence.
+
+Persist job revisions/events atomically. Claim steps conditionally and issue
+fences. Enforce step dependencies, attempt caps and job/account concurrency.
+Implement reservation, settlement and uncertain-outcome handling before
+connecting a real provider. Retain reservations across restarts.
+
+Cancellation blocks admission first, fences old attempts and records runner
+stop acknowledgements. Recovery checks outstanding actions before requeueing.
+Provide an explicit restore-quarantine state for future deployment recovery.
+Outbox retries use stable logical keys and never silently drop failed sync.
+
+Acceptance includes process termination at every boundary: after intent,
+after reservation, after dispatch, before receipt, after receipt and before
+outbox acknowledgement. No test may assume a timeout means no remote effect.
+Test renewal after expiry, even by the same runner. Startup pauses admission,
+checks the external incarnation marker and revalidates grants with Authority.
+Missing/unclean markers cause quarantine; only successful reconciliation can
+clear it automatically. A later hosted test must exercise the activator's
+automatic DB restore. Console restore invalidates the grant authority epoch.
+Provide a restricted audited settlement for irreconcilable usage; unknown
+usage is conservatively charged, never silently released as free capacity.
+Run focused tests and targeted race tests for claim/budget contention.
+
+Pin transaction order in tests: online versioned authority admission, then
+one transaction checking stored fence/revision/grant version/state/budget and
+recording dispatching. Admissions expire after five seconds. Claim/cancel
+mutate the same row; cancelled jobs cannot be reclaimed. New claims create
+new attempts/workspaces, with only broker-accepted checkpoints importable.
+Renewals recheck authority; observed revocation cancels the attempt. Charge
+late usage against open reservations even after cancellation, deduplicated by
+receipt. Give outbox delivery the same replay/authority path as actions.
+The per-call output ceiling is 4,000 generated tokens, including reasoning.
+
+## M2: authority broker and runner isolation
+
+Create `internal/team/broker.go` and a separate runner supervisor entry point
+under `cmd/team-runner`. Broker and runner communicate over an authenticated
+protocol with version and payload limits. A runner is enrolled for explicit
+accounts/capabilities; polling never lists other accounts' jobs.
+
+The supervisor creates one isolated workspace per attempt with an explicit
+environment, working directory, process/memory/disk limits and egress policy.
+Neither repository hooks nor generated commands can read host credentials or
+reach production, metadata services or local control sockets. A worker's
+broker handle grants only its current attempt and expires with its lease.
+
+Choose an existing sandbox facility only after negative tests prove the
+required isolation on the selected machine. If CARLOS has no supported way
+to provision or manage it, specify/build that product capability; do not add
+an SSH/SSM prerequisite. A local test adapter may use synthetic isolated
+fixtures, but it must not be advertised as production-safe execution.
+
+Acceptance: traversal/symlink escape, hostile hooks, stale fence, forged
+runner identity, wrong account, copied capability, direct network bypass,
+child process survival, disk exhaustion and revoked grant are all refused or
+contained. Failure to establish confinement blocks the live pilot.
+
+For the first shared-machine runner, use unprivileged bubblewrap with private
+user/mount/PID/network namespaces and an attempt-scoped broker Unix socket.
+Kill the whole PID namespace or delegated cgroup and verify it is empty;
+process-group termination is not sufficient. Prove this with a setsid child.
+Do not require sudo or new root services. Inspect the existing CARLOS
+isolated-exec facilities before a later hosted implementation. Preserve the
+machine's Go cache defaults and validate read-only cache sharing/overlays.
+
+## M3: console authority, API and conversation
+
+Add proposed `internal/console/apiteam.go` and tests, `internal/team/http.go`,
+`conversation.go`, `memory.go`, `cmd/team/main.go`, and CLI client/dispatch
+files following existing root command conventions.
+
+Implement the short-lived console delegation and online introspection
+contract before forwarding browser or CLI requests. Test expiry, revocation,
+audience, account, operation, spoofed headers, CSRF and console outage.
+Persistent job grants must remain independently revocable and owner-bounded.
+Do not grant existing service roles new authority through a wildcard route.
+Use person-only registrations and extend the existing `closedDoors` equality
+test. It already permits explicit empty role sets; no new role vocabulary is
+needed for these doors. A separate authenticated service endpoint performs
+introspection, without granting Admin automatic access.
+Handlers must also resolve a person and check account membership. Update the
+route test's expected count and wildcard substitution fixtures as necessary.
+
+Proposed remote API operations: create/list/get/cancel job; append/read
+conversation events; view evidence/usage; list/correct/delete preferences;
+view/revoke job grants. Use caller-generated idempotency keys for writes and
+revision checks for updates. Pagination and event cursors are account-scoped.
+Approval records bind an exact action/target/payload and expire; changing an
+action requires fresh authorization under the applicable policy.
+
+Build the smallest console view: conversation, work list and job detail.
+Provide proposed `carlos team` operations through the console API; no local
+DB mode. Add headings for the implemented verbs to `docs/site/cli.md`.
+Run the existing copy-review pipeline for all actual UI/CLI explanatory copy
+and docs prose. The current spec is an agent implementation contract, not
+approved product wording.
+
+Memory tests cover access revocation after caching, inferred versus explicit
+preferences, correction/deletion invalidation and summary provenance. First
+use synthetic data; privacy/retention and encryption are gates for real data.
+Test account switching in one conversation and provider-session isolation:
+recent history must exclude another account even when the user can access
+both, unless all source and destination policies permit that transfer.
+
+Acceptance: a user can report and inspect a fixture job from browser or CLI,
+close/reopen the conversation, cancel it and inspect evidence. A foreign user
+cannot infer job existence through lists, streams, artifacts or error shapes.
+
+## M4: supported integrations
+
+Add adapters under `internal/team/integrations` with recorded contract tests.
+Preserve a fake option for every integration so tests remain hermetic.
+
+1. Use metered API authentication for the first live providers. Prove bounded
+ calls, event parsing, cancellation, usage and confined tools before live
+ work. Keep another provider for independent review; unavailable review
+ produces a visible waiting state. Confirm provider account selection and
+ model explicitly. Do not silently switch accounts or providers on limits.
+ Subscription-CLI integration is deferred until its enforceable bounds are
+ documented. Use isolated per-attempt harness home/config/session storage;
+ include all retained provider state in deletion and retention tests.
+2. Bind one Amadan repository. Reuse discussions, dependencies, branch review
+ and handoff APIs. Audit write idempotency; add a supported operation-key
+ contract where absent, or stop on uncertain outcomes. Do not edit Amadan's
+ database or repurpose CI claims as general-purpose job leases.
+ Use a dedicated disclosed agent whose verified writer reach is limited to
+ the pilot repo. If that scope is unavailable, implement it upstream first.
+ Put operation IDs in created records for positive read-back evidence;
+ absence of a marker alone never permits a replay. Defer payload rewrites
+ without concurrency protection.
+3. Implement the configured forge's branch/review adapter. Publishing uses a
+ broker-held credential, exact target/ref/head checks and an operation
+ receipt. No unrestricted push/merge credential reaches repository code.
+ The first live forge is Amadan. Defer the GitHub adapter. Require branch CI
+ with no production credentials or deployment hooks, validate trusted CI
+ definitions before publication and pin default-branch protections.
+4. Add a minimal CARLOS read-only diagnostic grant before a monitoring
+ connector. Existing instance/operate roles are not a read-only grant.
+ Preview creation is optional for the first bug and needs a separately
+ scoped temporary-app/expiry policy before use.
+
+Acceptance: contract tests pin methods, auth and failure semantics. An
+integration gap becomes a dependency with its own change request, not an
+adapter that bypasses the platform. Persist upstream IDs and commit hashes.
+
+## M5: software workflow and experiment
+
+Implement a capability definition for reproduce -> implement -> review ->
+verify -> publish. Definitions name tools, evidence predicates and model
+routing policy. They do not contain permanent model conversations.
+
+Start with an intentionally broken local fixture. Preserve base/candidate
+snapshots and use trusted check definitions. Verify the original symptom on
+both. Test reviewer rejection, stale review after edits, failing checks,
+changed upstream head and publication acknowledgement loss. A successful
+result names the exact candidate and includes all required evidence.
+Freeze the reproduction artifact by hash before implementation, store it
+outside the worker's writable checkout and run that exact copy on base and
+candidate. A test that weakens/replaces it must be rejected. The fixture
+workflow runs after M1, before live dependencies.
+Compile errors, skipped/missing tests and zero matched tests are invalid
+reproduction evidence, never a passing candidate or the expected base failure.
+
+Before live use, prepare the pilot manifest: selected account/app/repository,
+machine, approved providers/data destinations, connection method, bounded
+budgets, permitted branch operations, retention and expiry. Set all other
+operations to deny. The user approves any remaining live authority here,
+after the fixture result and isolation evidence are reviewable. Existing
+explicit scope remains valid; do not ask again for every permitted call.
+Name the manifest approver, broker-credential operator and runner-machine
+owner. Classify real repository/conversation data and state retention for
+raw logs, artifacts, harness sessions and provider-hosted state. Record which
+bounds are enforced, not just estimated. API connections require their own
+explicit billing scope; design-review CLI credentials are not that scope.
+
+Run a small set of real bugs and compare with the current manual workflow.
+Record human intervention minutes, accepted/rejected fixes, elapsed time,
+tokens/cost including coordination and review, rework and regressions. Keep
+subscription usage distinct from metered API charges. Do not merge or deploy
+as part of this pilot.
+
+## Required failure matrix
+
+| Case | Required result |
+|---|---|
+| Two runners claim one step | One accepted current fence |
+| Old runner acts after lease expiry | Broker refuses; old artifacts cannot satisfy evidence |
+| Same runner renews after deadline | Renewal refused; a new claim gets a new fence |
+| Reclaimed attempt reuses stale workspace | Rejected; only accepted checkpoints can be imported |
+| Remote action succeeds, response lost | Reconcile or wait; never blind replay |
+| Cancel during remote action | Stop new work; show in-flight effect separately |
+| Scheduler/runner restarts | Restore intents/reservations before admission |
+| Backup predates revocation | Quarantine; stale grants cannot resume work |
+| Concurrent jobs/children reserve final budget | At most available capacity admitted |
+| Usage missing or price unknown | Retain reservation or refuse; no free retry assumption |
+| Usage arrives after cancellation | Open reservation settles exactly once; job outcome stays terminal |
+| Account access revoked after caching | No cached content returned or new actions admitted |
+| Log/support text requests more authority | Remains untrusted evidence; policy unchanged |
+| Reviewer absent or same implementation run | No verified success |
+| Candidate/check definitions change | Previous verification invalidated |
+| Implementer replaces reproduction | Hash-pinned reproduction still fails; no success |
+| Reproduction compiles badly, skips or matches no test | Invalid evidence; cannot satisfy success |
+| Candidate changes remote CI to obtain secrets | Publication refused before triggering CI |
+| Amadan unavailable or ambiguous write | Work visibly waiting/sync pending; no false completion |
+| Worker attempts host filesystem/network access | Isolation blocks it; no credential exposure |
+| Worker forks a detached setsid child | Entire containment unit is stopped |
+| Account switch or provider resume carries foreign context | Assembly/resume refused or scoped content excluded |
+| Repeated metric signal | One investigation per dedupe/cooldown policy, when enabled later |
+
+## Validation, rollout and deferred work
+
+For source implementation, use focused tests while iterating and run the
+repo's complete required build/vet/test/format/cross-compile gate before
+landing. Tests invoking `carlos` use `carlosTestEnv` and a scratch cwd. Leave
+Go cache defaults alone. No integration test may discover a real login from
+HOME or ancestor `.carlos/config` files.
+
+Ship the capability disabled by default. A service outage leaves app serving
+and ordinary CARLOS administration working. Additive schemas and API versions
+must allow stopping the service without breaking the console. Rollback pauses
+admission first; do not roll a binary back across an incompatible job schema.
+
+This design-only branch changes no executable code; validate document links,
+source references, whitespace, scope consistency and independent review. Do
+not claim implementation tests or live results for these documents.
+
+Deferred: remote sandbox vendor selection, multi-region scheduling, broad
+autonomous remediation, automatic merge/deploy, customer-support connectors,
+business connectors, model benchmarking and a team flow visualization. The
+first experiment must establish useful work and recoverability before these.
diff --git a/docs/superpowers/specs/2026-11-01-team-service-design.md b/docs/superpowers/specs/2026-11-01-team-service-design.md
new file mode 100644
index 000000000..107b914e0
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-01-team-service-design.md
@@ -0,0 +1,462 @@
+# Team service: delegated work for CARLOS and Oficina
+
+Status: independently reviewed implementation contract; ready for the local
+prototype. Live use remains gated by the implementation plan.
+Date: 2026-11-01.
+Companion: [implementation plan](../plans/2026-11-01-team-service.md).
+Evidence: [integration audit](2026-11-01-team-service-integration-audit.md) and
+[independent review](2026-11-01-team-service-review.md).
+
+## Outcome and scope
+
+Build an integrated CARLOS capability that carries a request from a main
+conversation to a verified result. Run orchestration as a separate service.
+CARLOS supplies software operations; Oficina can later supply business
+operations using the same job, authority and evidence contracts.
+
+The first experiment accepts one bug in an explicitly selected repository,
+reproduces it, prepares a change, obtains independent review, runs the
+repository's checks and opens a reviewable change request. It stops there.
+Automatic merge, deployment, production infrastructure changes, customer
+messages and financial actions are outside the experiment's grant.
+
+The first deliverable is this spec and its reviewed implementation plan.
+It does not authorize deploying the service or enrolling machines/accounts.
+Implementation starts with fake providers and local fixtures. A live pilot
+needs a concrete target repository, credential connection and finite budget.
+
+Product decisions from the conversation:
+
+- One main conversation; optional focused job conversations. Session and
+ context-window management are internal work.
+- Keep anthropomorphism low. Use coordinator, capability, job, run and
+ evidence. No invented staff biographies, personalities or staged dialogue.
+- Integrate with the existing console login and accounts. The service is
+ independently deployable; the edge does not depend on its availability.
+- Preferences are inspectable, sourced and correctable. Inferred taste does
+ not grant authority.
+- Use supported CARLOS API/CLI operations. Missing functionality is a product
+ gap to implement, never permission to use AWS, a box shell or a local DB.
+- Autonomous improvement is a later trigger for the same job workflow, with
+ explicit policy and measured outcomes.
+
+## Components and ownership
+
+Implement the first service in the platform Go module as `cmd/team` with
+domain code under `internal/team`. It has its own process and application
+database. Existing `cmd/console` and the `carlos` CLI are clients. These are
+proposed paths, not commands or packages that exist today.
+
+```mermaid
+flowchart LR
+ UI[CARLOS console and CLI] --> C[Coordinator and context selection]
+ O[Future Oficina client] --> C
+ C --> J[Durable jobs and scheduler]
+ J --> B[Policy and action broker]
+ J --> R[Isolated runners]
+ B --> P[Provider adapters]
+ B --> A[Amadan and forge APIs]
+ B --> K[CARLOS APIs]
+ R --> B
+```
+
+The coordinator proposes structured jobs and tool requests. Ordinary code
+validates them, admits work and enforces limits. A model cannot mint grants,
+raise a budget, edit enforcement policy or declare its own review sufficient.
+
+The team database is authoritative for execution state, reservations, action
+receipts and job events. Amadan is authoritative for its discussions, tasks,
+dependencies and reviews. Store links and publish selected execution events
+through an outbox; do not make two writable copies of the same state.
+An Amadan task status is not an execution lock or an authorization decision.
+
+Each job belongs to exactly one CARLOS account. An explicit binding maps it
+to a repository and any app. Never infer a mapping from matching names or
+email addresses. Cross-account programmes consist of separately authorized
+child jobs. Their summaries remain account-labelled and access-filtered.
+
+One personal conversation can navigate several accounts. Retrieval checks
+current access before returning any account content, including titles,
+counts, citations, summaries and cached context. A turn must select its
+account before model context is assembled. A cross-account overview merges
+only separately authorized summaries; it does not silently send all private
+contexts to every worker.
+
+Conversation events carry their own ID, sequence, owner, account/personal
+scope and source references. Generated content inherits its sources' scope;
+an account-derived summary cannot become personal memory. Build a turn only
+from personal and selected-account events. Multi-account events require all
+source grants and destination permissions, or are omitted. Provider state
+follows the same boundary. The live pilot uses one account only.
+
+## Records and invariants
+
+Use SQLite transactions in the service's application database, following the
+platform's single-writer app contract. The pilot proves process-crash recovery;
+it does not claim HA or host-loss recovery. Deployment durability and restore
+procedures are a separate release gate.
+
+| Record | Required fields and constraints |
+|---|---|
+| Job | ID, account, requester, target binding, outcome, evidence requirements, policy version, state, revision, budget ID, parent ID, created/updated timestamps |
+| Step | Job ID, capability/version, dependencies, state, expected input/artifact hashes; dependency graph must be acyclic |
+| Attempt | Step ID, attempt number, runner ID, fence generation, lease deadline, provider/model/effort, usage, terminal result; one active attempt per step |
+| Action | Account/job/step, logical action key, immutable canonical arguments hash, fence, grant reference, reservation, state, external receipt |
+| Event | Job-local increasing sequence, type, actor, payload reference, source timestamp; appended in the same transaction as state changes |
+| Artifact | Account/job, content hash, media type, byte limit, provenance, visibility, storage reference; no credentials |
+| Memory | Subject, account or personal scope, assertion, explicit/inferred status, source references, version, expiry/deletion state |
+| Grant | Issuer, actor, account, app/repo targets, allowed operations, provider/data destinations, budget, expiry, revocation/version; separate from memory |
+| Outbox | Unique action/event key, destination, delivery state, last error, external receipt |
+
+Job states: `queued`, `running`, `waiting`, `verifying`, `succeeded`, `failed`,
+`cancelled`. Waiting has a typed reason such as approval, provider limit,
+budget, dependency, runner unavailable or uncertain external outcome.
+Only the scheduler writes state transitions. Every transition checks the
+expected revision and appends an event atomically. Terminal jobs are immutable;
+additional work is a linked new job. Late usage updates the separate ledger
+and audit stream without changing a terminal job's outcome.
+
+Success requires the configured evidence predicate. For a software fix that
+includes a failing reproduction on the base, a passing reproduction on the
+candidate, required checks, independent review and the exact published head.
+A model's narrative or a successful provider exit code cannot satisfy this.
+Any changed candidate invalidates the previous checks and review.
+Freeze the reproduction artifact by content hash before implementation.
+Verification obtains that exact artifact from the trusted artifact store,
+outside the implementation workspace. A candidate cannot replace or weaken
+it; an authorized reproduction change restarts reproduction and review.
+Compile errors, skips, missing targets and zero matched tests count as neither
+the expected base failure nor a candidate pass. Run the frozen artifact under
+trusted base-revision check definitions and record the actual test count.
+
+## Leases, external actions and cancellation
+
+A runner claims a step transactionally. The initial lease is 60 seconds and
+renews every 15 seconds. A successful new claim increments a monotonically
+increasing fence. Every accepted event, artifact registration and broker
+action carries that fence. Stale runners cannot publish accepted results or
+begin new external actions. A runner stops work when renewal fails; the
+broker independently enforces the deadline.
+Renewal after the deadline is refused even to the previous holder. A fresh
+claim is required; artifacts made during the gap cannot inherit its new fence.
+A fresh claim creates a new Attempt and fresh workspace. Only previously
+accepted, hash-verified checkpoints may be imported through the broker; do
+not re-register files left by the expired worker. Enforce one active attempt
+with a partial unique index. The short lease may consume an attempt during a
+scheduler stall; tuning it later must preserve the same fencing semantics.
+
+Lease expiry does not prove a process stopped and does not undo an external
+request. Record an action intent and reserve its budget before dispatch.
+Retries keep the logical action key and canonical arguments, even when the
+attempt changes. A different payload under the same key is a conflict.
+
+Adapters must classify operations as read-only, externally idempotent,
+reconcilable by receipt/key, or unsafe to replay. Reconcile a lost response
+before dispatching again. If the external system cannot prove whether an
+operation happened, set `waiting/uncertain_external_outcome`; do not guess.
+This applies to discussions, comments, change requests and paid inference.
+The design promises controlled retries, not exactly-once external delivery.
+
+Cancel first revokes further admission and increments the fence, then asks
+the runner supervisor to terminate the attempt's whole containment unit
+(a delegated cgroup or private PID namespace, including detached children).
+A process-group kill alone is insufficient because a child can call setsid.
+Persist the stop
+request and its acknowledgement. Report cancellation complete only once the
+runner is confirmed stopped or isolated; report outstanding external effects
+and reservations separately. Do not declare an already-dispatched action
+reversed. A replacement attempt cannot conflict with an unresolved prior
+action or a worker whose resource use has not been contained.
+Claim and cancel update the same step row under the same revision guard.
+Cancel clears its holder, increments its fence and sets a non-claimable state;
+a concurrent claim cannot revive a cancelled job. Observed grant revocation
+triggers this cancel path, and renewal rechecks authority before extension.
+
+Scheduler startup reconciles attempts, actions and reservations before
+admitting replacements. Restoring a database backup starts in quarantine:
+no replay or autonomous writes until current grants and outstanding external
+effects have been reconciled. A restored local grant must never revive
+authority revoked outside that backup.
+All starts begin with admission paused and require fresh console validation
+of each continuing job grant. Keep a writer-incarnation/clean-shutdown marker
+outside the replicated application DB. A missing/mismatched marker or unclean
+shutdown enters recovery quarantine; ordinary crash recovery can clear it
+after online authority and action reconciliation. Uncertain effects remain
+waiting. The CARLOS activator can restore a missing DB automatically, so a
+restore test must exercise that path, not just an explicit import command.
+If the console authority store itself is restored, invalidate outstanding
+grants by rotating its authority epoch before enabling team admission. This
+restore procedure is a production release gate, not a claim of existing code.
+
+## Identity and enforcement
+
+The console remains the authority for CARLOS membership. The browser uses
+the existing same-origin console session and CSRF protection. The console
+proxies team requests after account checks; it does not give its cookie or
+session signing key to the team service. CLI requests follow the same gates.
+Preserve byte-identical scope refusals and the existing owner/fresh-auth order.
+
+Add an opaque, short-lived delegation and introspection contract to the
+console. Bind the delegation to the team-service audience, actor, account,
+target and permitted operation; store only its hash. The team service uses a
+separate transport identity to introspect it. Introspection checks expiry,
+revocation and current membership, and refuses on dependency failure. Do not
+trust an account/actor header supplied by the browser or a worker.
+
+Persistent job grants are separately recorded by an authorized person. They
+bind the finite job policy and are rechecked with current account membership
+at each broker admission. A normal user can grant only a subset of their own
+authority. Account-wide settings and standing autonomous policies require
+the account owner. Existing service roles must not silently gain team access.
+The new contract needs explicit console/API tests before a live integration.
+The console is the authoritative store for job grants and revocations; the
+team DB holds references and audit snapshots only. Every action admission
+revalidates online. Console failure pauses action admission and does not
+affect app serving. Team browser/CLI doors are person-only initially: register
+an empty `svcrole.Set{}` and add them to `closedDoors` in `svcroutes_test.go`.
+The existing coverage test already supports this exact closed-door list.
+Runner and service-introspection endpoints use their own audience-scoped
+transport identities; an existing Admin service role is not sufficient.
+Registration is only part of the gate: each person-only handler resolves the
+person and checks current account membership explicitly. Extend the existing
+route test's expected count and wildcard fixtures for new patterns.
+
+The broker holds connector credentials in protected storage outside worker
+filesystems. Workers receive an attempt-scoped broker handle, never a human's
+CLI credentials, provider login tokens, production environment or admin keys.
+The broker checks account, target, operation, current grant, fence and budget
+on every call, including calls suggested by retrieved text.
+
+Current CARLOS `instance` and `operate` roles are too broad for unattended
+read-only diagnostics. Add an explicitly read-only scope/role with a tested
+door catalogue, or a narrowly scoped delegation facility. Do not solve this
+by handing a worker an existing broad role and relying on its prompt.
+
+The pilot's allowlist permits repository reads, isolated edits/tests and
+broker-mediated publication to its selected review branch. It refuses main
+pushes, merge, deploy, credential creation, infrastructure, billing and
+customer communication. For remote changes, validate the repository, ref and
+candidate hash at the broker; disable untrusted git hooks and credential
+helpers in worker checkouts. No unrestricted shell with host network access.
+The broker's admitted/dispatching transition is the action's cancellation
+boundary. Recheck the current fence and online grant immediately before it;
+after that point cancellation reports an in-flight effect. A replacement
+cannot redispatch an unresolved logical action under a new key. Persist the
+step's intended logical operation identity before asking for execution.
+Order admission as follows: introspect Authority outside the DB transaction;
+receive its current grant version/epoch and an admission valid for at most
+five seconds; then transactionally compare the stored step fence, revision,
+locally observed grant version, job state and reservation before writing
+dispatching. Expired admissions require fresh introspection. Record the
+authority version used. A revocation concurrent with this sequence has a
+bounded race window; do not promise instant revocation. Renewals and the next
+admission observe it, with at most one lease period of continued local work.
+
+## Runners and provider connections
+
+Start with one trusted runner supervisor on one of docs-t1/tito-studio. Both
+are possible later placements, not automatically enrolled. A worktree is an
+edit boundary; use a tested sandbox to confine code and command execution.
+The supervisor controls process lifetime, filesystem mounts, network egress
+and CPU/memory/process/disk quotas. Workers cannot reach host HOME, other
+jobs, local daemon sockets, metadata services or the supervisor's credentials.
+Bind any local service to loopback or the explicitly selected Tailscale IP.
+
+For the shared-machine pilot, select unprivileged bubblewrap with private
+user/mount/PID/network namespaces. Mount only an attempt-scoped broker Unix
+socket for permitted external operations; an empty network namespace prevents
+direct egress. Verify actual namespace and resource-containment support before
+enrolment. Bubblewrap 0.11.0 is installed on docs-t1 and the unprivileged-userns
+setting is enabled; this is availability evidence, not an isolation test.
+No sudo or new root-managed units are part of this plan. Review CARLOS's
+existing isolated-exec implementation (`instancefs`, instance-control and
+instance unit templates) for later hosted runners; it is not automatically
+available to an unprivileged worker on these machines.
+
+Use default shared Go build caches where permitted by machine policy; do not
+create caches in `/tmp`. Repository code must not gain write access to a
+trusted cross-job cache: the runner needs a validated cache-sharing policy or
+an isolated writable layer. Scratch goes to disk and is cleaned after each
+attempt. Missing isolation is a refusal, not a fallback to an ordinary shell.
+Keep the machine's default Go cache unchanged. Expose a prevalidated cache
+read-only with an attempt-local writable overlay if needed; any module fetch
+uses a separately permitted broker path. Never share worker-writable cache
+content as trusted input to another job.
+
+Provider adapters implement start, streamed events, usage, cancel and resume
+capability discovery. Record the actual model and effort; never silently
+substitute another provider or send data to an unapproved destination.
+Use separate credentials for inference and deployment authority.
+
+Use officially supported provider authentication. Claude's unmodified CLI can
+use its own user-completed sign-in; a custom Claude API integration uses the
+user's API/cloud-provider credentials. Never collect subscription session
+tokens into the team database. Codex has documented app-server integration;
+confirm the chosen authentication mode's eligibility during implementation.
+An existing CLI login is not blanket permission to build a hosted credential
+relay. Open-weight models implement the same adapter and data-access contract.
+
+Select the first live adapter only after a capability probe verifies event
+format, cancellation, isolated tool execution, usage and authentication. Keep
+the provider harness outside the untrusted code sandbox. If tool calls cannot
+be intercepted and confined, that adapter is ineligible for autonomous runs.
+Remote runners use the same protocol; E2B and EC2 are deferred backend choices.
+
+The first live pilot uses metered API adapters, with per-request input/output
+limits, a currency cap and explicit provider connections. CLI subscription
+adapters remain a later capability: a harness that cannot bound its internal
+calls cannot claim enforcement of these token/currency ceilings. The native
+CLI accounts used to review this design do not authorize live pilot billing.
+Each harness has an isolated attempt-specific home/config/session directory;
+no user HOME or shared resume history. Credential delivery uses a supported
+connection mechanism outside worker reach. Harness transcripts, caches,
+provider-hosted session IDs and resume state are included in retention and
+deletion. Never resume a provider session into another job/account.
+
+## Budgets and context
+
+Reserve capacity before every provider request, tool action and child job.
+In one transaction, check both parent-job and account limits against spent
+plus reserved use. Settled child usage is charged once to the common ledger.
+Lost responses retain their reservation until reconciled. Retries, review,
+retrieval, summaries and coordinator turns are included, not hidden overhead.
+Reserve the request's maximum allowed usage before dispatch, then settle down
+to measured usage. Conversation turns use bounded conversation jobs charged
+to the same account ledger even before a software job exists. A restricted,
+audited operator settlement can close irreconcilable reservations using a
+conservative charge; it never turns unknown use into zero-cost retries.
+Accept settlement against an open reservation even after its attempt is
+cancelled or expired. Deduplicate settlements by provider receipt so late
+usage cannot disappear or be charged twice.
+
+Initial pilot ceilings, to be explicitly configured before live work:
+two concurrent attempts; depth one; two attempts per step; 24 provider calls;
+45 minutes per job and 20 per attempt; 200,000 total input tokens and 40,000
+total generated tokens, including reasoning; 32,000 input and 4,000 generated
+tokens per call. Reserve those per-call ceilings at the configured prices.
+API billing additionally requires a finite currency cap and versioned rate
+table. These numbers are proposed ceilings, not authorization to spend.
+
+An adapter must enforce a bounded request or be refused. Subscription usage
+is recorded as calls/tokens/time and reported separately from metered cost;
+do not invent a dollar value. If provider accounting cannot establish a hard
+financial bound, label the estimate and restrict the live pilot accordingly.
+Local cancellation cannot guarantee a provider stopped billing remotely.
+
+Persist original conversation events, then build each turn from a bounded
+recent window, relevant decision records and scoped retrieval. Summaries
+retain source references and can be regenerated. Immutable decisions and
+grants are never reconstructed from model summaries. A full context window
+creates a new bounded model turn, not a new conversation the user must manage.
+
+Explicit preferences may be reused within their scope. Inferred preferences
+remain tentative until confirmed and cannot widen access. Corrections and
+deletions invalidate derived summaries and retrieval caches; deletion also
+covers replicas/backups according to a documented retention policy. Until
+that policy and encryption are implemented, the fixture pilot uses synthetic
+data only. Keep secrets and raw customer-support content out of broad memory.
+The live manifest classifies repository code and conversation content and
+sets retention for artifacts, raw logs, harness state and provider retention.
+Encryption and this policy must be verified before real data is connected.
+
+## Amadan, verification and UI
+
+Keep execution claims in the scheduler. Amadan discussion claims are visible
+work ownership and do not replace fenced worker leases. Publish milestones
+through an outbox and show delivery failure. Account/repo bindings and current
+access are checked before every read and publication. A remote dependency
+closure can make work eligible; it cannot approve an action or enlarge scope.
+Outbox delivery uses the same action classification, reservation and
+reconcile-before-redeliver path as broker actions. A separate retry loop must
+not bypass replay safety or authority checks.
+
+Start with the configured forge's existing review mechanism. The platform
+checkout currently uses Amadan as `origin`; the infrastructure design repo
+uses GitHub. Do not hard-code GitHub for every job. A GitHub-backed target
+produces a PR; an Amadan-backed target uses its branch/review API. Repository
+rules and required CI apply to the exact candidate SHA. No merge in the pilot.
+Select Amadan as the first live forge; defer the GitHub adapter. This design
+and implementation live in carlos/platform on Amadan, per Paul's direction.
+Use a dedicated disclosed agent with writer reach limited to the
+pilot repo and no owner grant. Verify effective reach; if available grants
+cannot achieve it, add the upstream scope contract before live publication.
+Keep that credential in the broker, whose fixed allowlist refuses merge and
+default/protected refs. Record default-branch protections in the manifest.
+
+Include logical operation IDs in published records for reconciliation, but
+do not treat a text marker or an eventually consistent list as proof of
+absence. Retry a missing result only with an upstream idempotency contract or
+definitive outcome evidence; otherwise wait. Payload-rewrite operations such
+as claim/attach/task-set need concurrency protection before automated use;
+omit them in the first pilot if unavailable. Read-only tracking and creation
+of verified review artifacts are sufficient.
+
+The reviewer receives the brief, base/candidate diff and test evidence in a
+fresh context, with read-only tools and a different provider family where
+available. It cannot approve its own implementation. Provider unavailability
+puts the job in waiting; a fallback needs an existing policy grant.
+
+Verification executes trusted base-revision check definitions as well as the
+candidate's required checks; changing CI configuration must not weaken the
+acceptance gate. Record which checks ran, against which commit, and preserve
+their exit status and bounded logs. An independent test of the reported
+symptom is required, not only tests written alongside the proposed fix.
+Publishing can itself trigger CI with broader credentials. The pilot repo
+must run branch checks without production/deployment secrets or privileged
+untrusted-code access. Freeze trusted CI definitions and review any changes
+to CI/hooks before publication; a safe local worker alone does not make
+remote CI safe.
+
+The console view contains the main conversation, work list, job evidence,
+cost/usage and decisions requiring attention. Specialists are capabilities;
+models and runner controls are optional detail. Existing `team.html` manages
+account members and must not be repurposed accidentally. Names and UI copy
+remain provisional and go through the normal copy-review workflow when built.
+Every shipped CLI verb is API-backed and documented in `docs/site/cli.md`.
+
+## Later autonomy and acceptance
+
+Later triggers can consume platform metrics and support signals. Aggregate
+and deduplicate them in ordinary code. A standing policy specifies signal,
+account/app scope, observation window, cooldown, objective, protected metrics,
+budget and allowed action class. Untrusted messages/logs are evidence, never
+policy. Recommendations, prepared changes and executable remedies are distinct
+permissions. Failed experiments stop; they do not recursively create work.
+
+Support replies, refunds and account changes need their own connectors and
+grants. No existing mail/alert credential becomes customer-support authority.
+Measure results against a baseline and include regressions and recurrence.
+Automatic rollout requires an independently verified recovery procedure for
+that action; data changes are not assumed reversible.
+
+Accept the first slice only when a fixture bug reaches a correctly scoped
+review artifact, and the failure tests in the plan pass. Then measure a small
+live batch against the current manual workflow: accepted fixes, human minutes,
+elapsed time, total usage/cost, rework and unauthorized-action attempts.
+Do not claim savings from a single successful demonstration.
+
+Before live enrolment, name the account owner who approves the manifest, the
+service operator who rotates broker connections and clears quarantine, and
+the machine owner responsible for runner limits/cleanup. These are operational
+responsibilities; a model cannot assign itself any of them. The ordinary
+CARLOS CLI remains available if the team service is unavailable.
+
+## Evidence inspected
+
+Local source snapshots: platform `b5b0a53a0da1d9c8c936729fa5c0553e5363f987`;
+Amadan `2cb256bb1f0df560fe39245649a76b88d806d155`. These are inspection points,
+not claims about deployed versions. Revalidate integration contracts before
+implementation against the chosen base.
+
+- Platform: `internal/console/svcprincipal.go`, `authcli.go`,
+ `svcscope_test.go`, `alertwatch.go`; `internal/svcrole/svcrole.go`.
+- Amadan: `internal/hub/discuss_claim.go`, `discuss_block.go`,
+ `discuss_attach.go`; CLI help for task, branch review and handoff contracts.
+- Private journal: original platform design and service-principal plan.
+ Historical specs explain intent; current source determines actual reach.
+- Provider contracts:
+ [https://code.claude.com/docs/en/legal-and-compliance](https://code.claude.com/docs/en/legal-and-compliance),
+ [https://developers.openai.com/siwc/token-sharing-open-source/codex-app-server](https://developers.openai.com/siwc/token-sharing-open-source/codex-app-server).
+
+The linked audit and review record distinguish verified source findings,
+accepted design corrections and gates for later live implementation.
diff --git a/docs/superpowers/specs/2026-11-01-team-service-integration-audit.md b/docs/superpowers/specs/2026-11-01-team-service-integration-audit.md
new file mode 100644
index 000000000..596d7ec41
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-01-team-service-integration-audit.md
@@ -0,0 +1,59 @@
+# Team service integration audit
+
+Implementation-agent evidence, 2026-11-01. Sonnet (`claude-sonnet-5-5`)
+performed a read-only source audit; the coordinating agent checked the
+authority, claim and retry findings against the named source files.
+
+Inspection snapshots: platform `b5b0a53a0da1d9c8c936729fa5c0553e5363f987`;
+Amadan `2cb256bb1f0df560fe39245649a76b88d806d155`. These checkouts are not a
+statement of what is deployed or the latest remote main. Revalidate before
+building adapters. Historical design comments can lag current behaviour.
+
+| Integration | Existing evidence | Consequence for implementation |
+|---|---|---|
+| CARLOS principal resolution | `internal/console/svcprincipal.go:CLIPrincipal`, `NewServicePrincipal` | Reuse fixed account/app binding; never borrow the minter's memberships. Existing service tokens use revocation, with no automatic expiry. |
+| Route authority | `internal/console/authcli.go:registerCLIRoutes`, `internal/svcrole/svcrole.go` | Closed role catalogue and person-only routes already exist. Register new routes explicitly and test exact reach. |
+| Diagnostics | `authcli.go` registrations for logs, errors and analytics | `instance` and `operate` can read these but also perform writes. A read-only autonomous connector needs narrower authority. |
+| Fleet metrics | `internal/console/metricsview.go`, `apistatusinstances.go` | Existing metric loading is behind the console; do not grant bucket credentials or use box-local state. Confirm an authorized API shape for any new metric feed. |
+| Control-plane release protection | `internal/console/controlplane.go:refuseServiceControlPlane` | Existing service credentials cannot promote/rollback protected apps. Team integration must preserve that restriction. |
+| Rate limits | `authcli.go` service create/write/ship limiters | Request-rate limits are not durable job/token/cost budgets. Implement the execution ledger separately. |
+| Amadan identity | `internal/hub/cliauth.go`, `agents_api.go` | Use disclosed agent identity and supported grants. Audited agent grants are namespace-wide; workers must not receive these credentials. |
+| Work ownership | `internal/hub/discuss_claim.go` | Claim fields identify a holder and time, with no expiry, heartbeat or fence. Keep scheduler leases separate. |
+| Dependencies | `internal/hub/discuss_block.go` | Existing dependency and cycle semantics can inform scheduling. Closure is not action authorization. |
+| Tasks/reviews/handoffs | `internal/hub/discuss_api.go`, `discuss_assign.go`, `discuss_attach.go` | Reuse published workflow records. Review verdicts are informational; enforce independent verification in the service. |
+| Create/reply retry | `internal/hub/discuss_api.go` create/reply/task handlers | No caller operation key found in audited hub paths. A local outbox key alone cannot prevent duplicate remote creates after a lost response. |
+
+## Findings that require further verification
+
+The audit did not inspect every CLI path, the repository-instance update
+implementation, provider harness isolation, or all temporary-app features.
+It cannot establish global absence from a keyword search.
+
+- Preview/temporary-app support must be inventoried against the selected
+ implementation base. The pilot can omit previews; do not file a duplicate
+ feature solely because a route containing the word `preview` was absent.
+- Hub claim/handoff updates use read-modify-write. The audit did not establish
+ whether the repository instance performs additional concurrency checks.
+ Regardless, these records are not fenced execution leases.
+- An Amadan agent namespace token is broader than one repository job. The
+ broker needs a fixed mapping, a narrow tool surface and a documented
+ credential blast radius; stronger upstream scopes remain a product gap.
+- An independently reported review verdict is not a guarantee of separation
+ of duties or approval of the exact candidate commit.
+
+## Audit recommendations not adopted
+
+The audit suggested temporarily using an app-scoped `instance` credential
+for diagnostics and namespace tokens for workers. Those credentials carry
+more authority than the pilot requires. The spec instead requires broker
+handles and a read-only diagnostic grant before live monitoring.
+
+The audit also suggested local idempotency keys as a sufficient first step
+for remote creates. They are necessary for intent tracking but insufficient
+for replay safety. The spec requires upstream idempotency, reconciliation
+that proves the outcome, or a waiting state for uncertain results.
+
+Next dependency work is defined in the
+[implementation plan](../plans/2026-11-01-team-service.md). No credentials were
+minted, no production operations performed and no source code changed by this
+audit.
diff --git a/docs/superpowers/specs/2026-11-01-team-service-review.md b/docs/superpowers/specs/2026-11-01-team-service-review.md
new file mode 100644
index 000000000..241ec14ca
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-01-team-service-review.md
@@ -0,0 +1,75 @@
+# Team service independent review
+
+Implementation-agent review record, 2026-11-01.
+
+Integration audit: Sonnet, actual model `claude-sonnet-5-5`.
+Architecture reviewer: Fable, actual model `claude-fable-5-1`, high effort.
+Both ran through the unmodified Claude CLI with read-only source tools.
+No reviewer could edit files, run shell commands or contact live services.
+The requested Claude account was selected per process; the default login was
+not changed. Credentials and account identifiers are not part of this record.
+
+## Round 1
+
+Fable accepted the local fake-provider prototype with plan corrections and
+identified blockers for live access. It found no need to replace the overall
+architecture. Disposition against the revised spec and plan:
+
+| Finding | Resolution |
+|---|---|
+| Publication credentials and replay | Dedicated repo-limited agent identity; broker enforces refs/operations. Upstream scope gaps block live publication. Markers are positive evidence only; ambiguous outcomes wait. Payload rewrites need concurrency protection. |
+| Shared-machine confinement | Select unprivileged bubblewrap with private namespaces and scoped Unix broker socket; prove isolation before live use. Terminate the whole PID namespace/cgroup, including setsid children. |
+| Cross-account conversation history | Scope conversation events at write time; inherited source scopes govern summaries and retrieval. First live pilot is single-account. |
+| Provider session state | Isolated attempt-specific harness state; retention includes caches, transcripts and provider resume IDs. |
+| Subscription accounting mismatch | First live adapters use bounded metered API requests. Subscription CLI support is deferred until its actual enforceable bounds are specified. |
+| Restore and revocation | Console owns grants/revocations. Every startup pauses admission; external markers detect uncertainty, online reconciliation precedes resume, console restore rotates authority epoch. |
+| Slow fixture sequence | Execute M0, M1 and fixture-M5 first. Live integrations/UI are later gates. |
+| Person-only doors | Reuse empty role sets and the existing `closedDoors` test. The review's claim that coverage forbids every empty set was disproved by `svcroutes_test.go:193-213`. No new role vocabulary is needed. |
+| Mutable reproduction | Freeze the reproduction by hash outside the implementation workspace and verify that exact artifact. |
+| Renewal after expiry | Refuse renewal; require a new claim/fence. |
+| Reservation ceilings and stranded usage | Reserve the maximum admitted request; conservative audited settlement for irreconcilable usage. |
+| Shared build caches | Preserve machine defaults. Validate read-only caches and attempt-local overlays; no trusted worker-writable cross-job cache. |
+| Console runtime dependency | Explicit online authority checks; outages pause admission, not app serving. |
+| Real data and retention | Require a live manifest classifying repository/conversation data and covering every retained copy. |
+| Forge scope | Amadan is the first live integration; GitHub adapter deferred. Design-repo GitHub PR is a separate existing workflow. |
+| Operational responsibility | Live manifest names approver, credential/quarantine operator and runner-machine owner. |
+
+The coordinating review also added a publication check for remote CI:
+branch publication must not run untrusted code with production credentials
+or deploy hooks. Trusted check definitions and their hashes are evidence.
+
+## Round 2
+
+Fable returned **ACCEPT** for the design and plan for M0, M1 and the fixture
+workflow in M5, and for the later gated milestones. Its exact verdict begins:
+
+> **Verdict: ACCEPT** the design and plan for the bounded local prototype
+> (M0, M1, M5 fixture workflow) and as the contract for the later gated
+> milestones. No remaining finding blocks local coding.
+
+It withdrew the closed-door coverage finding after reading the equality test.
+It left transaction/type precision notes for implementation; these are now
+also explicit in the spec and plan:
+
+- Online authority check followed by a transaction over stored fence,
+ revision, grant version, state and reservation. Admission expires after
+ five seconds; record the bounded concurrent-revocation window.
+- Claim and cancellation update the same step row; cancellation prevents a
+ subsequent claim from reviving the job.
+- A new claim has a new attempt and workspace. Only accepted, hash-verified
+ checkpoints may cross attempts.
+- Reserve a per-call generated-token maximum of 4,000, including reasoning.
+- Settle late usage against an open reservation after cancellation or expiry,
+ without changing the terminal job outcome or double-charging receipts.
+- Outbox publication uses the same replay-safety and authority path as other
+ broker actions.
+- Observed revocation cancels the attempt; renewals also recheck authority.
+- Skips, missing tests, compile errors and zero test matches are invalid
+ reproduction evidence.
+- The 60-second lease is a deliberate pilot tradeoff; later tuning preserves
+ fencing. Handler person/membership checks and route-test wildcard/count
+ updates remain explicit M3 work.
+
+No live pilot or production operation is authorized by either review. The
+review accepts an implementation contract, not an unbuilt system's security
+or operational readiness.
diff --git a/internal/edge/localhold_probed_test.go b/internal/edge/localhold_probed_test.go
index 20feb2257..190f252a8 100644
--- a/internal/edge/localhold_probed_test.go
+++ b/internal/edge/localhold_probed_test.go
@@ -381,10 +381,25 @@ func TestProbedDeadlineMidPassDoesNotEject(t *testing.T) {
}
func TestProbedHoldSurvivesReload(t *testing.T) {
- a := deadAddr(t)
var hits atomic.Int64
- e, srv := probedEdge(t, []string{a}, fastHealth(), probedHold())
- listenLater(t, a, 200*time.Millisecond, countingHandler(&hits))
+ // The upstream stays bound for the whole test: releasing a port and
+ // rebinding it later lets another process take it in between. The dialer
+ // refuses until up flips, which stands in for the upstream not listening.
+ upstream := httptest.NewServer(countingHandler(&hits))
+ defer upstream.Close()
+ a := upstream.Listener.Addr().String()
+ var up atomic.Bool
+ var plain net.Dialer
+ hold := probedHold()
+ hold.dialer = func(ctx context.Context, network, addr string) (net.Conn, error) {
+ if !up.Load() {
+ return nil, refusedErr()
+ }
+ return plain.DialContext(ctx, network, addr)
+ }
+ e, srv := probedEdge(t, []string{a}, fastHealth(), hold)
+ avail := time.AfterFunc(200*time.Millisecond, func() { up.Store(true) })
+ defer avail.Stop()
reloaded := make(chan error, 1)
go func() {
time.Sleep(100 * time.Millisecond)