Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Retire hosted AI quickstart runtime

rcourtmanded190dcab78
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index e3b7d01b33..219beef127 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -1961,12 +1961,11 @@
},
{
"id": "RA21",
- "summary": "Pulse-owned hosted AI contracts stay vendor-neutral: quickstart runtime and API payloads expose the stable alias `quickstart:pulse-hosted`, while the license server requires explicit upstream model configuration instead of hardcoded vendor defaults.",
+ "summary": "Legacy Pulse-hosted AI aliases are retired for v6 GA: settings and runtime payloads must clear `quickstart:*` model strings, fail closed on the retired provider, and route operators to BYOK or local-provider setup instead of a managed-model promise.",
"kind": "invariant",
"blocking_level": "repo-ready",
"proof_type": "automated",
"lane_ids": [
- "L3",
"L6"
],
"subsystem_ids": [
@@ -1998,7 +1997,7 @@
"./internal/ai",
"./internal/api",
"-run",
- "Quickstart|DefaultModelForProvider|HostedAISettings|HostedTenantAISettings|ServiceLoadConfig_PrefersBYOKProviderOverQuickstart|ServiceLoadConfig_TracksQuickstartActivationRequirement|HandleGetPatrolStatus|AISettingsHandler_",
+ "Quickstart|DefaultModelForProvider|HostedAISettings|HostedTenantAISettings|HandleGetPatrolStatus|AISettingsHandler_",
"-count=1"
]
},
@@ -2054,26 +2053,6 @@
"repo": "pulse",
"path": "tests/integration/tests/51-quickstart-cross-surface.spec.ts",
"kind": "file"
- },
- {
- "repo": "pulse-pro",
- "path": "license-server/main.go",
- "kind": "file"
- },
- {
- "repo": "pulse-pro",
- "path": "license-server/quickstart_proxy.go",
- "kind": "file"
- },
- {
- "repo": "pulse-pro",
- "path": "license-server/quickstart_proxy_test.go",
- "kind": "file"
- },
- {
- "repo": "pulse-pro",
- "path": "license-server/secrets.env.template",
- "kind": "file"
}
]
},
@@ -2191,30 +2170,27 @@
},
{
"id": "RA23",
- "summary": "Patrol quickstart credits are billed per higher-level Patrol execution, not per internal provider turn: the runtime must propagate one stable execution ID across retries, agentic turns, and the evaluation pass, and the license server must treat repeated quickstart proxy calls for that execution as one commercial run.",
+ "summary": "Patrol agentic execution keeps one stable execution identifier across retries, agentic turns, and evaluation so runtime traces and follow-up work describe a single Patrol run without depending on retired hosted quickstart billing.",
"kind": "invariant",
"blocking_level": "repo-ready",
"proof_type": "automated",
"lane_ids": [
- "L3",
"L6"
],
"subsystem_ids": [
- "ai-runtime",
- "cloud-paid"
+ "ai-runtime"
],
"release_gate_ids": [],
"proof_commands": [
{
- "id": "patrol-quickstart-execution-contract-tests",
+ "id": "patrol-execution-identity-contract-tests",
"run": [
"go",
"test",
- "./internal/ai/providers",
"./internal/ai/chat",
"./internal/ai",
"-run",
- "Quickstart|ExecutePatrolStream|RunEvaluationPass|RetriesWithProviderDerivedSeedBudget",
+ "ExecutePatrolStream|RunEvaluationPass|RetriesWithProviderDerivedSeedBudget",
"-count=1"
]
}
@@ -2230,11 +2206,6 @@
"path": "docs/release-control/v6/internal/subsystems/ai-runtime.md",
"kind": "file"
},
- {
- "repo": "pulse",
- "path": "docs/release-control/v6/internal/subsystems/cloud-paid.md",
- "kind": "file"
- },
{
"repo": "pulse",
"path": "internal/ai/chat/service.go",
@@ -2254,36 +2225,6 @@
"repo": "pulse",
"path": "internal/ai/patrol_ai_more_test.go",
"kind": "file"
- },
- {
- "repo": "pulse",
- "path": "internal/ai/providers/quickstart.go",
- "kind": "file"
- },
- {
- "repo": "pulse",
- "path": "internal/ai/providers/quickstart_test.go",
- "kind": "file"
- },
- {
- "repo": "pulse-pro",
- "path": "license-server/quickstart_proxy.go",
- "kind": "file"
- },
- {
- "repo": "pulse-pro",
- "path": "license-server/quickstart_proxy_test.go",
- "kind": "file"
- },
- {
- "repo": "pulse-pro",
- "path": "license-server/quickstart_store.go",
- "kind": "file"
- },
- {
- "repo": "pulse-pro",
- "path": "license-server/v6_schema.go",
- "kind": "file"
}
]
},
@@ -2343,7 +2284,7 @@
},
{
"id": "RA25",
- "summary": "Patrol quickstart bootstrap must resolve a real server-verified commercial principal, never synthetic local identity: activated installs use installation tokens, while entitlement-backed trial or hosted runtimes use signed entitlement leases without fabricating installation-scoped activation state.",
+ "summary": "Hosted and self-hosted v6 AI bootstrap must stay BYOK/local-provider only: commercial billing state may authorize hosted tenancy, but it must not create quickstart credits, mint hosted-model tokens, or persist a managed-model AI config.",
"kind": "invariant",
"blocking_level": "repo-ready",
"proof_type": "automated",
@@ -2359,27 +2300,14 @@
"release_gate_ids": [],
"proof_commands": [
{
- "id": "quickstart-dual-principal-license-server-tests",
- "run": [
- "go",
- "-C",
- "../pulse-pro/license-server",
- "test",
- "-run",
- "TestHandleQuickstartBootstrap_.*HostedEntitlement|TestHandleQuickstartBootstrap_IssuesTokenForVerifiedInstallation|TestHandleQuickstartBootstrap_RequiresAuth",
- "-count=1"
- ]
- },
- {
- "id": "quickstart-dual-principal-runtime-tests",
+ "id": "hosted-ai-bootstrap-retirement-runtime-tests",
"run": [
"go",
"test",
- "./internal/ai",
"./internal/api",
"./pkg/licensing",
"-run",
- "Quickstart|AISettingsHandler_GetHostedSettings_AutoBootstrapsQuickstart|AISettingsHandler_GetHostedTenantSettings_InheritsDefaultHostedBillingState|AISettingsHandler_UpdateSettings_QuickstartBootstrapBeforeEnableUsesActivationIdentity|ClientBootstrapQuickstart",
+ "Quickstart|HostedAISettings|HostedTenantAISettings|HostedEntitlement|TrialStart|BillingState",
"-count=1"
]
}
@@ -2405,16 +2333,6 @@
"path": "docs/release-control/v6/internal/subsystems/cloud-paid.md",
"kind": "file"
},
- {
- "repo": "pulse",
- "path": "internal/ai/quickstart.go",
- "kind": "file"
- },
- {
- "repo": "pulse",
- "path": "internal/ai/quickstart_test.go",
- "kind": "file"
- },
{
"repo": "pulse",
"path": "internal/api/ai_handlers_test.go",
@@ -2429,36 +2347,6 @@
"repo": "pulse",
"path": "pkg/licensing/license_server_client.go",
"kind": "file"
- },
- {
- "repo": "pulse",
- "path": "pkg/licensing/quickstart_bootstrap.go",
- "kind": "file"
- },
- {
- "repo": "pulse-pro",
- "path": "license-server/quickstart_entitlement.go",
- "kind": "file"
- },
- {
- "repo": "pulse-pro",
- "path": "license-server/quickstart_proxy.go",
- "kind": "file"
- },
- {
- "repo": "pulse-pro",
- "path": "license-server/quickstart_proxy_test.go",
- "kind": "file"
- },
- {
- "repo": "pulse-pro",
- "path": "license-server/quickstart_store.go",
- "kind": "file"
- },
- {
- "repo": "pulse-pro",
- "path": "license-server/secrets.env.template",
- "kind": "file"
}
]
},
@@ -3573,7 +3461,7 @@
"status": "partial",
"completion": {
"state": "bounded-residual",
- "summary": "Policy-aware data governance now has a first-class governed floor: resource sensitivity, handling-boundary, and redaction posture are visible in Data Handling, non-local AI provider requests use the shared resource-policy sanitizer at the final model boundary, hosted quickstart requests carry a resource-policy marker that the proxy enforces, and privacy copy now reflects the runtime behavior. Broader enterprise DLP, provider-retention posture, and non-resource prompt-secret detection remain a named post-RC hardening track.",
+ "summary": "Policy-aware data governance now has a first-class governed floor: resource sensitivity, handling-boundary, and redaction posture are visible in Data Handling, non-local AI provider requests use the shared resource-policy sanitizer at the final model boundary, and privacy copy now reflects the runtime behavior. Broader enterprise DLP, provider-retention posture, and non-resource prompt-secret detection remain a named post-RC hardening track.",
"tracking": [
{
"kind": "lane-followup",
@@ -3629,16 +3517,6 @@
"path": "internal/ai/modelboundary/resource_policy_sanitizer_test.go",
"kind": "file"
},
- {
- "repo": "pulse",
- "path": "internal/ai/providers/quickstart.go",
- "kind": "file"
- },
- {
- "repo": "pulse",
- "path": "internal/ai/providers/quickstart_test.go",
- "kind": "file"
- },
{
"repo": "pulse",
"path": "internal/unifiedresources/policy_metadata.go",
@@ -3648,16 +3526,6 @@
"repo": "pulse",
"path": "internal/unifiedresources/policy_metadata_test.go",
"kind": "file"
- },
- {
- "repo": "pulse-pro",
- "path": "license-server/quickstart_proxy.go",
- "kind": "file"
- },
- {
- "repo": "pulse-pro",
- "path": "license-server/quickstart_proxy_test.go",
- "kind": "file"
}
]
},
@@ -4914,7 +4782,21 @@
],
"coverage_gaps": [],
"candidate_lanes": [],
- "work_claims": [],
+ "work_claims": [
+ {
+ "id": "codex-lane-l6",
+ "agent_id": "codex",
+ "summary": "Remove remaining hosted-AI quickstart provider/runtime plumbing so v6 self-hosted AI is BYOK/local-only and quickstart survives only as inert historical compatibility.",
+ "target_id": "v6-product-lane-expansion",
+ "claimed_at": "2026-04-28T14:53:29Z",
+ "heartbeat_at": "2026-04-28T14:53:29Z",
+ "expires_at": "2026-04-28T16:53:29Z",
+ "work_item": {
+ "kind": "lane",
+ "id": "L6"
+ }
+ }
+ ],
"open_decisions": [],
"source_of_truth_file": "docs/release-control/v6/internal/SOURCE_OF_TRUTH.md",
"resolved_decisions": [
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 345e0d97a9..7424dfd2b3 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -155,15 +155,13 @@ the manifest's support-floor row.
that follow-up uninstall so operators can immediately back out a reviewed
script-managed Proxmox setup without leaving a stale node record in Pulse.
That same shared `internal/api/` adjacency does not transfer ownership of
- Patrol quickstart bootstrap or mobile Patrol-provider bridging:
+ AI provider setup or mobile Patrol-provider bridging:
`internal/api/ai_handlers.go` and `internal/api/chat_service_adapter.go`
- may be invoked by lifecycle-adjacent surfaces, but server-issued
- quickstart tokens, Patrol quickstart credit snapshots, and AI runtime auth
- remain `ai-runtime` plus `api-contracts` concerns rather than install-token
- or lifecycle credential state. Server-verified runtime identity remains the
- only authority for Patrol quickstart bootstrap: self-hosted installs use the
- shared installation-scoped `activation.enc`, while entitled hosted lanes use
- the signed entitlement lease already carried in canonical billing state.
+ may be invoked by lifecycle-adjacent surfaces, but AI runtime auth and
+ provider selection remain `ai-runtime` plus `api-contracts` concerns rather
+ than install-token or lifecycle credential state. Lifecycle flows must not
+ recreate the retired Patrol quickstart bootstrap path, mint server-issued
+ hosted-model tokens, or derive AI provider state from installation identity.
Per-request `/api/ai/chat` execution-mode overrides follow that same
boundary: lifecycle-adjacent consumers may rely on Assistant approval
semantics, but scoped `autonomous_mode:false` chat requests must not be
@@ -175,11 +173,12 @@ the manifest's support-floor row.
creation, email issuance, or public-route availability from
`/api/public/signup` response codes or payload fields just because that
commercial route lives under the shared `internal/api/` tree.
- That same shared quickstart boundary is vendor-neutral at the lifecycle
- edge too: lifecycle-adjacent consumers may observe the stable
- `quickstart:pulse-hosted` alias in AI settings payloads, but they must not
- bake vendor model IDs or provider-model fallback rules into install or
- activation flows just because those routes share the backend API tree.
+ That same retired quickstart boundary is vendor-neutral at the lifecycle
+ edge too: lifecycle-adjacent consumers may observe old `quickstart:*`
+ values only as compatibility data being cleared by shared settings helpers.
+ They must not bake vendor model IDs or provider-model fallback rules into
+ install or activation flows just because those routes share the backend API
+ tree.
Lifecycle-adjacent resource reads that traverse `internal/api/resources.go`
must also preserve the canonical unified-resource `name -> type -> id`
order instead of inheriting map order or page-local re-sorts, so install
@@ -201,20 +200,16 @@ the manifest's support-floor row.
`/api/resources`.
Persisted legacy hosted quickstart model IDs are therefore not lifecycle
truth either: when shared settings helpers load or save historical
- quickstart values, they must normalize them back to
- `quickstart:pulse-hosted` before adjacent install or activation flows read
- the payload.
- The machine-scoped quickstart authority must stay canonical too:
- tenant-local lifecycle routes may reuse shared installation activation or
- effective entitlement billing state, but they must not fork per-org
- activation caches, alternate installation-token stores, synthetic
- entitlement mirrors, or competing quickstart-owner identity. That same
- shared AI/runtime boundary now also owns Patrol quickstart execution
- identity: lifecycle-adjacent flows may trigger or observe Patrol runs
- through `internal/api/chat_service_adapter.go`, but they must preserve the
- stable execution identifier that lets the hosted quickstart contract bill
- once per higher-level Patrol run rather than once per internal provider
- turn.
+ quickstart values, they must clear them before adjacent install or
+ activation flows read the payload. Tenant-local lifecycle routes may reuse
+ shared installation activation or effective entitlement billing state for
+ their own governed purposes, but they must not fork per-org activation
+ caches, alternate installation-token stores, synthetic entitlement mirrors,
+ or competing AI-provider identity. That same shared AI/runtime boundary owns
+ Patrol execution identity: lifecycle-adjacent flows may trigger or observe
+ Patrol runs through `internal/api/chat_service_adapter.go`, but they must
+ preserve the stable execution identifier that describes one higher-level
+ Patrol run across agentic turns.
2. Add or change update continuity and persisted-version handoff through `internal/agentupdate/`.
3. Add or change runtime-side Unified Agent startup, first-report assembly, and enroll/runtime continuity through `internal/hostagent/`.
Proxmox host-agent setup must treat local `proxmox-registered` markers as a cache, not authority: before skipping token setup or node repair, `internal/hostagent/proxmox_setup.go` must revalidate the current type and candidate hosts against Pulse through the canonical auto-register contract.
@@ -1067,20 +1062,17 @@ before any API-only token fallback or optional-auth anonymous fallback so
operators can mint relay-mobile credentials and continue onboarding from the
hosted runtime itself even after that tenant has already minted managed API
tokens.
-That same lifecycle-adjacent hosted setup path also depends on AI bootstrap
-staying canonical before the first settings write. Hosted operators may land
-in Chat, Patrol-backed setup hints, or AI-dependent remediation surfaces
-before anyone has visited AI Settings, so the shared `internal/api/`
-hosted-AI bootstrap helper must persist the machine-owned quickstart-backed
-`ai.enc` for entitled tenants by reusing the signed entitlement lease already
-present in billing state; it must not fabricate installation activation just
-to satisfy quickstart bootstrap. Otherwise lifecycle-adjacent hosted flows end
-up in a fake `AI disabled` state that disappears only after a manual save.
-That same lifecycle-adjacent hosted entitlement path must also preserve the
-trial quickstart grant fields already seeded into billing state. Hosted setup
-and pairing may depend on the shared `internal/api/` entitlement refresh, but
-that refresh must not erase quickstart bootstrap inventory while it rewrites
-lease-backed plan and capability data.
+That same lifecycle-adjacent hosted setup path now depends on AI bootstrap
+staying explicitly BYOK/local before the first settings write. Hosted
+operators may land in Chat, Patrol-backed setup hints, or AI-dependent
+remediation surfaces before anyone has visited AI Settings, but the shared
+`internal/api/` hosted-AI helper must return the same unconfigured
+provider-setup state as self-hosted unless an explicit AI config exists. It
+must not fabricate installation activation, quickstart credits, or a
+quickstart-backed `ai.enc` from billing state. Historical quickstart grant
+fields may stay parseable in billing state for old files, but hosted setup and
+pairing must not treat them as active AI inventory while entitlement refresh
+rewrites lease-backed plan and capability data.
That same shared entitlement refresh path must also keep hosted effective-org
ownership canonical for lifecycle-adjacent routes: when pairing or relay-mobile
bootstrap arrives scoped to a tenant org with no org-local lease, the refresh
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 648a05d6cb..050f45b071 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -159,8 +159,8 @@ title, empty/loading states, budget note, and reset/export history messaging so
settings shells and runtime widgets do not fork their own usage wording.
`internal/ai/` is the live backend AI engine. It owns chat execution, Patrol
-orchestration, findings generation, investigation support, quickstart and
-provider selection, remediation flow, and cost persistence.
+orchestration, findings generation, investigation support, provider selection,
+remediation flow, and cost persistence.
That Patrol runtime ownership includes seed-context admission control.
`internal/ai/patrol_ai.go` must build Patrol and triage prompts from
canonical seed sections, size them against the runtime budget model, and when
@@ -195,21 +195,17 @@ selection may fall back only to the provider-owned default declared in
`internal/config/ai.go`. Runtime startup, connection-test, and load-config
paths may not return an empty effective model or borrow another provider's
selection just because live model discovery was unavailable.
-Retired quickstart ownership is now a compatibility boundary, not a normal
-self-hosted GA runtime path. `internal/ai/providers/quickstart.go` and
-`internal/ai/quickstart.go` may remain parseable for mixed-version runtimes,
-hosted compatibility, or support migration while that backend code exists, but
-ordinary self-hosted Assistant, Patrol, and AI Settings flows must prefer the
+Retired quickstart ownership is now an inert compatibility boundary, not a
+self-hosted GA runtime path. The old quickstart provider, bootstrap manager,
+and local token-cache persistence API are removed from the Pulse runtime;
+ordinary self-hosted Assistant, Patrol, and AI Settings flows must use the
operator's configured provider or local model and must not bootstrap managed
-credits from the frontend. Any retained compatibility traffic must still use the
-owned commercial API edge, authenticate with server-verified commercial
-authority, avoid anonymous local identity, and carry the `resource-policy-v1`
-data-policy marker so legacy prompt relay cannot become an ungoverned
-external-model bypass.
-Public-facing copy that reflects those legacy runtime fields must normalize
-back to provider or local-model setup. It must not promise managed credits,
-account activation support, trial CTAs, anonymous Community bootstrap, or full
-hosted chat access in ordinary self-hosted v6 GA flows.
+credits, hosted-model tokens, or quickstart-backed provider clients from the
+frontend.
+Public-facing copy that reflects old quickstart fields must normalize back to
+provider or local-model setup. It must not promise managed credits, account
+activation support, trial CTAs, anonymous Community bootstrap, or full hosted
+chat access in ordinary self-hosted v6 GA flows.
That same runtime-backed contract now governs AI settings enablement too:
unconfigured installs open provider setup, while stale managed-credit or
activation-required states are treated as compatibility metadata rather than a
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index ee04ecc43c..0b01fd3892 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -529,8 +529,8 @@ the canonical monitored-system blocked payload.
`quickstart_credits_total`, `quickstart_credits_available`,
`quickstart_blocked_reason`, or `using_quickstart` as ordinary v6 GA fields,
and shared handlers must not invent client-authored commercial identity,
- synthetic credits, or quickstart-backed config when the legacy server path is
- unavailable
+ synthetic credits, or quickstart-backed config now that the hosted
+ quickstart bootstrap path is retired
and the provider-first availability rule, so missing managed-model activation
identity must not block ordinary BYOK/local setup and must not silently
attempt anonymous bootstrap
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index c02ce7acc3..1e18cce04c 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -110,7 +110,6 @@ cloud-specific enforcement rules.
87. `internal/cloudcp/stripe/grace_enforcer.go`, `internal/cloudcp/stripe/helpers.go`, `internal/cloudcp/stripe/reconciler.go`, `internal/cloudcp/stripe/webhook.go`
88. `internal/hosted/hosted_metrics.go`, `internal/hosted/reaper.go`
89. `pulse-pro:ops/pulse-cloud/audit/`
-90. `pulse-pro:license-server/quickstart_proxy.go`
## Shared Boundaries
@@ -221,7 +220,7 @@ Community limit enforcement.
that summary into a second overview deck, metric grid, or competing shell.
7. Add or change Stripe provisioning plan resolution through `internal/cloudcp/stripe/provisioner.go`
8. Add or change activation/grant lifecycle, release build helper gating, or dev-mode capability widening through `pkg/licensing/dev_mode_features.go`, `pkg/licensing/service.go`, `pkg/licensing/testing_helpers.go`, `pkg/licensing/grant_refresh.go`, and `pkg/licensing/revocation_poll.go`
-9. Add or change license-server transport through `pkg/licensing/license_server_client.go` and `pkg/licensing/quickstart_bootstrap.go`
+9. Add or change license-server transport through `pkg/licensing/license_server_client.go`
That transport boundary must use HTTPS for non-loopback commercial endpoints,
may allow plaintext only on direct loopback development targets, and must
route outbound license-server fetches through the restricted HTTP client so
@@ -770,24 +769,11 @@ fixtures. Future exchange-path changes must not reintroduce a split contract
where the shared Pulse runtime and the real `pulse-pro/license-server` disagree
on the activation payload shape.
That same license-server transport boundary now treats Patrol quickstart
-bootstrap as legacy/support compatibility rather than a normal self-hosted v6
-GA journey. `pkg/licensing/license_server_client.go` and
-`pkg/licensing/quickstart_bootstrap.go` may continue to understand
-`POST /v1/quickstart/bootstrap` payloads for mixed-version runtimes and support
-cases, but ordinary self-hosted frontend flows must not initiate that path.
-If the compatibility path is retained, the Pulse runtime must authenticate it
-with one of the server-verified commercial authorities owned by the shared
-commercial boundary and must not invent anonymous local identity or fake
-self-hosted `activation.enc` state. Local runtime cache files may memoize
-returned tokens and counts but may not treat those cached counts as commercial
-authority or customer-facing entitlement.
-That same public proxy boundary remains privacy-constrained for any legacy
-traffic that still reaches it: requests must carry the `resource-policy-v1`
-data-policy marker proving client-side aggregate-only local-only handling and
-exact resource-policy redaction. Pricing, docs, and normal self-hosted runtime
-UI must not present this compatibility path as Community entitlement, a trial
-CTA, account activation support, or a general hosted chat plan while Relay and
-Pro carry the paid story.
+bootstrap as retired, not as a mixed-version runtime extension point. The
+Pulse runtime must not call `POST /v1/quickstart/bootstrap`, must not persist
+quickstart-backed AI config, and must not mint hosted-model tokens from hosted
+or self-hosted billing state. Historical quickstart credit fields may remain
+parseable in billing state only so old HMAC-protected files can still load.
The self-hosted commercial counted unit is now also locked to monitored
systems rather than agent installs. `max_monitored_systems` is the live
runtime and UI contract, while legacy `max_agents` / `max_nodes` aliases are
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index e68888158e..7398ae2ace 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -2122,8 +2122,7 @@
"label": "license server transport proof",
"match_prefixes": [],
"match_files": [
- "pkg/licensing/license_server_client.go",
- "pkg/licensing/quickstart_bootstrap.go"
+ "pkg/licensing/license_server_client.go"
],
"allow_same_subsystem_tests": false,
"test_prefixes": [],
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 9ed32a450b..f6e8abf5ff 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -153,8 +153,9 @@ informational and non-commercial so free/self-hosted operators are not shown
paywall, trial, upgrade, or monitoring-limit prompts inside a privacy surface.
That posture is now enforced at the AI provider boundary too: non-local model
requests must be sanitized from the same resource-policy metadata that powers
-the Data Handling surface, and hosted quickstart requests must carry an
-explicit `resource-policy-v1` marker before the public proxy accepts them.
+the Data Handling surface. Hosted quickstart traffic is retired from the Pulse
+runtime, so privacy governance must not describe a live public hosted-model
+proxy for normal self-hosted v6 installs.
That shared settings boundary now also has an explicit split of responsibilities:
`frontend-modern/src/components/Settings/useSystemSettingsState.ts` remains the
canonical owner for telemetry, local-upgrade-metrics, and auth/privacy runtime
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 4fa722197e..5f264b0122 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -253,33 +253,26 @@ querying, and the operator-facing storage health presentation layer.
19. Preserve shipped local security-doc guidance in shared `internal/api/` config/setup helpers so storage- and recovery-adjacent transport surfaces do not reintroduce GitHub `main` security links when the running build already serves its own local security documentation route.
20. Keep shared `internal/api/` Patrol transport and alert-trigger edits feature-isolated: Patrol-specific recency fields, callback fan-out, or alert-bridge wiring changes must not leak into recovery queries, storage links, or recovery-adjacent install/setup flows unless this contract changes in the same slice.
The same adjacency rule applies to AI settings transport in `internal/api/ai_handlers.go`: provider auth state, masked-secret payload fields, and provider-test model selection remain AI/runtime plus API-contract concerns and must not be absorbed into storage/recovery transport ownership just because those handlers live under the shared backend API tree.
- That same adjacent boundary also owns the server-authoritative Patrol
- quickstart contract: bootstrap-triggered `quickstart_credits_remaining`,
- `quickstart_credits_total`, `using_quickstart`, and cached bearer-token
- state exposed through shared AI handlers are transport facts owned by the
- AI/runtime plus API-contract lanes, and storage/recovery surfaces must not
- reintroduce local quickstart accounting, token lifecycle, anonymous
- bootstrap identity, fake activation records, or commercial identity rules.
- That shared AI settings payload is also intentionally vendor-neutral:
- storage/recovery-adjacent consumers may react to the stable
- `quickstart:pulse-hosted` alias, but they must not treat vendor model IDs
- or quickstart upstream-model defaults as part of storage/recovery transport
+ That same adjacent boundary also keeps the retired Patrol quickstart
+ contract out of storage/recovery ownership: shared AI handlers no longer
+ expose active quickstart credit, token, or hosted-model provider state, and
+ storage/recovery surfaces must not reintroduce local quickstart accounting,
+ token lifecycle, anonymous bootstrap identity, fake activation records, or
+ commercial identity rules. That shared AI settings payload is also
+ intentionally vendor-neutral: storage/recovery-adjacent consumers may see
+ old `quickstart:*` values only as compatibility data being cleared by the
+ shared settings helpers, and they must not treat vendor model IDs or
+ quickstart upstream-model defaults as part of storage/recovery transport
ownership or route behavior.
- Self-hosted installation activation and hosted entitlement lease authority
- for quickstart bootstrap remain owned by the shared AI/runtime boundary;
- storage/recovery-adjacent helpers may consume the resulting state, but they
- must not mint alternate installation surrogates or duplicate entitlement
- verification logic.
- That same adjacent `internal/api/` boundary also now carries Patrol-run
- execution identity for hosted quickstart billing. Storage and recovery may
- observe shared Patrol transport through `internal/api/chat_service_adapter.go`,
- but they must not drop, rewrite, or reinterpret the execution identifier
- that lets the server-authoritative quickstart ledger charge once per Patrol
- run instead of once per agentic provider turn.
- Activation-required quickstart block reasons exposed on that same shared
- AI settings surface are likewise not storage/recovery onboarding truth;
- adjacent pages may react to the message, but they must not reinterpret it
- as a storage install prerequisite, provider-connection error, or
+ That same adjacent `internal/api/` boundary still carries Patrol-run
+ execution identity. Storage and recovery may observe shared Patrol
+ transport through `internal/api/chat_service_adapter.go`, but they must not
+ drop, rewrite, or reinterpret the execution identifier that describes one
+ Patrol run across agentic provider turns.
+ Retired quickstart block reasons exposed through stale compatibility state
+ are likewise not storage/recovery onboarding truth; adjacent pages may
+ normalize the message, but they must not reinterpret it as a storage install
+ prerequisite, provider-connection error, or
recovery-capability verdict.
21. Keep provider-backed recovery onboarding on the adjacent platform-connections contract. When `internal/api/` grows or changes TrueNAS connection CRUD, masked-secret preservation, saved-connection retest routes, edit-form saved-test payload overlays, or similar provider setup flows, storage and recovery may consume the resulting recovery points but must not absorb that connection-management ownership into storage/recovery-local handlers or page flows. That same adjacency also covers per-surface scope as it flows through the unified connections aggregator: when `internal/api/connections_aggregator.go` projects TrueNAS `MonitorDatasets`/`MonitorPools`/`MonitorReplication` flags into the aggregator's `scope` map, storage and recovery may observe that projection to explain dataset/pool/replication coverage to operators but must not reinterpret those flags as a recovery freshness verdict, restore-capability gate, or storage-local scope registry.
That same adjacent platform-connections boundary now also owns
@@ -602,9 +595,8 @@ querying, and the operator-facing storage health presentation layer.
17. Keep adjacent AI settings persistence vendor-neutral on the shared
`internal/api/` boundary. When storage- or recovery-adjacent hosted flows
load or save AI settings through shared helpers, any historical hosted
- quickstart model IDs must be normalized back to the governed alias
- `quickstart:pulse-hosted` before adjacent surfaces read or re-emit that
- state.
+ quickstart model IDs must be cleared before adjacent surfaces read or
+ re-emit that state.
When operators hover or focus pools versus physical disks, the storage
summary must reuse one resolved active-series ID across card state and
chart highlighting so pool-only cards demote cleanly during disk focus and
@@ -1209,16 +1201,14 @@ ledger explanation reads: storage- and recovery-adjacent surfaces may coexist
with counted monitored-system inventory, but any support-facing count
reasoning must come from the canonical unified-resource grouping explanation
payload rather than from storage or recovery heuristics.
-That same shared hosted-entitlement refresh path must also preserve the
-canonical quickstart grant metadata carried in billing state. Storage- and
+That same shared hosted-entitlement refresh path must preserve historical
+quickstart fields only as billing-state compatibility. Storage- and
recovery-adjacent hosted tenants may share Patrol-backed investigation and
recovery context with the rest of the app, but the shared `internal/api/`
-lease refresh must not clear quickstart inventory and leave adjacent product
-surfaces inferring a fake "unavailable" runtime from rewritten billing state.
-That same canonical billing state is also the hosted quickstart authority, so
-recovery-adjacent code must not compensate for missing install activation by
-fabricating local activation state when the lease-backed runtime already has a
-server-verifiable principal.
+lease refresh must not turn old quickstart inventory into active AI runtime
+state or lead adjacent product surfaces to infer a hosted-model entitlement.
+Recovery-adjacent code must not compensate for missing AI provider setup by
+fabricating local activation state or a quickstart-backed runtime.
That adjacent ledger read must also preserve canonical grouped system status,
including `warning`, so recovery- and storage-adjacent support views do not
flatten governed degraded state into a fake `unknown` label when the shared
@@ -2417,12 +2407,10 @@ localhost caller.
That same shared `internal/api/` boundary also owns hosted AI bootstrap
continuity. Storage- and recovery-adjacent hosted flows may surface Patrol-
backed investigation or AI-assisted recovery guidance before an operator has
-ever opened AI Settings, so the shared hosted runtime helper must persist the
-canonical quickstart-backed `ai.enc` from entitled billing state when no
-explicit AI config exists. Adjacent recovery surfaces must not invent their
-own "AI disabled until configured" fallback or synthetic activation state when
-the hosted runtime already has enough entitlement proof to bootstrap the
-machine-owned default.
+ever opened AI Settings, but the shared hosted runtime helper must return the
+same unconfigured provider-setup state as self-hosted unless an explicit AI
+config exists. Adjacent recovery surfaces must not invent their own hosted AI
+fallback, synthetic activation state, or quickstart-backed machine default.
That same hosted entitlement continuity also depends on the shared refresh path
repairing the correct billing owner. When recovery-adjacent hosted requests run
under a tenant org without org-local billing state, `internal/api/` must
@@ -2430,12 +2418,11 @@ refresh, persist, and re-evaluate the instance-level `default` lease instead of
rewriting the empty tenant org. Otherwise AI-assisted recovery can degrade to a
false free-tier state even though the hosted machine still has a valid refresh
token and signed entitlement lease.
-That same shared persistence path must also rewrite historical hosted
-quickstart model IDs to the Pulse-owned alias before adjacent recovery or
-storage flows read AI settings state. Support and recovery surfaces may
-observe `quickstart:pulse-hosted`, but they must not inherit or re-emit stale
-vendor IDs from old `ai.enc` payloads just because the shared settings helper
-touched persistence on the way through.
+That same shared persistence path must also clear historical hosted quickstart
+model IDs before adjacent recovery or storage flows read AI settings state.
+Support and recovery surfaces must not inherit or re-emit stale vendor IDs from
+old `ai.enc` payloads just because the shared settings helper touched
+persistence on the way through.
That same shared settings helper layer must then preserve canonical
org-management privilege for non-default tenant requests. Storage- and
recovery-adjacent hosted flows that reuse settings-bound helpers must allow
diff --git a/internal/ai/chat/agentic_control.go b/internal/ai/chat/agentic_control.go
index ace3e513ad..a72039c3ee 100644
--- a/internal/ai/chat/agentic_control.go
+++ b/internal/ai/chat/agentic_control.go
@@ -47,8 +47,8 @@ func (a *AgenticLoop) SetProviderInfo(provider, model string) {
}
// SetExecutionID binds a stable higher-level execution identifier to all
-// provider calls made by this loop. Patrol quickstart billing uses this to
-// charge once per Patrol run instead of once per provider turn.
+// provider calls made by this loop so Patrol traces one logical run across
+// agentic turns.
func (a *AgenticLoop) SetExecutionID(executionID string) {
a.mu.Lock()
a.executionID = executionID
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index 7dd865d61d..f3d3482787 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -103,8 +103,8 @@ type Service struct {
}
// SetPatrolProviderFactory installs a Patrol-only provider factory override.
-// This lets Patrol use a different quickstart contract without changing normal
-// interactive chat provider selection in the same slice.
+// This lets Patrol resolve provider-scoped model strings without changing
+// normal interactive chat provider selection in the same slice.
func (s *Service) SetPatrolProviderFactory(factory func(modelStr string) (providers.StreamingProvider, error)) {
s.mu.Lock()
defer s.mu.Unlock()
diff --git a/internal/ai/patrol.go b/internal/ai/patrol.go
index 913e3c37fd..95021cd6b1 100644
--- a/internal/ai/patrol.go
+++ b/internal/ai/patrol.go
@@ -88,12 +88,6 @@ const (
PatrolRuntimeStateActive PatrolRuntimeState = "active"
)
-const (
- patrolQuickstartCreditsExhaustedReason = "Quickstart credits exhausted. Connect your API key to continue using AI Patrol."
- patrolQuickstartActivationRequiredReason = "Connect your API key to use AI Patrol on this install. Hosted quickstart requires an activated entitlement."
- patrolQuickstartUnavailableReason = "Quickstart credits require internet access. Connect your API key for offline AI Patrol."
-)
-
type PatrolStatus struct {
RuntimeState PatrolRuntimeState `json:"runtime_state"`
Running bool `json:"running"`
@@ -110,10 +104,6 @@ type PatrolStatus struct {
IntervalMs int64 `json:"interval_ms"` // Patrol interval in milliseconds
BlockedReason string `json:"blocked_reason,omitempty"`
BlockedAt *time.Time `json:"blocked_at,omitempty"`
- // Quickstart credit info for the frontend
- QuickstartCreditsRemaining int `json:"quickstart_credits_remaining"`
- QuickstartCreditsTotal int `json:"quickstart_credits_total"`
- UsingQuickstart bool `json:"using_quickstart"`
}
// PatrolRunRecord represents a single patrol check run
@@ -465,9 +455,6 @@ type PatrolService struct {
// Patrol run history with persistence support
runHistoryStore *PatrolRunHistoryStore
- // Quickstart credit manager for free hosted patrol runs
- quickstartCredits QuickstartCreditManager
-
// Ad-hoc trigger channel for event-driven patrols (alert driven)
adHocTrigger chan *alerts.Alert
diff --git a/internal/ai/patrol_init.go b/internal/ai/patrol_init.go
index 142b96c605..9fc008b655 100644
--- a/internal/ai/patrol_init.go
+++ b/internal/ai/patrol_init.go
@@ -618,23 +618,6 @@ func (p *PatrolService) SetEventTriggersEnabled(enabled bool) {
})
}
-// SetQuickstartCredits sets the quickstart credit manager for free hosted patrol runs.
-func (p *PatrolService) SetQuickstartCredits(mgr QuickstartCreditManager) {
- p.mu.Lock()
- defer p.mu.Unlock()
- p.quickstartCredits = mgr
- if mgr != nil {
- log.Info().Int("remaining", mgr.CreditsRemaining()).Msg("AI Patrol: Quickstart credit manager configured")
- }
-}
-
-// GetQuickstartCredits returns the quickstart credit manager.
-func (p *PatrolService) GetQuickstartCredits() QuickstartCreditManager {
- p.mu.RLock()
- defer p.mu.RUnlock()
- return p.quickstartCredits
-}
-
// TriggerScopedPatrol runs a targeted patrol for specific resources.
// This is called by the TriggerManager for event-driven patrols.
// When ResourceIDs or ResourceTypes are specified in the scope, only those resources
diff --git a/internal/ai/patrol_run.go b/internal/ai/patrol_run.go
index 7834b01eb9..5be6464a21 100644
--- a/internal/ai/patrol_run.go
+++ b/internal/ai/patrol_run.go
@@ -13,7 +13,6 @@ import (
"github.com/google/uuid"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/circuit"
- "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
@@ -362,24 +361,10 @@ func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger Trigge
aiServiceEnabled := p.aiService != nil && p.aiService.IsEnabled()
canRunLLM := aiServiceEnabled && llmAllowed
- // Check quickstart credit status for messaging
- p.mu.RLock()
- qsMgr := p.quickstartCredits
- p.mu.RUnlock()
-
// Check if we can run LLM analysis (AI-only patrol)
if !canRunLLM {
reason := "AI not configured - set up a provider in Settings > Pulse Assistant"
- if !aiServiceEnabled {
- if p.aiService != nil && strings.TrimSpace(p.aiService.QuickstartBlockedReason()) != "" {
- reason = p.aiService.QuickstartBlockedReason()
- } else if qsMgr != nil && !qsMgr.HasBYOK() && !qsMgr.HasCredits() {
- // Distinguish between exhausted credits and no AI configured.
- reason = patrolQuickstartCreditsExhaustedReason
- } else {
- reason = "AI not configured - set up a provider in Settings > Pulse Assistant"
- }
- } else if !llmAllowed {
+ if aiServiceEnabled && !llmAllowed {
reason = "circuit breaker is open"
GetPatrolMetrics().RecordCircuitBlock()
}
@@ -388,19 +373,6 @@ func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger Trigge
return
}
- // Check if using quickstart credits — verify credits remain before starting
- usingQuickstart := p.aiService != nil && p.aiService.IsUsingQuickstart()
- if usingQuickstart && p.aiService != nil && strings.TrimSpace(p.aiService.QuickstartBlockedReason()) != "" {
- p.setBlockedReason(p.aiService.QuickstartBlockedReason())
- log.Info().Str("reason", p.aiService.QuickstartBlockedReason()).Msg("AI Patrol: Skipping run - quickstart unavailable")
- return
- }
- if usingQuickstart && qsMgr != nil && !qsMgr.HasCredits() {
- p.setBlockedReason(patrolQuickstartCreditsExhaustedReason)
- log.Info().Msg("AI Patrol: Skipping run - quickstart credits exhausted")
- return
- }
-
{
p.clearBlockedReason()
// Ensure stream state is clean for this run before the first streamed event.
@@ -415,11 +387,7 @@ func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger Trigge
// Create a finding to surface this error to the user
errMsg := aiErr.Error()
var title, description, recommendation string
- if usingQuickstart && (strings.Contains(errMsg, "dial tcp") || strings.Contains(errMsg, "no such host") || strings.Contains(errMsg, "connection refused") || strings.Contains(errMsg, "i/o timeout")) {
- title = "Pulse Patrol: Quickstart credits require internet"
- description = "Pulse Patrol cannot reach the quickstart proxy server. Quickstart credits require an internet connection."
- recommendation = patrolQuickstartUnavailableReason
- } else if strings.Contains(errMsg, "Insufficient Balance") || strings.Contains(errMsg, "402") {
+ if strings.Contains(errMsg, "Insufficient Balance") || strings.Contains(errMsg, "402") {
title = "Pulse Patrol: Provider billing or quota issue"
description = "Pulse Patrol cannot analyze your infrastructure because the configured AI provider rejected the request for billing or quota reasons."
recommendation = "Resolve the billing or quota issue with your AI provider, or switch to a different provider or local model in Pulse Assistant settings."
@@ -453,15 +421,6 @@ func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger Trigge
LastSeenAt: time.Now(),
}
trackFinding(errorFinding)
-
- if usingQuickstart {
- switch {
- case providers.IsQuickstartCreditsExhausted(aiErr):
- p.setBlockedReason(patrolQuickstartCreditsExhaustedReason)
- case providers.IsQuickstartUnavailable(aiErr), quickstartBootstrapUnavailable(aiErr):
- p.setBlockedReason(patrolQuickstartUnavailableReason)
- }
- }
} else if aiResult != nil {
runStats.aiAnalysis = aiResult
runStats.rejectedFindings = aiResult.RejectedFindings
@@ -833,21 +792,9 @@ func (p *PatrolService) runScopedPatrol(ctx context.Context, scope PatrolScope)
aiServiceEnabled := p.aiService != nil && p.aiService.IsEnabled()
canRunLLM := aiServiceEnabled && llmAllowed
- // Check quickstart credit status for scoped runs
- p.mu.RLock()
- scopedQsMgr := p.quickstartCredits
- p.mu.RUnlock()
- scopedUsingQuickstart := p.aiService != nil && p.aiService.IsUsingQuickstart()
-
if !canRunLLM {
reason := "AI not configured - set up a provider in Settings > Pulse Assistant"
- if !aiServiceEnabled {
- if p.aiService != nil && strings.TrimSpace(p.aiService.QuickstartBlockedReason()) != "" {
- reason = p.aiService.QuickstartBlockedReason()
- } else if scopedQsMgr != nil && !scopedQsMgr.HasBYOK() && !scopedQsMgr.HasCredits() {
- reason = patrolQuickstartCreditsExhaustedReason
- }
- } else if !llmAllowed {
+ if aiServiceEnabled && !llmAllowed {
reason = "circuit breaker is open"
GetPatrolMetrics().RecordCircuitBlock()
}
@@ -856,18 +803,6 @@ func (p *PatrolService) runScopedPatrol(ctx context.Context, scope PatrolScope)
return
}
- // Check if using quickstart credits — verify credits remain before starting
- if scopedUsingQuickstart && p.aiService != nil && strings.TrimSpace(p.aiService.QuickstartBlockedReason()) != "" {
- p.setBlockedReason(p.aiService.QuickstartBlockedReason())
- log.Info().Str("reason", p.aiService.QuickstartBlockedReason()).Msg("AI Patrol: Skipping scoped run - quickstart unavailable")
- return
- }
- if scopedUsingQuickstart && scopedQsMgr != nil && !scopedQsMgr.HasCredits() {
- p.setBlockedReason(patrolQuickstartCreditsExhaustedReason)
- log.Info().Msg("AI Patrol: Skipping scoped run - quickstart credits exhausted")
- return
- }
-
{
p.clearBlockedReason()
if !scope.NoStream {
@@ -879,14 +814,6 @@ func (p *PatrolService) runScopedPatrol(ctx context.Context, scope PatrolScope)
if aiErr != nil {
log.Warn().Err(aiErr).Msg("AI Patrol (scoped): LLM analysis failed")
runStats.errors++
- if scopedUsingQuickstart {
- switch {
- case providers.IsQuickstartCreditsExhausted(aiErr):
- p.setBlockedReason(patrolQuickstartCreditsExhaustedReason)
- case providers.IsQuickstartUnavailable(aiErr), quickstartBootstrapUnavailable(aiErr):
- p.setBlockedReason(patrolQuickstartUnavailableReason)
- }
- }
} else if aiResult != nil {
runStats.aiAnalysis = aiResult
runStats.rejectedFindings = aiResult.RejectedFindings
@@ -1580,31 +1507,6 @@ func (p *PatrolService) GetStatus() PatrolStatus {
status.TriggerStatus = &triggerStatus
}
- if p.quickstartCredits != nil {
- status.QuickstartCreditsRemaining = p.quickstartCredits.CreditsRemaining()
- status.QuickstartCreditsTotal = p.quickstartCredits.CreditsTotal()
- status.UsingQuickstart = p.aiService != nil && p.aiService.IsUsingQuickstart()
- }
-
- quickstartReason := ""
- if p.aiService != nil {
- quickstartReason = strings.TrimSpace(p.aiService.QuickstartBlockedReason())
- }
- if quickstartReason == "" &&
- p.config.Enabled &&
- p.quickstartCredits != nil &&
- !p.quickstartCredits.HasBYOK() &&
- !p.quickstartCredits.HasCredits() {
- quickstartReason = patrolQuickstartCreditsExhaustedReason
- }
- if quickstartReason != "" {
- status.BlockedReason = quickstartReason
- } else if strings.TrimSpace(status.BlockedReason) == patrolQuickstartCreditsExhaustedReason ||
- strings.TrimSpace(status.BlockedReason) == patrolQuickstartActivationRequiredReason ||
- strings.TrimSpace(status.BlockedReason) == patrolQuickstartUnavailableReason {
- status.BlockedReason = ""
- }
-
switch {
case analysisInProgress:
status.RuntimeState = PatrolRuntimeStateRunning
diff --git a/internal/ai/patrol_run_test.go b/internal/ai/patrol_run_test.go
index 7a58a2351a..4794ada8cc 100644
--- a/internal/ai/patrol_run_test.go
+++ b/internal/ai/patrol_run_test.go
@@ -1,37 +1,16 @@
package ai
import (
- "context"
"strings"
"sync"
"testing"
"time"
"github.com/prometheus/client_golang/prometheus/testutil"
- "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
- pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
)
-type stubPatrolQuickstartCreditManager struct {
- remaining int
- total int
- byok bool
-}
-
-func (m *stubPatrolQuickstartCreditManager) EnsureBootstrap(context.Context) error { return nil }
-func (m *stubPatrolQuickstartCreditManager) HasCredits() bool { return m.remaining > 0 }
-func (m *stubPatrolQuickstartCreditManager) CreditsRemaining() int { return m.remaining }
-func (m *stubPatrolQuickstartCreditManager) CreditsTotal() int {
- if m.total > 0 {
- return m.total
- }
- return pkglicensing.QuickstartCreditsTotal
-}
-func (m *stubPatrolQuickstartCreditManager) HasBYOK() bool { return m.byok }
-func (m *stubPatrolQuickstartCreditManager) GetProvider() providers.Provider { return nil }
-
// --- filterStateByScope tests ---
func TestFilterStateByScope_NoScope(t *testing.T) {
@@ -1485,53 +1464,6 @@ func TestGetStatus_BlockedReason(t *testing.T) {
}
}
-func TestGetStatus_QuickstartCreditsExhaustedBlocksRuntimeWithoutWaitingForRun(t *testing.T) {
- ps := NewPatrolService(nil, nil)
- ps.SetQuickstartCredits(&stubPatrolQuickstartCreditManager{remaining: 0})
-
- status := ps.GetStatus()
- if status.RuntimeState != PatrolRuntimeStateBlocked {
- t.Fatalf("runtime_state = %q, want %q", status.RuntimeState, PatrolRuntimeStateBlocked)
- }
- if status.BlockedReason != patrolQuickstartCreditsExhaustedReason {
- t.Fatalf("blocked_reason = %q, want %q", status.BlockedReason, patrolQuickstartCreditsExhaustedReason)
- }
- if status.Healthy {
- t.Fatal("expected blocked patrol status to report healthy=false")
- }
-}
-
-func TestGetStatus_ClearsStaleQuickstartBlockedStateWhenCreditsReturn(t *testing.T) {
- ps := NewPatrolService(nil, nil)
- quickstart := &stubPatrolQuickstartCreditManager{remaining: 0}
- ps.SetQuickstartCredits(quickstart)
- ps.setBlockedReason(patrolQuickstartCreditsExhaustedReason)
-
- blockedStatus := ps.GetStatus()
- if blockedStatus.RuntimeState != PatrolRuntimeStateBlocked {
- t.Fatalf("runtime_state = %q, want %q before refill", blockedStatus.RuntimeState, PatrolRuntimeStateBlocked)
- }
- if blockedStatus.BlockedAt == nil {
- t.Fatal("expected blocked_at to be present before refill")
- }
-
- quickstart.remaining = 3
-
- status := ps.GetStatus()
- if status.RuntimeState != PatrolRuntimeStateActive {
- t.Fatalf("runtime_state = %q, want %q after refill", status.RuntimeState, PatrolRuntimeStateActive)
- }
- if status.BlockedReason != "" {
- t.Fatalf("expected stale quickstart blocked_reason to clear after refill, got %q", status.BlockedReason)
- }
- if status.BlockedAt != nil {
- t.Fatalf("expected stale quickstart blocked_at to clear after refill, got %v", status.BlockedAt)
- }
- if !status.Healthy {
- t.Fatal("expected refilled quickstart status to return to healthy when there are no findings")
- }
-}
-
func TestShouldSkipInitialFullPatrol_IgnoresRecentScopedErrorRun(t *testing.T) {
now := time.Now()
skip := shouldSkipInitialFullPatrol([]PatrolRunRecord{
diff --git a/internal/ai/providers/quickstart.go b/internal/ai/providers/quickstart.go
deleted file mode 100644
index 2e67b64b7f..0000000000
--- a/internal/ai/providers/quickstart.go
+++ /dev/null
@@ -1,424 +0,0 @@
-package providers
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "os"
- "strings"
- "time"
-
- "github.com/rcourtman/pulse-go-rewrite/internal/config"
- "github.com/rs/zerolog/log"
-)
-
-const (
- // defaultQuickstartProxyURL is the owned public quickstart proxy surface.
- // The API key lives server-side — self-hosted binaries never see it.
- defaultQuickstartProxyURL = "https://license.pulserelay.pro/v1/quickstart/patrol"
-
- quickstartModel = config.DefaultAIModelQuickstart
- quickstartRequestTimeout = 300 * time.Second // 5 minutes
- quickstartMaxRetries = 2
- quickstartInitialBackoff = 2 * time.Second
-
- quickstartDataPolicyVersion = "resource-policy-v1"
-)
-
-// QuickstartClient implements the Provider interface for the Pulse-hosted
-// quickstart proxy. It forwards patrol chat requests through the public
-// commercial API edge so users don't need their own API key.
-type QuickstartClient struct {
- // licenseID is the legacy caller-chosen identity path.
- licenseID string
- // quickstartToken is the server-issued bearer token path.
- quickstartToken string
- client *http.Client
- onStateSync func(QuickstartServerState)
- onTokenInvalid func()
-}
-
-func quickstartProxyURL() string {
- if override := strings.TrimSpace(os.Getenv("PULSE_AI_QUICKSTART_PROXY_URL")); override != "" {
- return override
- }
- return defaultQuickstartProxyURL
-}
-
-// NewQuickstartClient creates a quickstart provider that uses the hosted proxy.
-// This is the legacy identity path retained for non-Patrol callers.
-func NewQuickstartClient(licenseID string) *QuickstartClient {
- return &QuickstartClient{
- licenseID: licenseID,
- client: &http.Client{
- Timeout: quickstartRequestTimeout,
- },
- }
-}
-
-// QuickstartServerState is the authoritative quickstart inventory snapshot
-// returned by the license server alongside a Patrol response.
-type QuickstartServerState struct {
- CreditsRemaining *int
- CreditsTotal *int
- TokenExpiresAt *time.Time
-}
-
-// NewQuickstartClientWithToken creates a quickstart provider that authenticates
-// requests with a server-issued bearer token.
-func NewQuickstartClientWithToken(quickstartToken string, onStateSync func(QuickstartServerState), onTokenInvalid func()) *QuickstartClient {
- return &QuickstartClient{
- quickstartToken: strings.TrimSpace(quickstartToken),
- onStateSync: onStateSync,
- onTokenInvalid: onTokenInvalid,
- client: &http.Client{
- Timeout: quickstartRequestTimeout,
- },
- }
-}
-
-// quickstartRequest is the payload sent to the hosted proxy.
-type quickstartRequest struct {
- Messages []Message `json:"messages"`
- System string `json:"system,omitempty"`
- Tools []Tool `json:"tools,omitempty"`
- ExecutionID string `json:"execution_id,omitempty"`
- DataPolicy quickstartDataPolicy `json:"data_policy"`
- // LicenseID is retained only for the legacy caller-chosen identity path.
- LicenseID string `json:"license_id,omitempty"`
-}
-
-type quickstartDataPolicy struct {
- Version string `json:"version"`
- ClientEnforced bool `json:"client_enforced"`
- LocalOnlyHandling string `json:"local_only_handling"`
- ResourceRedactionMode string `json:"resource_redaction_mode"`
-}
-
-// quickstartResponse is the response from the hosted proxy.
-type quickstartResponse struct {
- Content string `json:"content"`
- Model string `json:"model"`
- StopReason string `json:"stop_reason,omitempty"`
- ToolCalls []ToolCall `json:"tool_calls,omitempty"`
- InputTokens int `json:"input_tokens,omitempty"`
- OutputTokens int `json:"output_tokens,omitempty"`
- CreditsRemaining *int `json:"credits_remaining,omitempty"`
- CreditsTotal *int `json:"credits_total,omitempty"`
- QuickstartTokenExpiresAt string `json:"quickstart_token_expires_at,omitempty"`
- TokenExpiresAt string `json:"token_expires_at,omitempty"`
- Code string `json:"code,omitempty"`
- // Error is set when the server returns a structured error.
- Error string `json:"error,omitempty"`
-}
-
-// QuickstartRequestError captures a structured quickstart proxy failure.
-type QuickstartRequestError struct {
- StatusCode int
- Code string
- Message string
- CreditsRemaining int
- CreditsTotal int
-}
-
-func (e *QuickstartRequestError) Error() string {
- if e == nil {
- return "quickstart: request failed"
- }
- if msg := strings.TrimSpace(e.Message); msg != "" {
- return "quickstart: " + msg
- }
- return fmt.Sprintf("quickstart: server returned %d", e.StatusCode)
-}
-
-func (e *QuickstartRequestError) exhausted() bool {
- if e == nil {
- return false
- }
- if e.StatusCode == http.StatusPaymentRequired {
- return true
- }
- if strings.EqualFold(strings.TrimSpace(e.Code), "quickstart_credits_exhausted") {
- return true
- }
- return e.CreditsTotal > 0 && e.CreditsRemaining == 0
-}
-
-func (e *QuickstartRequestError) unavailable() bool {
- if e == nil {
- return false
- }
- switch e.StatusCode {
- case http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:
- return true
- default:
- return strings.Contains(strings.ToLower(strings.TrimSpace(e.Code)), "unavailable")
- }
-}
-
-// IsQuickstartCreditsExhausted reports whether err represents an exhausted
-// quickstart inventory response from the server.
-func IsQuickstartCreditsExhausted(err error) bool {
- typed, ok := err.(*QuickstartRequestError)
- return ok && typed.exhausted()
-}
-
-// IsQuickstartUnavailable reports whether err represents a quickstart transport
-// failure returned by the license server.
-func IsQuickstartUnavailable(err error) bool {
- typed, ok := err.(*QuickstartRequestError)
- return ok && typed.unavailable()
-}
-
-// Chat sends a chat request through the Pulse-hosted quickstart proxy.
-func (c *QuickstartClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse, error) {
- payload := quickstartRequest{
- Messages: req.Messages,
- System: req.System,
- Tools: req.Tools,
- ExecutionID: strings.TrimSpace(req.ExecutionID),
- DataPolicy: defaultQuickstartDataPolicy(),
- }
- if strings.TrimSpace(c.quickstartToken) == "" {
- payload.LicenseID = c.licenseID
- }
-
- body, err := json.Marshal(payload)
- if err != nil {
- return nil, fmt.Errorf("quickstart: marshal request: %w", err)
- }
-
- var lastErr error
- backoff := quickstartInitialBackoff
-
- for attempt := 0; attempt <= quickstartMaxRetries; attempt++ {
- if attempt > 0 {
- select {
- case <-ctx.Done():
- return nil, ctx.Err()
- case <-time.After(backoff):
- backoff *= 2
- }
- }
-
- httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, quickstartProxyURL(), bytes.NewReader(body))
- if err != nil {
- return nil, fmt.Errorf("quickstart: create request: %w", err)
- }
- httpReq.Header.Set("Content-Type", "application/json")
- if token := strings.TrimSpace(c.quickstartToken); token != "" {
- httpReq.Header.Set("Authorization", "Bearer "+token)
- }
-
- resp, err := c.client.Do(httpReq)
- if err != nil {
- lastErr = fmt.Errorf("quickstart: request failed: %w", err)
- log.Warn().Err(err).Int("attempt", attempt+1).Msg("Quickstart proxy request failed")
- continue
- }
-
- respBody, readErr := io.ReadAll(resp.Body)
- resp.Body.Close()
- if readErr != nil {
- lastErr = fmt.Errorf("quickstart: read response: %w", readErr)
- continue
- }
-
- if resp.StatusCode != http.StatusOK {
- var failure quickstartResponse
- if err := json.Unmarshal(respBody, &failure); err == nil {
- if failure.Code == "quickstart_credits_exhausted" && failure.CreditsRemaining == nil {
- remaining := 0
- failure.CreditsRemaining = &remaining
- }
- c.syncServerState(failure)
- }
- if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
- c.invalidateToken()
- }
- lastErr = &QuickstartRequestError{
- StatusCode: resp.StatusCode,
- Code: strings.TrimSpace(failure.Code),
- Message: firstNonEmpty(strings.TrimSpace(failure.Error), strings.TrimSpace(string(respBody))),
- CreditsRemaining: quickstartOptionalInt(failure.CreditsRemaining),
- CreditsTotal: quickstartOptionalInt(failure.CreditsTotal),
- }
- // Don't retry on client errors (4xx)
- if resp.StatusCode >= 400 && resp.StatusCode < 500 {
- return nil, lastErr
- }
- continue
- }
-
- var result quickstartResponse
- if err := json.Unmarshal(respBody, &result); err != nil {
- return nil, fmt.Errorf("quickstart: decode response: %w", err)
- }
-
- if result.Error != "" {
- return nil, fmt.Errorf("quickstart: server error: %s", result.Error)
- }
- c.syncServerState(result)
-
- return &ChatResponse{
- Content: result.Content,
- Model: result.Model,
- StopReason: result.StopReason,
- ToolCalls: result.ToolCalls,
- InputTokens: result.InputTokens,
- OutputTokens: result.OutputTokens,
- }, nil
- }
-
- return nil, lastErr
-}
-
-// TestConnection validates connectivity to the quickstart proxy.
-func (c *QuickstartClient) TestConnection(ctx context.Context) error {
- // Simple connectivity check — send a minimal request.
- payload := quickstartRequest{
- Messages: []Message{},
- DataPolicy: defaultQuickstartDataPolicy(),
- }
- if strings.TrimSpace(c.quickstartToken) == "" {
- payload.LicenseID = c.licenseID
- }
- body, err := json.Marshal(payload)
- if err != nil {
- return fmt.Errorf("quickstart: marshal test request: %w", err)
- }
- httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, quickstartProxyURL(), bytes.NewReader(body))
- if err != nil {
- return fmt.Errorf("quickstart: create test request: %w", err)
- }
- httpReq.Header.Set("Content-Type", "application/json")
- if token := strings.TrimSpace(c.quickstartToken); token != "" {
- httpReq.Header.Set("Authorization", "Bearer "+token)
- }
-
- resp, err := c.client.Do(httpReq)
- if err != nil {
- return fmt.Errorf("quickstart credits require internet access. Connect your API key for offline AI Patrol")
- }
- resp.Body.Close()
-
- // Any response (even 400) means the server is reachable.
- return nil
-}
-
-func defaultQuickstartDataPolicy() quickstartDataPolicy {
- return quickstartDataPolicy{
- Version: quickstartDataPolicyVersion,
- ClientEnforced: true,
- LocalOnlyHandling: "aggregate_only",
- ResourceRedactionMode: "resource_policy_exact_values",
- }
-}
-
-// Name returns the provider name.
-func (c *QuickstartClient) Name() string {
- return "quickstart"
-}
-
-// ChatStream implements StreamingProvider by calling Chat and emitting the result
-// as a single content event. The quickstart proxy is synchronous (no server-sent events).
-func (c *QuickstartClient) ChatStream(ctx context.Context, req ChatRequest, callback StreamCallback) error {
- resp, err := c.Chat(ctx, req)
- if err != nil {
- return err
- }
-
- // Emit content as a single event
- if resp.Content != "" {
- callback(StreamEvent{Type: "content", Data: ContentEvent{Text: resp.Content}})
- }
-
- // Emit tool calls as ToolStartEvent (matches what the agentic loop expects)
- for _, tc := range resp.ToolCalls {
- callback(StreamEvent{Type: "tool_start", Data: ToolStartEvent{
- ID: tc.ID,
- Name: tc.Name,
- Input: tc.Input,
- }})
- }
-
- // Emit done with usage and tool calls (agentic loop reads ToolCalls from DoneEvent)
- callback(StreamEvent{Type: "done", Data: DoneEvent{
- StopReason: resp.StopReason,
- ToolCalls: resp.ToolCalls,
- InputTokens: resp.InputTokens,
- OutputTokens: resp.OutputTokens,
- }})
-
- return nil
-}
-
-// SupportsThinking returns false — the quickstart model does not support extended thinking.
-func (c *QuickstartClient) SupportsThinking(_ string) bool {
- return false
-}
-
-// ListModels returns the single model available via quickstart.
-func (c *QuickstartClient) ListModels(_ context.Context) ([]ModelInfo, error) {
- return []ModelInfo{
- {
- ID: quickstartModel,
- Name: "Pulse Hosted Quickstart",
- Notable: true,
- },
- }, nil
-}
-
-func (c *QuickstartClient) syncServerState(result quickstartResponse) {
- if c == nil || c.onStateSync == nil {
- return
- }
- state := QuickstartServerState{}
- hasState := false
- if result.CreditsRemaining != nil {
- remaining := *result.CreditsRemaining
- state.CreditsRemaining = &remaining
- hasState = true
- }
- if result.CreditsTotal != nil {
- total := *result.CreditsTotal
- state.CreditsTotal = &total
- hasState = true
- }
- if rawExpiry := firstNonEmpty(result.QuickstartTokenExpiresAt, result.TokenExpiresAt); rawExpiry != "" {
- if parsed, err := time.Parse(time.RFC3339, rawExpiry); err == nil {
- state.TokenExpiresAt = &parsed
- hasState = true
- }
- }
- if !hasState {
- return
- }
- c.onStateSync(state)
-}
-
-func (c *QuickstartClient) invalidateToken() {
- if c == nil || c.onTokenInvalid == nil {
- return
- }
- c.onTokenInvalid()
-}
-
-func firstNonEmpty(values ...string) string {
- for _, value := range values {
- if trimmed := strings.TrimSpace(value); trimmed != "" {
- return trimmed
- }
- }
- return ""
-}
-
-func quickstartOptionalInt(v *int) int {
- if v == nil {
- return 0
- }
- return *v
-}
diff --git a/internal/ai/providers/quickstart_test.go b/internal/ai/providers/quickstart_test.go
deleted file mode 100644
index 06be227b5d..0000000000
--- a/internal/ai/providers/quickstart_test.go
+++ /dev/null
@@ -1,250 +0,0 @@
-package providers
-
-import (
- "context"
- "encoding/json"
- "net/http"
- "net/http/httptest"
- "testing"
- "time"
-)
-
-func TestQuickstartProxyURL_Default(t *testing.T) {
- t.Setenv("PULSE_AI_QUICKSTART_PROXY_URL", "")
- if got := quickstartProxyURL(); got != defaultQuickstartProxyURL {
- t.Fatalf("quickstartProxyURL()=%q want %q", got, defaultQuickstartProxyURL)
- }
-}
-
-func TestQuickstartClientChat_UsesOverrideProxyURL(t *testing.T) {
- var seenLicenseID string
- var seenDataPolicy quickstartDataPolicy
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- var req quickstartRequest
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- t.Fatalf("decode request: %v", err)
- }
- seenLicenseID = req.LicenseID
- seenDataPolicy = req.DataPolicy
- w.Header().Set("Content-Type", "application/json")
- if err := json.NewEncoder(w).Encode(quickstartResponse{
- Content: "hello",
- Model: quickstartModel,
- StopReason: "end_turn",
- }); err != nil {
- t.Fatalf("encode response: %v", err)
- }
- }))
- defer server.Close()
-
- t.Setenv("PULSE_AI_QUICKSTART_PROXY_URL", server.URL)
-
- client := NewQuickstartClient("lic_test")
- resp, err := client.Chat(context.Background(), ChatRequest{
- Messages: []Message{{Role: "user", Content: "Hi"}},
- })
- if err != nil {
- t.Fatalf("Chat(): %v", err)
- }
- if seenLicenseID != "lic_test" {
- t.Fatalf("license_id=%q want lic_test", seenLicenseID)
- }
- if seenDataPolicy.Version != quickstartDataPolicyVersion || !seenDataPolicy.ClientEnforced {
- t.Fatalf("data_policy=%#v want enforced %s", seenDataPolicy, quickstartDataPolicyVersion)
- }
- if resp.Content != "hello" {
- t.Fatalf("content=%q want hello", resp.Content)
- }
-}
-
-func TestQuickstartClientWithToken_UsesBearerAuthAndSyncsServerState(t *testing.T) {
- var seenAuthorization string
- var seenLicenseID string
- var seenExecutionID string
- var seenDataPolicy quickstartDataPolicy
- var synced QuickstartServerState
- var syncCalls int
- remaining := 16
- total := 25
-
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- var req quickstartRequest
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- t.Fatalf("decode request: %v", err)
- }
- seenAuthorization = r.Header.Get("Authorization")
- seenLicenseID = req.LicenseID
- seenExecutionID = req.ExecutionID
- seenDataPolicy = req.DataPolicy
- w.Header().Set("Content-Type", "application/json")
- if err := json.NewEncoder(w).Encode(quickstartResponse{
- Content: "hello",
- Model: quickstartModel,
- StopReason: "end_turn",
- CreditsRemaining: &remaining,
- CreditsTotal: &total,
- QuickstartTokenExpiresAt: "2026-04-02T12:00:00Z",
- }); err != nil {
- t.Fatalf("encode response: %v", err)
- }
- }))
- defer server.Close()
-
- t.Setenv("PULSE_AI_QUICKSTART_PROXY_URL", server.URL)
-
- client := NewQuickstartClientWithToken("qst_live_test", func(state QuickstartServerState) {
- synced = state
- syncCalls++
- }, nil)
- resp, err := client.Chat(context.Background(), ChatRequest{
- Messages: []Message{{Role: "user", Content: "Hi"}},
- ExecutionID: "patrol-run-123",
- })
- if err != nil {
- t.Fatalf("Chat(): %v", err)
- }
- if seenAuthorization != "Bearer qst_live_test" {
- t.Fatalf("Authorization=%q want Bearer qst_live_test", seenAuthorization)
- }
- if seenLicenseID != "" {
- t.Fatalf("license_id=%q want empty for bearer-token quickstart", seenLicenseID)
- }
- if seenExecutionID != "patrol-run-123" {
- t.Fatalf("execution_id=%q want patrol-run-123", seenExecutionID)
- }
- if seenDataPolicy.Version != quickstartDataPolicyVersion || seenDataPolicy.LocalOnlyHandling != "aggregate_only" {
- t.Fatalf("data_policy=%#v want local-only aggregate policy", seenDataPolicy)
- }
- if resp.Content != "hello" {
- t.Fatalf("content=%q want hello", resp.Content)
- }
- if syncCalls != 1 {
- t.Fatalf("syncCalls=%d want 1", syncCalls)
- }
- if synced.CreditsRemaining == nil || synced.CreditsTotal == nil {
- t.Fatalf("expected synced credits, got %v/%v", synced.CreditsRemaining, synced.CreditsTotal)
- }
- if *synced.CreditsRemaining != 16 || *synced.CreditsTotal != 25 {
- t.Fatalf("synced credits=%d/%d want 16/25", *synced.CreditsRemaining, *synced.CreditsTotal)
- }
- if synced.TokenExpiresAt == nil {
- t.Fatal("expected token expiry sync")
- }
- if got := synced.TokenExpiresAt.UTC().Format(time.RFC3339); got != "2026-04-02T12:00:00Z" {
- t.Fatalf("TokenExpiresAt=%q want 2026-04-02T12:00:00Z", got)
- }
-}
-
-func TestQuickstartClientWithToken_AcceptsTokenExpiresAtAlias(t *testing.T) {
- var synced QuickstartServerState
-
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- remaining := 24
- total := 25
- w.Header().Set("Content-Type", "application/json")
- if err := json.NewEncoder(w).Encode(quickstartResponse{
- Content: "hello",
- Model: quickstartModel,
- StopReason: "end_turn",
- CreditsRemaining: &remaining,
- CreditsTotal: &total,
- TokenExpiresAt: "2026-04-03T19:00:00Z",
- }); err != nil {
- t.Fatalf("encode response: %v", err)
- }
- }))
- defer server.Close()
-
- t.Setenv("PULSE_AI_QUICKSTART_PROXY_URL", server.URL)
-
- client := NewQuickstartClientWithToken("qst_live_test", func(state QuickstartServerState) {
- synced = state
- }, nil)
- if _, err := client.Chat(context.Background(), ChatRequest{
- Messages: []Message{{Role: "user", Content: "Hi"}},
- }); err != nil {
- t.Fatalf("Chat(): %v", err)
- }
- if synced.TokenExpiresAt == nil {
- t.Fatal("expected token expiry sync")
- }
- if got := synced.TokenExpiresAt.UTC().Format(time.RFC3339); got != "2026-04-03T19:00:00Z" {
- t.Fatalf("TokenExpiresAt=%q want 2026-04-03T19:00:00Z", got)
- }
-}
-
-func TestQuickstartClientWithToken_ExhaustionSyncsStateAndReturnsTypedError(t *testing.T) {
- var synced QuickstartServerState
- var syncCalls int
-
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(http.StatusPaymentRequired)
- w.Header().Set("Content-Type", "application/json")
- remaining := 0
- total := 25
- if err := json.NewEncoder(w).Encode(quickstartResponse{
- Error: "credits exhausted",
- Code: "quickstart_credits_exhausted",
- CreditsRemaining: &remaining,
- CreditsTotal: &total,
- }); err != nil {
- t.Fatalf("encode response: %v", err)
- }
- }))
- defer server.Close()
-
- t.Setenv("PULSE_AI_QUICKSTART_PROXY_URL", server.URL)
-
- client := NewQuickstartClientWithToken("qst_live_test", func(state QuickstartServerState) {
- synced = state
- syncCalls++
- }, nil)
- _, err := client.Chat(context.Background(), ChatRequest{
- Messages: []Message{{Role: "user", Content: "Hi"}},
- })
- if err == nil {
- t.Fatal("expected quickstart exhaustion error")
- }
- if !IsQuickstartCreditsExhausted(err) {
- t.Fatalf("expected typed quickstart exhaustion, got %v", err)
- }
- if syncCalls != 1 {
- t.Fatalf("syncCalls=%d want 1", syncCalls)
- }
- if synced.CreditsRemaining == nil || synced.CreditsTotal == nil {
- t.Fatalf("expected synced credits, got %v/%v", synced.CreditsRemaining, synced.CreditsTotal)
- }
- if *synced.CreditsRemaining != 0 || *synced.CreditsTotal != 25 {
- t.Fatalf("synced credits=%d/%d want 0/25", *synced.CreditsRemaining, *synced.CreditsTotal)
- }
-}
-
-func TestQuickstartClientWithToken_DoesNotZeroCreditsWhenErrorOmitsInventory(t *testing.T) {
- var syncCalls int
-
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(http.StatusBadGateway)
- w.Header().Set("Content-Type", "application/json")
- if err := json.NewEncoder(w).Encode(quickstartResponse{
- Error: "temporary upstream failure",
- }); err != nil {
- t.Fatalf("encode response: %v", err)
- }
- }))
- defer server.Close()
-
- t.Setenv("PULSE_AI_QUICKSTART_PROXY_URL", server.URL)
-
- client := NewQuickstartClientWithToken("qst_live_test", func(state QuickstartServerState) {
- syncCalls++
- }, nil)
- _, err := client.Chat(context.Background(), ChatRequest{
- Messages: []Message{{Role: "user", Content: "Hi"}},
- })
- if err == nil {
- t.Fatal("expected quickstart error")
- }
- if syncCalls != 0 {
- t.Fatalf("syncCalls=%d want 0 when error omits inventory", syncCalls)
- }
-}
diff --git a/internal/ai/quickstart.go b/internal/ai/quickstart.go
deleted file mode 100644
index 3588ea3d19..0000000000
--- a/internal/ai/quickstart.go
+++ /dev/null
@@ -1,603 +0,0 @@
-package ai
-
-import (
- "context"
- "errors"
- "fmt"
- "net/http"
- "os"
- "strings"
- "sync"
- "time"
-
- "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
- "github.com/rcourtman/pulse-go-rewrite/internal/config"
- pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
- "github.com/rs/zerolog/log"
-)
-
-const (
- quickstartBootstrapUseCase = "patrol"
- quickstartBootstrapRefreshWindow = 5 * time.Minute
- quickstartProviderUnavailableText = "Quickstart credits require internet access. Connect your API key for offline AI Patrol."
-)
-
-// QuickstartCreditManager owns the persisted quickstart bootstrap state used by
-// Patrol when no BYOK provider is configured. Cached local state is never
-// authoritative for entitlement; it only memoizes the last server snapshot.
-type QuickstartCreditManager interface {
- EnsureBootstrap(ctx context.Context) error
- HasCredits() bool
- CreditsRemaining() int
- CreditsTotal() int
- HasBYOK() bool
- GetProvider() providers.Provider
-}
-
-type quickstartBootstrapClient interface {
- BootstrapQuickstart(ctx context.Context, bearerToken string, req pkglicensing.QuickstartBootstrapRequest) (*pkglicensing.QuickstartBootstrapResponse, error)
-}
-
-// PersistentQuickstartCreditManager persists the server-issued quickstart token
-// and the latest server-reported inventory in quickstart.enc.
-type PersistentQuickstartCreditManager struct {
- mu sync.RWMutex
- orgID string
- persistence *config.ConfigPersistence
- aiConfig func() *config.AIConfig
- client quickstartBootstrapClient
- now func() time.Time
- hostname func() (string, error)
- state *config.QuickstartState
-}
-
-// NewPersistentQuickstartCreditManager creates a server-authoritative
-// quickstart manager backed by quickstart.enc.
-func NewPersistentQuickstartCreditManager(
- persistence *config.ConfigPersistence,
- orgID string,
- aiConfigGetter func() *config.AIConfig,
-) *PersistentQuickstartCreditManager {
- return NewPersistentQuickstartCreditManagerWithClient(
- persistence,
- orgID,
- aiConfigGetter,
- pkglicensing.NewLicenseServerClient(""),
- )
-}
-
-// NewPersistentQuickstartCreditManagerWithClient exists for unit tests.
-func NewPersistentQuickstartCreditManagerWithClient(
- persistence *config.ConfigPersistence,
- orgID string,
- aiConfigGetter func() *config.AIConfig,
- client quickstartBootstrapClient,
-) *PersistentQuickstartCreditManager {
- if aiConfigGetter == nil {
- aiConfigGetter = func() *config.AIConfig { return nil }
- }
- if client == nil {
- client = pkglicensing.NewLicenseServerClient("")
- }
- return &PersistentQuickstartCreditManager{
- orgID: strings.TrimSpace(orgID),
- persistence: persistence,
- aiConfig: aiConfigGetter,
- client: client,
- now: func() time.Time { return time.Now().UTC() },
- hostname: os.Hostname,
- }
-}
-
-func (m *PersistentQuickstartCreditManager) EnsureBootstrap(ctx context.Context) error {
- if m == nil {
- return fmt.Errorf("quickstart: manager unavailable")
- }
- if ctx == nil {
- ctx = context.Background()
- }
-
- m.mu.Lock()
- defer m.mu.Unlock()
-
- state, err := m.loadStateLocked()
- if err != nil {
- return err
- }
- bearerToken, fingerprint, err := m.secureBootstrapIdentityLocked()
- if err != nil {
- return err
- }
- if !m.bootstrapNeededLocked(state, m.now()) {
- return nil
- }
-
- req, err := m.bootstrapRequestLocked(fingerprint)
- if err != nil {
- return err
- }
-
- resp, err := m.client.BootstrapQuickstart(ctx, bearerToken, req)
- if err != nil {
- if quickstartBootstrapCreditsExhausted(err) {
- state.QuickstartCreditsRemaining = 0
- nowUnix := m.now().Unix()
- state.LastSyncedAt = &nowUnix
- if persistErr := m.persistence.SaveQuickstartState(*config.NormalizeQuickstartState(state)); persistErr != nil {
- log.Warn().Err(persistErr).Str("orgID", m.orgID).Msg("Quickstart: failed to persist exhausted bootstrap state")
- }
- }
- return err
- }
-
- m.applyBootstrapLocked(state, resp)
- return m.persistence.SaveQuickstartState(*config.NormalizeQuickstartState(state))
-}
-
-func (m *PersistentQuickstartCreditManager) HasCredits() bool {
- if m == nil {
- return false
- }
-
- m.mu.Lock()
- defer m.mu.Unlock()
-
- state, err := m.loadStateLocked()
- if err != nil {
- log.Warn().Err(err).Str("orgID", m.orgID).Msg("Quickstart: failed to read cached state")
- return false
- }
- if state == nil || state.QuickstartCreditsRemaining <= 0 {
- return false
- }
- _, _, err = m.secureBootstrapIdentityLocked()
- return err == nil
-}
-
-func (m *PersistentQuickstartCreditManager) CreditsRemaining() int {
- if m == nil {
- return 0
- }
-
- m.mu.Lock()
- defer m.mu.Unlock()
-
- state, err := m.loadStateLocked()
- if err != nil {
- log.Warn().Err(err).Str("orgID", m.orgID).Msg("Quickstart: failed to read cached state")
- return 0
- }
- if state == nil {
- return 0
- }
- if _, _, err := m.secureBootstrapIdentityLocked(); err != nil {
- return 0
- }
- return state.QuickstartCreditsRemaining
-}
-
-func (m *PersistentQuickstartCreditManager) CreditsTotal() int {
- if m == nil {
- return 0
- }
-
- m.mu.Lock()
- defer m.mu.Unlock()
-
- state, err := m.loadStateLocked()
- if err != nil {
- log.Warn().Err(err).Str("orgID", m.orgID).Msg("Quickstart: failed to read cached state")
- return 0
- }
- if state == nil {
- return 0
- }
- if _, _, err := m.secureBootstrapIdentityLocked(); err != nil {
- return 0
- }
- return state.QuickstartCreditsTotal
-}
-
-func (m *PersistentQuickstartCreditManager) HasBYOK() bool {
- if m == nil || m.aiConfig == nil {
- return false
- }
- cfg := m.aiConfig()
- if cfg == nil {
- return false
- }
- return len(cfg.GetConfiguredProviders()) > 0
-}
-
-func (m *PersistentQuickstartCreditManager) GetProvider() providers.Provider {
- if m == nil {
- return nil
- }
-
- m.mu.Lock()
- defer m.mu.Unlock()
-
- state, err := m.loadStateLocked()
- if err != nil {
- log.Warn().Err(err).Str("orgID", m.orgID).Msg("Quickstart: failed to load cached quickstart state")
- return nil
- }
- if state == nil || state.QuickstartCreditsRemaining <= 0 {
- return nil
- }
- if _, _, err := m.secureBootstrapIdentityLocked(); err != nil {
- return nil
- }
- if strings.TrimSpace(state.QuickstartToken) == "" || state.TokenExpired(m.now()) {
- return nil
- }
-
- token := state.QuickstartToken
- return providers.NewQuickstartClientWithToken(
- token,
- m.syncServerState,
- m.invalidateToken,
- )
-}
-
-func (m *PersistentQuickstartCreditManager) stateSnapshot() *config.QuickstartState {
- if m == nil {
- return nil
- }
-
- m.mu.Lock()
- defer m.mu.Unlock()
-
- state, err := m.loadStateLocked()
- if err != nil {
- log.Warn().Err(err).Str("orgID", m.orgID).Msg("Quickstart: failed to read cached state")
- return &config.QuickstartState{}
- }
- return config.NormalizeQuickstartState(state)
-}
-
-func (m *PersistentQuickstartCreditManager) loadStateLocked() (*config.QuickstartState, error) {
- if m.state != nil {
- return m.state, nil
- }
- if m.persistence == nil {
- m.state = &config.QuickstartState{}
- return m.state, fmt.Errorf("quickstart: persistence unavailable")
- }
- state, err := m.persistence.LoadQuickstartState()
- if err != nil {
- return nil, fmt.Errorf("quickstart: load quickstart state: %w", err)
- }
- m.state = config.NormalizeQuickstartState(state)
- return m.state, nil
-}
-
-func (m *PersistentQuickstartCreditManager) bootstrapNeededLocked(state *config.QuickstartState, now time.Time) bool {
- if state == nil {
- return true
- }
- if strings.TrimSpace(state.QuickstartToken) == "" {
- return true
- }
- if state.TokenExpired(now) {
- return true
- }
- if state.LastSyncedAt == nil || *state.LastSyncedAt <= 0 {
- return true
- }
- return now.Unix()-*state.LastSyncedAt >= int64(quickstartBootstrapRefreshWindow/time.Second)
-}
-
-func (m *PersistentQuickstartCreditManager) bootstrapRequestLocked(fingerprint string) (pkglicensing.QuickstartBootstrapRequest, error) {
- instanceName := ""
- if hostname, err := m.hostname(); err == nil {
- instanceName = strings.TrimSpace(hostname)
- }
-
- return pkglicensing.QuickstartBootstrapRequest{
- InstanceFingerprint: strings.TrimSpace(fingerprint),
- InstanceName: instanceName,
- UseCase: quickstartBootstrapUseCase,
- }, nil
-}
-
-func (m *PersistentQuickstartCreditManager) applyBootstrapLocked(state *config.QuickstartState, resp *pkglicensing.QuickstartBootstrapResponse) {
- if state == nil || resp == nil {
- return
- }
-
- state.QuickstartToken = strings.TrimSpace(resp.QuickstartToken)
- state.QuickstartCreditsRemaining = max(0, resp.CreditsRemaining)
- state.QuickstartCreditsTotal = max(0, resp.CreditsTotal)
- if expiry := parseQuickstartRFC3339(resp.QuickstartTokenExpiresAt); expiry != nil {
- state.QuickstartTokenExpiresAt = expiry
- } else {
- state.QuickstartTokenExpiresAt = nil
- }
- nowUnix := m.now().Unix()
- state.LastSyncedAt = &nowUnix
-}
-
-func (m *PersistentQuickstartCreditManager) syncServerState(serverState providers.QuickstartServerState) {
- if m == nil {
- return
- }
-
- m.mu.Lock()
- defer m.mu.Unlock()
-
- state, err := m.loadStateLocked()
- if err != nil {
- log.Warn().Err(err).Str("orgID", m.orgID).Msg("Quickstart: failed to load cached state for sync")
- return
- }
-
- updated := false
- if serverState.CreditsRemaining != nil {
- state.QuickstartCreditsRemaining = max(0, *serverState.CreditsRemaining)
- updated = true
- }
- if serverState.CreditsTotal != nil {
- state.QuickstartCreditsTotal = max(0, *serverState.CreditsTotal)
- updated = true
- }
- if serverState.TokenExpiresAt != nil {
- expiryUnix := serverState.TokenExpiresAt.UTC().Unix()
- state.QuickstartTokenExpiresAt = &expiryUnix
- updated = true
- }
- if !updated {
- return
- }
- nowUnix := m.now().Unix()
- state.LastSyncedAt = &nowUnix
-
- if m.persistence == nil {
- return
- }
- if err := m.persistence.SaveQuickstartState(*config.NormalizeQuickstartState(state)); err != nil {
- log.Warn().Err(err).Str("orgID", m.orgID).Msg("Quickstart: failed to persist synced server state")
- }
-}
-
-func (m *PersistentQuickstartCreditManager) invalidateToken() {
- if m == nil {
- return
- }
-
- m.mu.Lock()
- defer m.mu.Unlock()
-
- state, err := m.loadStateLocked()
- if err != nil {
- log.Warn().Err(err).Str("orgID", m.orgID).Msg("Quickstart: failed to load cached state for token invalidation")
- return
- }
-
- state.QuickstartToken = ""
- state.QuickstartTokenExpiresAt = nil
- nowUnix := m.now().Unix()
- state.LastSyncedAt = &nowUnix
-
- if m.persistence == nil {
- return
- }
- if err := m.persistence.SaveQuickstartState(*config.NormalizeQuickstartState(state)); err != nil {
- log.Warn().Err(err).Str("orgID", m.orgID).Msg("Quickstart: failed to persist invalidated token state")
- }
-}
-
-func (m *PersistentQuickstartCreditManager) secureBootstrapIdentityLocked() (string, string, error) {
- if m.persistence == nil {
- return "", "", fmt.Errorf("quickstart: persistence unavailable")
- }
-
- if bearerToken, fingerprint, ok, err := m.installationBootstrapIdentityLocked(); err != nil {
- return "", "", err
- } else if ok {
- return bearerToken, fingerprint, nil
- }
-
- return m.entitlementBootstrapIdentityLocked()
-}
-
-func (m *PersistentQuickstartCreditManager) installationBootstrapIdentityLocked() (string, string, bool, error) {
- if m == nil || m.persistence == nil {
- return "", "", false, fmt.Errorf("quickstart: persistence unavailable")
- }
-
- licensePersistence, err := pkglicensing.NewPersistence(m.persistence.SharedInstallationDataDir())
- if err != nil {
- return "", "", false, fmt.Errorf("quickstart: load license persistence: %w", err)
- }
- activationState, err := licensePersistence.LoadActivationState()
- if err != nil {
- return "", "", false, fmt.Errorf("quickstart: load activation state: %w", err)
- }
- if activationState == nil {
- return "", "", false, nil
- }
-
- installationToken := strings.TrimSpace(activationState.InstallationToken)
- instanceFingerprint := strings.TrimSpace(activationState.InstanceFingerprint)
- if installationToken == "" || instanceFingerprint == "" {
- return "", "", false, nil
- }
-
- return installationToken, instanceFingerprint, true, nil
-}
-
-func (m *PersistentQuickstartCreditManager) entitlementBootstrapIdentityLocked() (string, string, error) {
- if m == nil || m.persistence == nil {
- return "", "", fmt.Errorf("quickstart: persistence unavailable")
- }
-
- state, _, err := config.LoadEffectiveEntitlementBillingState(m.persistence.SharedInstallationDataDir(), m.orgID)
- if err != nil {
- return "", "", fmt.Errorf("quickstart: load entitlement billing state: %w", err)
- }
-
- entitlementJWT := ""
- if state != nil {
- entitlementJWT = strings.TrimSpace(state.EntitlementJWT)
- }
- if entitlementJWT == "" {
- return "", "", quickstartActivationRequiredError()
- }
-
- publicKey, err := pkglicensing.TrialActivationPublicKey()
- if err != nil {
- return "", "", fmt.Errorf("quickstart: load entitlement verification key: %w", err)
- }
-
- claims, err := pkglicensing.VerifyEntitlementLeaseToken(entitlementJWT, publicKey, "", m.now())
- if err != nil {
- return "", "", fmt.Errorf("quickstart: verify entitlement lease: %w", err)
- }
- if !quickstartEntitlementSupportsPatrol(claims) {
- return "", "", quickstartActivationRequiredError()
- }
-
- return entitlementJWT, "", nil
-}
-
-func quickstartEntitlementSupportsPatrol(claims *pkglicensing.EntitlementLeaseClaims) bool {
- if claims == nil {
- return false
- }
- switch claims.SubscriptionState {
- case pkglicensing.SubStateActive, pkglicensing.SubStateGrace, pkglicensing.SubStateTrial:
- default:
- return false
- }
- for _, capability := range claims.Capabilities {
- switch strings.TrimSpace(capability) {
- case pkglicensing.FeatureAIPatrol, pkglicensing.FeatureAIAutoFix:
- return true
- }
- }
- return false
-}
-
-func quickstartBlockedReasonFromError(err error) string {
- switch {
- case err == nil:
- return ""
- case providers.IsQuickstartCreditsExhausted(err), quickstartBootstrapCreditsExhausted(err):
- return patrolQuickstartCreditsExhaustedReason
- case quickstartBootstrapActivationRequired(err):
- return patrolQuickstartActivationRequiredReason
- case providers.IsQuickstartUnavailable(err), quickstartBootstrapUnavailable(err):
- return patrolQuickstartUnavailableReason
- default:
- return quickstartProviderUnavailableText
- }
-}
-
-// QuickstartBlockedReasonForError exposes quickstart block classification to
-// adjacent runtime/API layers without duplicating the mapping logic.
-func QuickstartBlockedReasonForError(err error) string {
- return quickstartBlockedReasonFromError(err)
-}
-
-// QuickstartCreditsExhaustedReason returns the canonical Patrol quickstart
-// availability message shown when the install has consumed its quickstart runs.
-func QuickstartCreditsExhaustedReason() string {
- return patrolQuickstartCreditsExhaustedReason
-}
-
-// QuickstartUnavailableReason returns the canonical Patrol quickstart
-// availability message shown when the server-authoritative bootstrap path
-// cannot be reached.
-func QuickstartUnavailableReason() string {
- return patrolQuickstartUnavailableReason
-}
-
-// QuickstartActivationRequiredReason returns the canonical Patrol quickstart
-// availability message shown when the install is not activated.
-func QuickstartActivationRequiredReason() string {
- return patrolQuickstartActivationRequiredReason
-}
-
-func quickstartActivationRequiredError() error {
- return &pkglicensing.LicenseServerError{
- StatusCode: http.StatusUnauthorized,
- Code: "activation_required",
- Message: "Quickstart bootstrap requires Pulse Account activation",
- Retryable: false,
- }
-}
-
-func quickstartBootstrapCreditsExhausted(err error) bool {
- var serverErr *pkglicensing.LicenseServerError
- if !errors.As(err, &serverErr) {
- return false
- }
- if serverErr.StatusCode == http.StatusPaymentRequired {
- return true
- }
- return strings.EqualFold(strings.TrimSpace(serverErr.Code), "quickstart_credits_exhausted")
-}
-
-func quickstartBootstrapActivationRequired(err error) bool {
- var serverErr *pkglicensing.LicenseServerError
- if !errors.As(err, &serverErr) {
- return false
- }
- switch serverErr.StatusCode {
- case http.StatusUnauthorized, http.StatusForbidden:
- return true
- }
-
- switch strings.ToLower(strings.TrimSpace(serverErr.Code)) {
- case "activation_required", "installation_required", "invalid_installation_token", "invalid_token":
- return true
- default:
- return false
- }
-}
-
-func quickstartBootstrapUnavailable(err error) bool {
- var serverErr *pkglicensing.LicenseServerError
- if errors.As(err, &serverErr) {
- switch serverErr.StatusCode {
- case http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:
- return true
- }
- return serverErr.Retryable
- }
-
- lower := strings.ToLower(strings.TrimSpace(err.Error()))
- switch {
- case strings.Contains(lower, "connection refused"),
- strings.Contains(lower, "no such host"),
- strings.Contains(lower, "dial tcp"),
- strings.Contains(lower, "i/o timeout"),
- strings.Contains(lower, "context deadline exceeded"),
- strings.Contains(lower, "network is unreachable"),
- strings.Contains(lower, "network unreachable"):
- return true
- default:
- return false
- }
-}
-
-func parseQuickstartRFC3339(raw string) *int64 {
- raw = strings.TrimSpace(raw)
- if raw == "" {
- return nil
- }
- parsed, err := time.Parse(time.RFC3339, raw)
- if err != nil {
- return nil
- }
- unix := parsed.UTC().Unix()
- return &unix
-}
-
-func max(a, b int) int {
- if a > b {
- return a
- }
- return b
-}
diff --git a/internal/ai/quickstart_test.go b/internal/ai/quickstart_test.go
deleted file mode 100644
index fe654cfd97..0000000000
--- a/internal/ai/quickstart_test.go
+++ /dev/null
@@ -1,364 +0,0 @@
-package ai
-
-import (
- "context"
- "crypto/ed25519"
- "encoding/base64"
- "strings"
- "testing"
- "time"
-
- "github.com/rcourtman/pulse-go-rewrite/internal/config"
- pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
-)
-
-type stubQuickstartBootstrapClient struct {
- calls int
- bearer string
- req pkglicensing.QuickstartBootstrapRequest
- resp *pkglicensing.QuickstartBootstrapResponse
- err error
-}
-
-func (s *stubQuickstartBootstrapClient) BootstrapQuickstart(ctx context.Context, bearerToken string, req pkglicensing.QuickstartBootstrapRequest) (*pkglicensing.QuickstartBootstrapResponse, error) {
- s.calls++
- s.bearer = bearerToken
- s.req = req
- if s.err != nil {
- return nil, s.err
- }
- return s.resp, nil
-}
-
-func seedQuickstartEntitlementState(t *testing.T, persistence *config.ConfigPersistence, orgID, instanceHost string) string {
- t.Helper()
-
- pub, priv, err := ed25519.GenerateKey(nil)
- if err != nil {
- t.Fatalf("GenerateKey(): %v", err)
- }
- t.Setenv(pkglicensing.TrialActivationPublicKeyEnvVar, base64.StdEncoding.EncodeToString(pub))
-
- entitlementJWT, err := pkglicensing.SignEntitlementLeaseToken(priv, pkglicensing.EntitlementLeaseClaims{
- OrgID: orgID,
- InstanceHost: instanceHost,
- PlanVersion: "cloud_starter",
- SubscriptionState: pkglicensing.SubStateTrial,
- Capabilities: []string{pkglicensing.FeatureAIPatrol},
- })
- if err != nil {
- t.Fatalf("SignEntitlementLeaseToken(): %v", err)
- }
-
- billingStore := config.NewFileBillingStore(persistence.SharedInstallationDataDir())
- if err := billingStore.SaveBillingState(orgID, &pkglicensing.BillingState{
- EntitlementJWT: entitlementJWT,
- EntitlementRefreshToken: "etr_test_default",
- }); err != nil {
- t.Fatalf("SaveBillingState(): %v", err)
- }
-
- return entitlementJWT
-}
-
-func TestPersistentQuickstartCreditManager_EnsureBootstrapUsesActivationIdentity(t *testing.T) {
- dir := t.TempDir()
- persistence := config.NewConfigPersistence(dir)
-
- licensePersistence, err := pkglicensing.NewPersistence(persistence.GetConfigDir())
- if err != nil {
- t.Fatalf("NewPersistence(): %v", err)
- }
- if err := licensePersistence.SaveActivationState(&pkglicensing.ActivationState{
- InstallationID: "inst_live_test",
- InstallationToken: "pit_live_test",
- InstanceFingerprint: "fp-live-test",
- }); err != nil {
- t.Fatalf("SaveActivationState(): %v", err)
- }
-
- client := &stubQuickstartBootstrapClient{
- resp: &pkglicensing.QuickstartBootstrapResponse{
- QuickstartToken: "qst_live_activation",
- QuickstartTokenExpiresAt: time.Now().Add(30 * time.Minute).UTC().Format(time.RFC3339),
- CreditsRemaining: 19,
- CreditsTotal: 25,
- },
- }
- mgr := NewPersistentQuickstartCreditManagerWithClient(persistence, "default", func() *config.AIConfig { return &config.AIConfig{Enabled: true} }, client)
- mgr.hostname = func() (string, error) { return "pulse-test", nil }
-
- if err := mgr.EnsureBootstrap(context.Background()); err != nil {
- t.Fatalf("EnsureBootstrap(): %v", err)
- }
- if client.calls != 1 {
- t.Fatalf("BootstrapQuickstart calls = %d, want 1", client.calls)
- }
- if client.bearer != "pit_live_test" {
- t.Fatalf("bearer = %q, want pit_live_test", client.bearer)
- }
- if client.req.InstanceFingerprint != "fp-live-test" {
- t.Fatalf("InstanceFingerprint = %q, want fp-live-test", client.req.InstanceFingerprint)
- }
- if mgr.CreditsRemaining() != 19 {
- t.Fatalf("CreditsRemaining() = %d, want 19", mgr.CreditsRemaining())
- }
- if mgr.CreditsTotal() != 25 {
- t.Fatalf("CreditsTotal() = %d, want 25", mgr.CreditsTotal())
- }
- if mgr.GetProvider() == nil {
- t.Fatal("expected quickstart provider after activation bootstrap")
- }
-}
-
-func TestPersistentQuickstartCreditManager_EnsureBootstrapRequiresInstallationToken(t *testing.T) {
- dir := t.TempDir()
- persistence := config.NewConfigPersistence(dir)
-
- client := &stubQuickstartBootstrapClient{
- resp: &pkglicensing.QuickstartBootstrapResponse{
- QuickstartToken: "qst_should_not_be_used",
- CreditsRemaining: 17,
- CreditsTotal: 25,
- },
- }
- mgr := NewPersistentQuickstartCreditManagerWithClient(persistence, "default", func() *config.AIConfig { return &config.AIConfig{Enabled: true} }, client)
-
- err := mgr.EnsureBootstrap(context.Background())
- if err == nil {
- t.Fatal("expected activation-required error")
- }
- if QuickstartBlockedReasonForError(err) != patrolQuickstartActivationRequiredReason {
- t.Fatalf("blocked reason = %q, want %q", QuickstartBlockedReasonForError(err), patrolQuickstartActivationRequiredReason)
- }
- if client.calls != 0 {
- t.Fatalf("BootstrapQuickstart calls = %d, want 0", client.calls)
- }
- if mgr.CreditsRemaining() != 0 || mgr.CreditsTotal() != 0 {
- t.Fatalf("credits = %d/%d, want 0/0", mgr.CreditsRemaining(), mgr.CreditsTotal())
- }
-}
-
-func TestQuickstartReasonExportsRemainCanonical(t *testing.T) {
- if got := QuickstartCreditsExhaustedReason(); got != patrolQuickstartCreditsExhaustedReason {
- t.Fatalf("QuickstartCreditsExhaustedReason() = %q, want %q", got, patrolQuickstartCreditsExhaustedReason)
- }
- if got := QuickstartActivationRequiredReason(); got != patrolQuickstartActivationRequiredReason {
- t.Fatalf("QuickstartActivationRequiredReason() = %q, want %q", got, patrolQuickstartActivationRequiredReason)
- }
- if strings.Contains(strings.ToLower(QuickstartActivationRequiredReason()), "trial") {
- t.Fatalf("activation-required quickstart reason must stay BYOK-first, got %q", QuickstartActivationRequiredReason())
- }
- if err := quickstartActivationRequiredError(); strings.Contains(strings.ToLower(err.Error()), "trial") {
- t.Fatalf("activation-required quickstart error must not mention trials, got %q", err.Error())
- } else if !strings.Contains(err.Error(), "Pulse Account activation") {
- t.Fatalf("activation-required quickstart error = %q, want Pulse Account activation guidance", err.Error())
- }
-}
-
-func TestPersistentQuickstartCreditManager_LoadsPersistedTokenWithoutBootstrap(t *testing.T) {
- dir := t.TempDir()
- persistence := config.NewConfigPersistence(dir)
-
- licensePersistence, err := pkglicensing.NewPersistence(persistence.GetConfigDir())
- if err != nil {
- t.Fatalf("NewPersistence(): %v", err)
- }
- if err := licensePersistence.SaveActivationState(&pkglicensing.ActivationState{
- InstallationID: "inst_live_test",
- InstallationToken: "pit_live_test",
- InstanceFingerprint: "fp-live-test",
- }); err != nil {
- t.Fatalf("SaveActivationState(): %v", err)
- }
-
- expiresAt := time.Now().Add(30 * time.Minute).UTC().Unix()
- lastSyncedAt := time.Now().UTC().Unix()
- if err := persistence.SaveQuickstartState(config.QuickstartState{
- QuickstartToken: "qst_live_cached",
- QuickstartTokenExpiresAt: &expiresAt,
- QuickstartCreditsRemaining: 11,
- QuickstartCreditsTotal: 25,
- LastSyncedAt: &lastSyncedAt,
- }); err != nil {
- t.Fatalf("SaveQuickstartState(): %v", err)
- }
-
- client := &stubQuickstartBootstrapClient{
- resp: &pkglicensing.QuickstartBootstrapResponse{
- QuickstartToken: "qst_should_not_be_used",
- CreditsRemaining: 1,
- CreditsTotal: 25,
- },
- }
- mgr := NewPersistentQuickstartCreditManagerWithClient(persistence, "default", func() *config.AIConfig { return &config.AIConfig{Enabled: true} }, client)
-
- if err := mgr.EnsureBootstrap(context.Background()); err != nil {
- t.Fatalf("EnsureBootstrap(): %v", err)
- }
- if client.calls != 0 {
- t.Fatalf("BootstrapQuickstart calls = %d, want 0 for fresh cached state", client.calls)
- }
- if mgr.CreditsRemaining() != 11 {
- t.Fatalf("CreditsRemaining() = %d, want 11", mgr.CreditsRemaining())
- }
- if mgr.GetProvider() == nil {
- t.Fatal("expected provider from cached quickstart token")
- }
-}
-
-func TestPersistentQuickstartCreditManager_ExpiredTokenRebootstrapsWithInstallationToken(t *testing.T) {
- dir := t.TempDir()
- persistence := config.NewConfigPersistence(dir)
-
- licensePersistence, err := pkglicensing.NewPersistence(persistence.GetConfigDir())
- if err != nil {
- t.Fatalf("NewPersistence(): %v", err)
- }
- if err := licensePersistence.SaveActivationState(&pkglicensing.ActivationState{
- InstallationID: "inst_live_test",
- InstallationToken: "pit_live_test",
- InstanceFingerprint: "fp-live-test",
- }); err != nil {
- t.Fatalf("SaveActivationState(): %v", err)
- }
-
- expiredAt := time.Now().Add(-5 * time.Minute).UTC().Unix()
- lastSyncedAt := time.Now().Add(-10 * time.Minute).UTC().Unix()
- if err := persistence.SaveQuickstartState(config.QuickstartState{
- QuickstartToken: "qst_live_expired",
- QuickstartTokenExpiresAt: &expiredAt,
- QuickstartCreditsRemaining: 11,
- QuickstartCreditsTotal: 25,
- LastSyncedAt: &lastSyncedAt,
- }); err != nil {
- t.Fatalf("SaveQuickstartState(): %v", err)
- }
-
- client := &stubQuickstartBootstrapClient{
- resp: &pkglicensing.QuickstartBootstrapResponse{
- QuickstartToken: "qst_live_rotated",
- QuickstartTokenExpiresAt: time.Now().Add(30 * time.Minute).UTC().Format(time.RFC3339),
- CreditsRemaining: 9,
- CreditsTotal: 25,
- },
- }
- mgr := NewPersistentQuickstartCreditManagerWithClient(persistence, "default", func() *config.AIConfig { return &config.AIConfig{Enabled: true} }, client)
-
- if err := mgr.EnsureBootstrap(context.Background()); err != nil {
- t.Fatalf("EnsureBootstrap(): %v", err)
- }
- if client.calls != 1 {
- t.Fatalf("BootstrapQuickstart calls = %d, want 1", client.calls)
- }
- if client.bearer != "pit_live_test" {
- t.Fatalf("bearer = %q, want pit_live_test", client.bearer)
- }
- if client.req.InstanceFingerprint != "fp-live-test" {
- t.Fatalf("InstanceFingerprint = %q, want fp-live-test", client.req.InstanceFingerprint)
- }
-
- loaded, err := persistence.LoadQuickstartState()
- if err != nil {
- t.Fatalf("LoadQuickstartState(): %v", err)
- }
- if loaded.QuickstartToken != "qst_live_rotated" {
- t.Fatalf("QuickstartToken = %q, want qst_live_rotated", loaded.QuickstartToken)
- }
- if loaded.QuickstartCreditsRemaining != 9 {
- t.Fatalf("QuickstartCreditsRemaining = %d, want 9", loaded.QuickstartCreditsRemaining)
- }
-}
-
-func TestPersistentQuickstartCreditManager_TenantUsesSharedInstallationActivationState(t *testing.T) {
- dir := t.TempDir()
- mtp := config.NewMultiTenantPersistence(dir)
-
- defaultPersistence, err := mtp.GetPersistence("default")
- if err != nil {
- t.Fatalf("GetPersistence(default): %v", err)
- }
- tenantPersistence, err := mtp.GetPersistence("t-tenant")
- if err != nil {
- t.Fatalf("GetPersistence(t-tenant): %v", err)
- }
-
- licensePersistence, err := pkglicensing.NewPersistence(defaultPersistence.SharedInstallationDataDir())
- if err != nil {
- t.Fatalf("NewPersistence(): %v", err)
- }
- if err := licensePersistence.SaveActivationState(&pkglicensing.ActivationState{
- InstallationID: "inst_live_test",
- InstallationToken: "pit_live_test",
- InstanceFingerprint: "fp-live-test",
- }); err != nil {
- t.Fatalf("SaveActivationState(): %v", err)
- }
-
- client := &stubQuickstartBootstrapClient{
- resp: &pkglicensing.QuickstartBootstrapResponse{
- QuickstartToken: "qst_live_tenant",
- QuickstartTokenExpiresAt: time.Now().Add(30 * time.Minute).UTC().Format(time.RFC3339),
- CreditsRemaining: 14,
- CreditsTotal: 25,
- },
- }
- mgr := NewPersistentQuickstartCreditManagerWithClient(tenantPersistence, "t-tenant", func() *config.AIConfig { return &config.AIConfig{Enabled: true} }, client)
-
- if err := mgr.EnsureBootstrap(context.Background()); err != nil {
- t.Fatalf("EnsureBootstrap(): %v", err)
- }
- if client.calls != 1 {
- t.Fatalf("BootstrapQuickstart calls = %d, want 1", client.calls)
- }
- if client.bearer != "pit_live_test" {
- t.Fatalf("bearer = %q, want pit_live_test", client.bearer)
- }
- if mgr.CreditsRemaining() != 14 {
- t.Fatalf("CreditsRemaining() = %d, want 14", mgr.CreditsRemaining())
- }
-}
-
-func TestPersistentQuickstartCreditManager_EnsureBootstrapUsesEntitlementIdentityWhenActivationMissing(t *testing.T) {
- dir := t.TempDir()
- mtp := config.NewMultiTenantPersistence(dir)
-
- defaultPersistence, err := mtp.GetPersistence("default")
- if err != nil {
- t.Fatalf("GetPersistence(default): %v", err)
- }
- tenantPersistence, err := mtp.GetPersistence("t-tenant")
- if err != nil {
- t.Fatalf("GetPersistence(t-tenant): %v", err)
- }
-
- entitlementJWT := seedQuickstartEntitlementState(t, defaultPersistence, "default", "t-hosted.cloud.pulserelay.pro")
- client := &stubQuickstartBootstrapClient{
- resp: &pkglicensing.QuickstartBootstrapResponse{
- QuickstartToken: "qst_live_entitlement",
- QuickstartTokenExpiresAt: time.Now().Add(30 * time.Minute).UTC().Format(time.RFC3339),
- CreditsRemaining: 23,
- CreditsTotal: 25,
- },
- }
- mgr := NewPersistentQuickstartCreditManagerWithClient(tenantPersistence, "t-tenant", func() *config.AIConfig { return &config.AIConfig{Enabled: true} }, client)
-
- if err := mgr.EnsureBootstrap(context.Background()); err != nil {
- t.Fatalf("EnsureBootstrap(): %v", err)
- }
- if client.calls != 1 {
- t.Fatalf("BootstrapQuickstart calls = %d, want 1", client.calls)
- }
- if client.bearer != entitlementJWT {
- t.Fatalf("bearer = %q, want entitlement lease JWT", client.bearer)
- }
- if client.req.InstanceFingerprint != "" {
- t.Fatalf("InstanceFingerprint = %q, want empty for entitlement bootstrap", client.req.InstanceFingerprint)
- }
- if mgr.CreditsRemaining() != 23 {
- t.Fatalf("CreditsRemaining() = %d, want 23", mgr.CreditsRemaining())
- }
- if mgr.GetProvider() == nil {
- t.Fatal("expected quickstart provider after entitlement bootstrap")
- }
-}
diff --git a/internal/ai/service.go b/internal/ai/service.go
index 645fc9ad31..d126905a56 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -220,13 +220,6 @@ type Service struct {
// License checker for Pro feature gating
licenseChecker LicenseChecker
-
- // Quickstart credit manager for free hosted patrol runs
- quickstartCredits QuickstartCreditManager
- // usingQuickstart tracks whether the current provider was set via quickstart credits
- usingQuickstart bool
- // quickstartBlockedReason captures why Patrol-only quickstart is currently unavailable.
- quickstartBlockedReason string
}
type executionLimits struct {
@@ -512,9 +505,6 @@ func (s *Service) initPatrolServiceLocked() {
if s.discoveryStore != nil {
s.patrolService.SetDiscoveryStore(s.discoveryStore)
}
- if s.quickstartCredits != nil {
- s.patrolService.SetQuickstartCredits(s.quickstartCredits)
- }
if s.readState != nil {
s.patrolService.SetReadState(s.readState)
}
@@ -640,7 +630,7 @@ func (s *Service) SetChatService(cs ChatServiceProvider) {
s.mu.Lock()
defer s.mu.Unlock()
s.chatService = cs
- s.configurePatrolQuickstartProviderFactoryLocked()
+ s.configurePatrolProviderFactoryLocked()
}
// GetChatService returns the chat service for investigation orchestrator
@@ -1521,8 +1511,6 @@ func (s *Service) LoadConfig() error {
s.mu.Lock()
s.provider = nil
s.cfg = nil
- s.usingQuickstart = false
- s.quickstartBlockedReason = ""
s.mu.Unlock()
return fmt.Errorf("Pulse Assistant config persistence unavailable")
}
@@ -1533,8 +1521,6 @@ func (s *Service) LoadConfig() error {
}
modelResolutionCtx := context.Background()
var providerClient providers.Provider
- usingQuickstart := false
- blockedReason := ""
// Don't initialize provider if AI is not enabled or not configured
if cfg == nil || !cfg.Enabled || !cfg.IsConfigured() {
@@ -1600,8 +1586,6 @@ func (s *Service) LoadConfig() error {
s.mu.Lock()
s.cfg = cfg
s.provider = providerClient
- s.usingQuickstart = usingQuickstart
- s.quickstartBlockedReason = blockedReason
s.initInfraDiscoveryServiceLocked()
s.initDiscoveryServiceLocked()
s.mu.Unlock()
@@ -1626,44 +1610,11 @@ func (s *Service) IsEnabled() bool {
return false
}
-// IsUsingQuickstart returns true if the current provider is the quickstart proxy.
-func (s *Service) IsUsingQuickstart() bool {
- s.mu.RLock()
- defer s.mu.RUnlock()
- return s.usingQuickstart
-}
-
-// QuickstartBlockedReason returns the current Patrol quickstart blocking reason.
-func (s *Service) QuickstartBlockedReason() string {
- s.mu.RLock()
- defer s.mu.RUnlock()
- return strings.TrimSpace(s.quickstartBlockedReason)
-}
-
-// SetQuickstartCredits sets the quickstart credit manager on both the
-// service and its patrol sub-service so credit checks work at runtime.
-func (s *Service) SetQuickstartCredits(mgr QuickstartCreditManager) {
- s.mu.Lock()
- defer s.mu.Unlock()
- s.quickstartCredits = mgr
- if s.patrolService != nil {
- s.patrolService.SetQuickstartCredits(mgr)
- }
- s.configurePatrolQuickstartProviderFactoryLocked()
-}
-
-// GetQuickstartCredits returns the quickstart credit manager.
-func (s *Service) GetQuickstartCredits() QuickstartCreditManager {
- s.mu.RLock()
- defer s.mu.RUnlock()
- return s.quickstartCredits
-}
-
type patrolProviderFactorySetter interface {
SetPatrolProviderFactory(func(modelStr string) (providers.StreamingProvider, error))
}
-func (s *Service) configurePatrolQuickstartProviderFactoryLocked() {
+func (s *Service) configurePatrolProviderFactoryLocked() {
setter, ok := s.chatService.(patrolProviderFactorySetter)
if !ok {
return
@@ -4366,7 +4317,6 @@ func (s *Service) TestConnection(ctx context.Context) error {
cfg := s.cfg
defaultProvider := s.provider
persistence := s.persistence
- isQuickstart := s.usingQuickstart
s.mu.RUnlock()
// Load config if not available
@@ -4382,10 +4332,6 @@ func (s *Service) TestConnection(ctx context.Context) error {
}
if cfg == nil || !cfg.IsConfigured() {
- // If using quickstart credits, test the quickstart proxy instead.
- if isQuickstart && defaultProvider != nil {
- return defaultProvider.TestConnection(ctx)
- }
return fmt.Errorf("no provider configured")
}
diff --git a/internal/ai/service_extended_test.go b/internal/ai/service_extended_test.go
index 32ec4e1bb3..a9dd1ef279 100644
--- a/internal/ai/service_extended_test.go
+++ b/internal/ai/service_extended_test.go
@@ -933,31 +933,6 @@ func TestService_TestConnection_Extended(t *testing.T) {
t.Errorf("Expected 'no provider configured' error, got: %v", err)
}
- // 2. Quickstart provider fallback
- mockProv := &mockProvider{
- testConnectionFunc: func(ctx context.Context) error {
- return nil
- },
- }
- svc.provider = mockProv
- svc.usingQuickstart = true
- svc.cfg = &config.AIConfig{
- Enabled: true,
- }
-
- err = svc.TestConnection(context.Background())
- if err != nil {
- t.Errorf("TestConnection failed: %v", err)
- }
-
- // 3. Provider error
- mockProv.testConnectionFunc = func(ctx context.Context) error {
- return fmt.Errorf("connection failed")
- }
- err = svc.TestConnection(context.Background())
- if err == nil || !strings.Contains(err.Error(), "connection failed") {
- t.Errorf("Expected 'connection failed' error, got: %v", err)
- }
}
func TestService_ExecuteTool_ResolveFinding(t *testing.T) {
diff --git a/internal/ai/service_quickstart_test.go b/internal/ai/service_quickstart_test.go
deleted file mode 100644
index 4284300bd6..0000000000
--- a/internal/ai/service_quickstart_test.go
+++ /dev/null
@@ -1,114 +0,0 @@
-package ai
-
-import (
- "context"
- "net/http"
- "testing"
-
- "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
- "github.com/rcourtman/pulse-go-rewrite/internal/config"
- pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
-)
-
-type stubServiceQuickstartManager struct {
- ensureErr error
- remaining int
- total int
- provider providers.Provider
- byok bool
-}
-
-func (m *stubServiceQuickstartManager) EnsureBootstrap(context.Context) error { return m.ensureErr }
-func (m *stubServiceQuickstartManager) HasCredits() bool { return m.remaining > 0 }
-func (m *stubServiceQuickstartManager) CreditsRemaining() int { return m.remaining }
-func (m *stubServiceQuickstartManager) CreditsTotal() int {
- if m.total > 0 {
- return m.total
- }
- return pkglicensing.QuickstartCreditsTotal
-}
-func (m *stubServiceQuickstartManager) HasBYOK() bool { return m.byok }
-func (m *stubServiceQuickstartManager) GetProvider() providers.Provider { return m.provider }
-
-func TestServiceLoadConfig_PrefersBYOKProviderOverQuickstart(t *testing.T) {
- dir := t.TempDir()
- persistence := config.NewConfigPersistence(dir)
- cfg := config.NewDefaultAIConfig()
- cfg.Enabled = true
- cfg.Model = "ollama:llama3"
- cfg.OllamaBaseURL = "http://127.0.0.1:11434"
- if err := persistence.SaveAIConfig(*cfg); err != nil {
- t.Fatalf("SaveAIConfig(): %v", err)
- }
-
- svc := NewService(persistence, nil)
- svc.SetQuickstartCredits(&stubServiceQuickstartManager{
- ensureErr: &pkglicensing.LicenseServerError{StatusCode: http.StatusServiceUnavailable, Code: "temporarily_unavailable", Message: "down", Retryable: true},
- remaining: 25,
- total: 25,
- provider: providers.NewQuickstartClientWithToken("qst_live_test", nil, nil),
- })
-
- if err := svc.LoadConfig(); err != nil {
- t.Fatalf("LoadConfig(): %v", err)
- }
- if svc.IsUsingQuickstart() {
- t.Fatal("expected BYOK provider to win over quickstart")
- }
- if svc.QuickstartBlockedReason() != "" {
- t.Fatalf("QuickstartBlockedReason() = %q, want empty when BYOK is configured", svc.QuickstartBlockedReason())
- }
- if !svc.IsEnabled() {
- t.Fatal("expected BYOK AI service to remain enabled")
- }
-}
-
-func TestServiceLoadConfig_IgnoresQuickstartBootstrapFailureWhenNoBYOK(t *testing.T) {
- dir := t.TempDir()
- persistence := config.NewConfigPersistence(dir)
- cfg := config.NewDefaultAIConfig()
- cfg.Enabled = true
- if err := persistence.SaveAIConfig(*cfg); err != nil {
- t.Fatalf("SaveAIConfig(): %v", err)
- }
-
- svc := NewService(persistence, nil)
- svc.SetQuickstartCredits(&stubServiceQuickstartManager{
- ensureErr: &pkglicensing.LicenseServerError{StatusCode: http.StatusServiceUnavailable, Code: "temporarily_unavailable", Message: "down", Retryable: true},
- })
-
- if err := svc.LoadConfig(); err != nil {
- t.Fatalf("LoadConfig(): %v", err)
- }
- if svc.QuickstartBlockedReason() != "" {
- t.Fatalf("QuickstartBlockedReason() = %q, want empty for retired quickstart", svc.QuickstartBlockedReason())
- }
- if svc.IsEnabled() {
- t.Fatal("expected AI service to remain disabled when no BYOK/local provider exists")
- }
-}
-
-func TestServiceLoadConfig_IgnoresQuickstartActivationRequirementWhenNoBYOK(t *testing.T) {
- dir := t.TempDir()
- persistence := config.NewConfigPersistence(dir)
- cfg := config.NewDefaultAIConfig()
- cfg.Enabled = true
- if err := persistence.SaveAIConfig(*cfg); err != nil {
- t.Fatalf("SaveAIConfig(): %v", err)
- }
-
- svc := NewService(persistence, nil)
- svc.SetQuickstartCredits(&stubServiceQuickstartManager{
- ensureErr: &pkglicensing.LicenseServerError{StatusCode: http.StatusUnauthorized, Code: "activation_required", Message: "activation required", Retryable: false},
- })
-
- if err := svc.LoadConfig(); err != nil {
- t.Fatalf("LoadConfig(): %v", err)
- }
- if svc.QuickstartBlockedReason() != "" {
- t.Fatalf("QuickstartBlockedReason() = %q, want empty for retired quickstart", svc.QuickstartBlockedReason())
- }
- if svc.IsEnabled() {
- t.Fatal("expected AI service to remain disabled when no BYOK/local provider exists")
- }
-}
diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.go
index 0744926f11..5cce453cef 100644
--- a/internal/api/ai_handlers.go
+++ b/internal/api/ai_handlers.go
@@ -4775,8 +4775,7 @@ func writePatrolServiceUnavailableResponse(w http.ResponseWriter) {
}
func retireQuickstartPatrolStatus(status ai.PatrolStatus) ai.PatrolStatus {
- switch strings.TrimSpace(status.BlockedReason) {
- case ai.QuickstartCreditsExhaustedReason(), ai.QuickstartActivationRequiredReason():
+ if isRetiredQuickstartBlockedReason(status.BlockedReason) {
status.BlockedReason = ""
status.BlockedAt = nil
if status.RuntimeState == ai.PatrolRuntimeStateBlocked {
@@ -4791,6 +4790,12 @@ func retireQuickstartPatrolStatus(status ai.PatrolStatus) ai.PatrolStatus {
return status
}
+func isRetiredQuickstartBlockedReason(reason string) bool {
+ normalized := strings.ToLower(strings.TrimSpace(reason))
+ return strings.Contains(normalized, "quickstart credits exhausted") ||
+ strings.Contains(normalized, "hosted quickstart requires")
+}
+
// HandleGetPatrolStatus returns the current patrol status (GET /api/ai/patrol/status)
func (h *AISettingsHandler) HandleGetPatrolStatus(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
diff --git a/internal/api/ai_handlers_patrol_actions_additional_test.go b/internal/api/ai_handlers_patrol_actions_additional_test.go
index bb71ee66f8..c9562315ab 100644
--- a/internal/api/ai_handlers_patrol_actions_additional_test.go
+++ b/internal/api/ai_handlers_patrol_actions_additional_test.go
@@ -2,7 +2,6 @@ package api
import (
"bytes"
- "context"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -12,10 +11,8 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/ai"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/learning"
- "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/unified"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
- pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
)
func setupAIHandlerWithPatrol(t *testing.T) (*AISettingsHandler, *ai.PatrolService, *unified.UnifiedStore, *learning.LearningStore) {
@@ -115,88 +112,6 @@ func addUnifiedRuntimeFinding(store *unified.UnifiedStore, id string, detectedAt
return finding
}
-type stubQuickstartCreditManager struct {
- remaining int
- total int
- provider providers.Provider
-}
-
-func (m *stubQuickstartCreditManager) EnsureBootstrap(context.Context) error { return nil }
-func (m *stubQuickstartCreditManager) HasCredits() bool { return m.remaining > 0 }
-func (m *stubQuickstartCreditManager) CreditsRemaining() int { return m.remaining }
-func (m *stubQuickstartCreditManager) CreditsTotal() int {
- if m.total > 0 {
- return m.total
- }
- return pkglicensing.QuickstartCreditsTotal
-}
-func (m *stubQuickstartCreditManager) HasBYOK() bool { return false }
-func (m *stubQuickstartCreditManager) GetProvider() providers.Provider {
- if m.provider != nil {
- return m.provider
- }
- if m.remaining <= 0 {
- return nil
- }
- return providers.NewQuickstartClientWithToken("qst_live_test", nil, nil)
-}
-
-func TestHandleGetPatrolStatus_DoesNotExposeQuickstartFields(t *testing.T) {
- handler, _, _, _ := setupAIHandlerWithPatrol(t)
-
- handler.defaultAIService.SetQuickstartCredits(&stubQuickstartCreditManager{remaining: 7})
- setUnexportedField(t, handler.defaultAIService, "usingQuickstart", true)
-
- req := newLoopbackRequest(http.MethodGet, "/api/ai/patrol/status", nil)
- rec := httptest.NewRecorder()
-
- handler.HandleGetPatrolStatus(rec, req)
-
- if rec.Code != http.StatusOK {
- t.Fatalf("status = %d, want 200", rec.Code)
- }
-
- var resp PatrolStatusResponse
- if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
- t.Fatalf("decode response: %v", err)
- }
-
- body := rec.Body.String()
- if strings.Contains(body, "quickstart_credits") || strings.Contains(body, "using_quickstart") {
- t.Fatalf("patrol status must not expose retired quickstart fields: %s", body)
- }
-}
-
-func TestHandleGetPatrolStatus_DoesNotSurfaceExhaustedQuickstartCredits(t *testing.T) {
- handler, _, _, _ := setupAIHandlerWithPatrol(t)
-
- handler.defaultAIService.SetQuickstartCredits(&stubQuickstartCreditManager{remaining: 0})
-
- req := newLoopbackRequest(http.MethodGet, "/api/ai/patrol/status", nil)
- rec := httptest.NewRecorder()
-
- handler.HandleGetPatrolStatus(rec, req)
-
- if rec.Code != http.StatusOK {
- t.Fatalf("status = %d, want 200", rec.Code)
- }
-
- var resp PatrolStatusResponse
- if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
- t.Fatalf("decode response: %v", err)
- }
-
- if resp.RuntimeState == ai.PatrolRuntimeStateBlocked {
- t.Fatalf("runtime_state = %q, want non-blocked for retired quickstart", resp.RuntimeState)
- }
- if strings.Contains(strings.ToLower(resp.BlockedReason), "quickstart") {
- t.Fatalf("blocked_reason must not expose retired quickstart copy, got %q", resp.BlockedReason)
- }
- if !resp.Healthy {
- t.Fatal("expected retired quickstart state to remain healthy on the public status surface")
- }
-}
-
func TestHandleGetPatrolStatus_DistinguishesLastFullPatrolFromLastActivity(t *testing.T) {
handler, patrol, _, _ := setupAIHandlerWithPatrol(t)
diff --git a/internal/api/ai_handlers_test.go b/internal/api/ai_handlers_test.go
index 01e633b60a..8a81d94110 100644
--- a/internal/api/ai_handlers_test.go
+++ b/internal/api/ai_handlers_test.go
@@ -19,7 +19,6 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
"github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"
- pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -54,43 +53,6 @@ func saveEnabledTestAIConfig(t *testing.T, persistence *config.ConfigPersistence
require.NoError(t, persistence.SaveAIConfig(*aiCfg))
}
-func useTestQuickstartBootstrapServer(t *testing.T, assertRequest func(*http.Request, map[string]any)) {
- t.Helper()
-
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(t, http.MethodPost, r.Method)
- require.Equal(t, "/v1/quickstart/bootstrap", r.URL.Path)
-
- var reqBody map[string]any
- require.NoError(t, json.NewDecoder(r.Body).Decode(&reqBody))
- if assertRequest != nil {
- assertRequest(r, reqBody)
- }
-
- w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{
- "quickstart_token": "qst_live_handler_test",
- "quickstart_token_expires_at": time.Now().Add(30 * time.Minute).UTC().Format(time.RFC3339),
- "credits_remaining": 25,
- "credits_total": 25,
- }))
- }))
- t.Cleanup(server.Close)
- t.Setenv("PULSE_LICENSE_SERVER_URL", server.URL)
-}
-
-func persistQuickstartActivationState(t *testing.T, persistence *config.ConfigPersistence) {
- t.Helper()
-
- licensePersistence, err := pkglicensing.NewPersistence(persistence.GetConfigDir())
- require.NoError(t, err)
- require.NoError(t, licensePersistence.SaveActivationState(&pkglicensing.ActivationState{
- InstallationID: "inst_live_test",
- InstallationToken: "pit_live_test",
- InstanceFingerprint: "fp-live-test",
- }))
-}
-
func TestAIHandlersUseSafeRemediationCommercialCopy(t *testing.T) {
files := []string{"ai_handlers.go", "router_routes_ai_relay.go"}
for _, file := range files {
@@ -343,11 +305,6 @@ func TestAISettingsHandler_GetSettings_DoesNotExposeQuickstartSurface(t *testing
cfg := &config.Config{DataPath: tmp}
persistence := config.NewConfigPersistence(tmp)
handler := newTestAISettingsHandler(cfg, persistence, nil)
- handler.defaultAIService.SetQuickstartCredits(ai.NewPersistentQuickstartCreditManager(
- persistence,
- "default",
- func() *config.AIConfig { return &config.AIConfig{Enabled: true} },
- ))
req := newLoopbackRequest(http.MethodGet, "/api/settings/ai", nil)
rec := httptest.NewRecorder()
@@ -383,7 +340,6 @@ func TestAISettingsHandler_UpdateSettings_DoesNotBootstrapQuickstartWithActivati
tmp := t.TempDir()
cfg := &config.Config{DataPath: tmp}
persistence := config.NewConfigPersistence(tmp)
- persistQuickstartActivationState(t, persistence)
handler := newTestAISettingsHandler(cfg, persistence, nil)
diff --git a/internal/api/ai_hosted_runtime.go b/internal/api/ai_hosted_runtime.go
index a5effe295c..70e8b1c659 100644
--- a/internal/api/ai_hosted_runtime.go
+++ b/internal/api/ai_hosted_runtime.go
@@ -3,7 +3,6 @@ package api
import (
"fmt"
"os"
- "strings"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
)
@@ -24,27 +23,10 @@ func shouldAutoBootstrapHostedAIConfig(hostedMode bool, persistence *config.Conf
return false
}
-func ensureHostedAIQuickstartBillingState(billingBaseDir, orgID string) (*billingState, error) {
- state, _, err := config.LoadEffectiveEntitlementBillingState(billingBaseDir, orgID)
- return state, err
-}
-
func hostedAIAutoBootstrapEligible(state *billingState) bool {
return false
}
-func hasBillingCapability(state *billingState, feature string) bool {
- if state == nil || strings.TrimSpace(feature) == "" {
- return false
- }
- for _, capability := range state.Capabilities {
- if capability == feature {
- return true
- }
- }
- return false
-}
-
func hostedModeEnabledFromEnv() bool {
return os.Getenv("PULSE_HOSTED_MODE") == "true"
}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 4cab281de6..5c6774b38c 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -369,25 +369,18 @@ func TestContract_AISettingsUpdateProviderResolutionJSONSnapshot(t *testing.T) {
}
func TestContract_PatrolStatusDoesNotSurfaceQuickstartActivation(t *testing.T) {
- handler, _, _, _ := setupAIHandlerWithPatrol(t)
+ handler, patrol, _, _ := setupAIHandlerWithPatrol(t)
persistence := handler.defaultPersistence
aiCfg := config.NewDefaultAIConfig()
aiCfg.Enabled = true
if err := persistence.SaveAIConfig(*aiCfg); err != nil {
t.Fatalf("SaveAIConfig: %v", err)
}
-
- handler.defaultAIService.SetQuickstartCredits(ai.NewPersistentQuickstartCreditManager(
- persistence,
- "default",
- func() *config.AIConfig {
- cfg, _ := persistence.LoadAIConfig()
- return cfg
- },
- ))
if err := handler.defaultAIService.LoadConfig(); err != nil {
t.Fatalf("LoadConfig: %v", err)
}
+ setUnexportedField(t, patrol, "lastBlockedReason", "Quickstart credits exhausted. Connect your API key to continue using AI Patrol.")
+ setUnexportedField(t, patrol, "lastBlockedAt", time.Now().UTC())
req := httptest.NewRequest(http.MethodGet, "/api/ai/patrol/status", nil)
rec := httptest.NewRecorder()
@@ -420,11 +413,6 @@ func TestContract_AISettingsDoesNotExposeQuickstartActivation(t *testing.T) {
cfg := &config.Config{DataPath: tmp}
persistence := config.NewConfigPersistence(tmp)
handler := newTestAISettingsHandler(cfg, persistence, nil)
- handler.defaultAIService.SetQuickstartCredits(ai.NewPersistentQuickstartCreditManager(
- persistence,
- "default",
- func() *config.AIConfig { return &config.AIConfig{Enabled: true} },
- ))
req := httptest.NewRequest(http.MethodGet, "/api/settings/ai", nil)
rec := httptest.NewRecorder()
@@ -460,10 +448,6 @@ func TestContract_AISettingsBYOKOverrideDoesNotExposeQuickstartInventoryJSONSnap
}
handler := newTestAISettingsHandler(cfg, persistence, nil)
- handler.defaultAIService.SetQuickstartCredits(&stubQuickstartCreditManager{
- remaining: 12,
- total: pkglicensing.QuickstartCreditsTotal,
- })
req := httptest.NewRequest(http.MethodGet, "/api/settings/ai", nil)
rec := httptest.NewRecorder()
diff --git a/internal/api/licensing_bridge.go b/internal/api/licensing_bridge.go
index c2c78897a9..2747a2b6f9 100644
--- a/internal/api/licensing_bridge.go
+++ b/internal/api/licensing_bridge.go
@@ -361,9 +361,6 @@ func recordConversionEventMetric(eventType, surface string) {
// licenseTierFreeValue is the canonical free-tier constant for use outside the bridge.
const licenseTierFreeValue = pkglicensing.TierFree
-// quickstartCreditsTotalFromLicensing returns the total quickstart credits granted per workspace.
-const quickstartCreditsTotalFromLicensing = pkglicensing.QuickstartCreditsTotal
-
// overflowBonusFromLicensing returns the number of bonus host slots granted by the onboarding overflow.
func overflowBonusFromLicensing(tier licenseTier, overflowGrantedAt *int64, now time.Time) int {
return pkglicensing.OverflowBonus(tier, overflowGrantedAt, now)
diff --git a/internal/config/billing_state.go b/internal/config/billing_state.go
index 73f8aa5215..6c5381f8ba 100644
--- a/internal/config/billing_state.go
+++ b/internal/config/billing_state.go
@@ -304,7 +304,8 @@ type billingIntegrityPayload struct {
TrialEndsAt *int64 `json:"trial_ends_at"`
TrialExtendedAt *int64 `json:"trial_extended_at"`
OverflowGrantedAt *int64 `json:"overflow_granted_at"`
- // Quickstart credits gate free hosted Patrol runs — must be HMAC-protected.
+ // Historical hosted-AI quickstart fields remain HMAC-protected so old
+ // billing-state files can be verified without reintroducing active credits.
QuickstartCreditsGranted bool `json:"quickstart_credits_granted"`
QuickstartCreditsUsed int `json:"quickstart_credits_used"`
QuickstartCreditsGrantedAt *int64 `json:"quickstart_credits_granted_at"`
diff --git a/internal/config/persistence.go b/internal/config/persistence.go
index 9d192892b8..1181c77934 100644
--- a/internal/config/persistence.go
+++ b/internal/config/persistence.go
@@ -38,7 +38,6 @@ type ConfigPersistence struct {
ssoFile string
apiTokensFile string
aiFile string
- quickstartFile string
aiFindingsFile string
aiPatrolRunsFile string
aiUsageHistoryFile string
@@ -102,7 +101,6 @@ type resolvedConfigPersistencePaths struct {
ssoFile string
apiTokensFile string
aiFile string
- quickstartFile string
aiFindingsFile string
aiPatrolRunsFile string
aiUsageHistoryFile string
@@ -167,10 +165,6 @@ func resolveConfigPersistencePaths(configDir string) (string, resolvedConfigPers
if err != nil {
return "", resolvedConfigPersistencePaths{}, fmt.Errorf("resolve ai.enc: %w", err)
}
- quickstartFile, err := resolveLeaf("quickstart.enc")
- if err != nil {
- return "", resolvedConfigPersistencePaths{}, fmt.Errorf("resolve quickstart.enc: %w", err)
- }
aiFindingsFile, err := resolveLeaf("ai_findings.json")
if err != nil {
return "", resolvedConfigPersistencePaths{}, fmt.Errorf("resolve ai_findings.json: %w", err)
@@ -216,7 +210,6 @@ func resolveConfigPersistencePaths(configDir string) (string, resolvedConfigPers
ssoFile: ssoFile,
apiTokensFile: apiTokensFile,
aiFile: aiFile,
- quickstartFile: quickstartFile,
aiFindingsFile: aiFindingsFile,
aiPatrolRunsFile: aiPatrolRunsFile,
aiUsageHistoryFile: aiUsageHistoryFile,
@@ -267,7 +260,6 @@ func newConfigPersistence(configDir string) (*ConfigPersistence, error) {
ssoFile: resolvedPaths.ssoFile,
apiTokensFile: resolvedPaths.apiTokensFile,
aiFile: resolvedPaths.aiFile,
- quickstartFile: resolvedPaths.quickstartFile,
aiFindingsFile: resolvedPaths.aiFindingsFile,
aiPatrolRunsFile: resolvedPaths.aiPatrolRunsFile,
aiUsageHistoryFile: resolvedPaths.aiUsageHistoryFile,
diff --git a/internal/config/quickstart_state.go b/internal/config/quickstart_state.go
deleted file mode 100644
index 0cb8353a0b..0000000000
--- a/internal/config/quickstart_state.go
+++ /dev/null
@@ -1,126 +0,0 @@
-package config
-
-import (
- "encoding/json"
- "fmt"
- "os"
- "strings"
- "time"
-)
-
-// QuickstartState is the machine-owned local cache for the server-authoritative
-// quickstart bootstrap contract.
-type QuickstartState struct {
- QuickstartToken string `json:"quickstart_token,omitempty"`
- QuickstartTokenExpiresAt *int64 `json:"quickstart_token_expires_at,omitempty"`
- QuickstartCreditsTotal int `json:"quickstart_credits_total,omitempty"`
- QuickstartCreditsRemaining int `json:"quickstart_credits_remaining,omitempty"`
- LastSyncedAt *int64 `json:"last_synced_at,omitempty"`
-}
-
-// NormalizeQuickstartState returns a deep-cloned, normalized quickstart state.
-func NormalizeQuickstartState(state *QuickstartState) *QuickstartState {
- if state == nil {
- return &QuickstartState{}
- }
-
- cp := *state
- normalized := &cp
- normalized.QuickstartToken = strings.TrimSpace(normalized.QuickstartToken)
- normalized.QuickstartTokenExpiresAt = cloneQuickstartInt64Ptr(state.QuickstartTokenExpiresAt)
- normalized.LastSyncedAt = cloneQuickstartInt64Ptr(state.LastSyncedAt)
- if normalized.QuickstartCreditsTotal < 0 {
- normalized.QuickstartCreditsTotal = 0
- }
- if normalized.QuickstartCreditsRemaining < 0 {
- normalized.QuickstartCreditsRemaining = 0
- }
- if normalized.QuickstartCreditsTotal > 0 && normalized.QuickstartCreditsRemaining > normalized.QuickstartCreditsTotal {
- normalized.QuickstartCreditsRemaining = normalized.QuickstartCreditsTotal
- }
- return normalized
-}
-
-func cloneQuickstartInt64Ptr(value *int64) *int64 {
- if value == nil {
- return nil
- }
- cloned := *value
- return &cloned
-}
-
-// TokenExpired reports whether the cached quickstart token is expired at the
-// supplied timestamp.
-func (s *QuickstartState) TokenExpired(now time.Time) bool {
- if s == nil || s.QuickstartTokenExpiresAt == nil || *s.QuickstartTokenExpiresAt <= 0 {
- return false
- }
- return now.Unix() >= *s.QuickstartTokenExpiresAt
-}
-
-// SaveQuickstartState persists the machine-owned quickstart cache.
-func (c *ConfigPersistence) SaveQuickstartState(state QuickstartState) error {
- c.mu.Lock()
- defer c.mu.Unlock()
-
- if err := c.EnsureConfigDir(); err != nil {
- return fmt.Errorf("prepare config directory for quickstart state: %w", err)
- }
-
- normalized := NormalizeQuickstartState(&state)
- data, err := json.Marshal(normalized)
- if err != nil {
- return fmt.Errorf("marshal quickstart state: %w", err)
- }
-
- if c.crypto != nil {
- encrypted, err := c.crypto.Encrypt(data)
- if err != nil {
- return fmt.Errorf("encrypt quickstart state: %w", err)
- }
- data = encrypted
- }
-
- if err := c.writeConfigFileLocked(c.quickstartFile, data, 0o600); err != nil {
- return fmt.Errorf("persist quickstart state: %w", err)
- }
-
- return nil
-}
-
-// LoadQuickstartState retrieves the cached quickstart bootstrap state.
-func (c *ConfigPersistence) LoadQuickstartState() (*QuickstartState, error) {
- c.mu.Lock()
- defer c.mu.Unlock()
-
- var state QuickstartState
- migratedPlaintext, _, err := loadEncryptedJSONLocked(c, c.quickstartFile, &state, "quickstart state")
- if err != nil {
- if os.IsNotExist(err) {
- return &QuickstartState{}, nil
- }
- return nil, err
- }
-
- normalized := NormalizeQuickstartState(&state)
- if migratedPlaintext {
- jsonData, err := json.Marshal(normalized)
- if err != nil {
- return nil, fmt.Errorf("marshal quickstart state migration rewrite: %w", err)
- }
- if err := rewriteEncryptedJSONLocked(c, c.quickstartFile, jsonData, "quickstart state migration rewrite"); err != nil {
- return nil, err
- }
- }
-
- return normalized, nil
-}
-
-// HasQuickstartState reports whether quickstart.enc exists on disk.
-func (c *ConfigPersistence) HasQuickstartState() bool {
- if c == nil || c.fs == nil {
- return false
- }
- _, err := c.fs.Stat(c.quickstartFile)
- return err == nil
-}
diff --git a/internal/config/quickstart_state_test.go b/internal/config/quickstart_state_test.go
deleted file mode 100644
index dd4c635d46..0000000000
--- a/internal/config/quickstart_state_test.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package config
-
-import (
- "bytes"
- "os"
- "path/filepath"
- "testing"
-)
-
-func TestQuickstartStateSaveAndLoad(t *testing.T) {
- dir := t.TempDir()
- persistence := NewConfigPersistence(dir)
-
- expiresAt := int64(1774449000)
- lastSyncedAt := int64(1774448000)
- state := QuickstartState{
- QuickstartToken: "qst_live_test_123",
- QuickstartTokenExpiresAt: &expiresAt,
- QuickstartCreditsTotal: 25,
- QuickstartCreditsRemaining: 17,
- LastSyncedAt: &lastSyncedAt,
- }
-
- if err := persistence.SaveQuickstartState(state); err != nil {
- t.Fatalf("SaveQuickstartState: %v", err)
- }
-
- loaded, err := persistence.LoadQuickstartState()
- if err != nil {
- t.Fatalf("LoadQuickstartState: %v", err)
- }
- if loaded.QuickstartToken != state.QuickstartToken {
- t.Fatalf("QuickstartToken = %q, want %q", loaded.QuickstartToken, state.QuickstartToken)
- }
- if loaded.QuickstartCreditsRemaining != state.QuickstartCreditsRemaining {
- t.Fatalf("QuickstartCreditsRemaining = %d, want %d", loaded.QuickstartCreditsRemaining, state.QuickstartCreditsRemaining)
- }
- if loaded.QuickstartCreditsTotal != state.QuickstartCreditsTotal {
- t.Fatalf("QuickstartCreditsTotal = %d, want %d", loaded.QuickstartCreditsTotal, state.QuickstartCreditsTotal)
- }
- if loaded.QuickstartTokenExpiresAt == nil || *loaded.QuickstartTokenExpiresAt != expiresAt {
- t.Fatalf("QuickstartTokenExpiresAt = %v, want %d", loaded.QuickstartTokenExpiresAt, expiresAt)
- }
- if loaded.LastSyncedAt == nil || *loaded.LastSyncedAt != lastSyncedAt {
- t.Fatalf("LastSyncedAt = %v, want %d", loaded.LastSyncedAt, lastSyncedAt)
- }
-
- raw, err := os.ReadFile(filepath.Join(dir, "quickstart.enc"))
- if err != nil {
- t.Fatalf("ReadFile(quickstart.enc): %v", err)
- }
- if bytes.Contains(raw, []byte(state.QuickstartToken)) {
- t.Fatal("quickstart.enc should not contain the raw quickstart token")
- }
-}
-
-func TestLoadQuickstartState_MissingReturnsEmptyState(t *testing.T) {
- persistence := NewConfigPersistence(t.TempDir())
-
- loaded, err := persistence.LoadQuickstartState()
- if err != nil {
- t.Fatalf("LoadQuickstartState: %v", err)
- }
- if loaded == nil {
- t.Fatal("expected empty quickstart state, got nil")
- }
- if loaded.QuickstartToken != "" || loaded.QuickstartCreditsRemaining != 0 {
- t.Fatalf("expected zero-value quickstart state, got %#v", loaded)
- }
-}
diff --git a/pkg/licensing/billing_store.go b/pkg/licensing/billing_store.go
index a12e4b5209..6976750f2c 100644
--- a/pkg/licensing/billing_store.go
+++ b/pkg/licensing/billing_store.go
@@ -22,8 +22,8 @@ type BillingState struct {
// The overflow window is 14 days from this timestamp.
OverflowGrantedAt *int64 `json:"overflow_granted_at,omitempty"`
- // Quickstart credits: 25 free hosted Patrol runs for every new workspace.
- // No API key needed — uses the Pulse-hosted MiniMax proxy.
+ // Historical hosted-AI quickstart fields retained for old billing-state
+ // compatibility. New v6 workspaces must not grant or consume these values.
QuickstartCreditsGranted bool `json:"quickstart_credits_granted,omitempty"`
QuickstartCreditsUsed int `json:"quickstart_credits_used,omitempty"`
QuickstartCreditsGrantedAt *int64 `json:"quickstart_credits_granted_at,omitempty"`
diff --git a/pkg/licensing/license_server_client.go b/pkg/licensing/license_server_client.go
index 71b495407f..33cd841f79 100644
--- a/pkg/licensing/license_server_client.go
+++ b/pkg/licensing/license_server_client.go
@@ -294,59 +294,6 @@ func (c *LicenseServerClient) CreateCheckoutPortalHandoff(ctx context.Context, r
return &result, nil
}
-// BootstrapQuickstart exchanges a runtime identity for a short-lived
-// quickstart token and the current authoritative quickstart inventory.
-// Callers must pass a server-verified quickstart authority token as
-// bearerToken: either an installation token or a signed entitlement lease JWT.
-func (c *LicenseServerClient) BootstrapQuickstart(ctx context.Context, bearerToken string, req QuickstartBootstrapRequest) (*QuickstartBootstrapResponse, error) {
- if err := c.ready(); err != nil {
- return nil, err
- }
-
- if strings.TrimSpace(bearerToken) == "" {
- return nil, &LicenseServerError{
- StatusCode: http.StatusUnauthorized,
- Code: "activation_required",
- Message: "Quickstart bootstrap requires an activated or entitlement-backed runtime",
- Retryable: false,
- }
- }
-
- body, err := json.Marshal(req)
- if err != nil {
- return nil, fmt.Errorf("marshal quickstart bootstrap request: %w", err)
- }
-
- httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/v1/quickstart/bootstrap", bytes.NewReader(body))
- if err != nil {
- return nil, fmt.Errorf("create quickstart bootstrap request: %w", err)
- }
- httpReq.Header.Set("Content-Type", "application/json")
- httpReq.Header.Set("Authorization", "Bearer "+strings.TrimSpace(bearerToken))
-
- bootstrapClient := *c.httpClient
- bootstrapClient.Timeout = 10 * time.Second
-
- resp, err := bootstrapClient.Do(httpReq)
- if err != nil {
- return nil, fmt.Errorf("quickstart bootstrap request failed: %w", err)
- }
- defer resp.Body.Close()
-
- if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
- return nil, c.parseError(resp)
- }
-
- var result QuickstartBootstrapResponse
- if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&result); err != nil {
- return nil, fmt.Errorf("decode quickstart bootstrap response: %w", err)
- }
- if strings.TrimSpace(result.QuickstartTokenExpiresAt) == "" {
- result.QuickstartTokenExpiresAt = strings.TrimSpace(result.TokenExpiresAt)
- }
- return &result, nil
-}
-
// FetchRevocations polls the revocation feed for events after the given sequence number.
// The feedToken authenticates access to the revocation feed.
func (c *LicenseServerClient) FetchRevocations(ctx context.Context, feedToken string, sinceSeq int64, limit int) (*RevocationFeedResponse, error) {
diff --git a/pkg/licensing/license_server_client_test.go b/pkg/licensing/license_server_client_test.go
index 74570902d7..7f90214515 100644
--- a/pkg/licensing/license_server_client_test.go
+++ b/pkg/licensing/license_server_client_test.go
@@ -500,103 +500,3 @@ func TestClientRefreshGrant(t *testing.T) {
}
})
}
-
-func TestClientBootstrapQuickstart(t *testing.T) {
- t.Run("uses provided quickstart bearer token", func(t *testing.T) {
- var seenAuthorization string
- var seenRequest QuickstartBootstrapRequest
-
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodPost {
- t.Errorf("Method = %q, want POST", r.Method)
- }
- if r.URL.Path != "/v1/quickstart/bootstrap" {
- t.Errorf("Path = %q, want /v1/quickstart/bootstrap", r.URL.Path)
- }
- seenAuthorization = r.Header.Get("Authorization")
- if err := json.NewDecoder(r.Body).Decode(&seenRequest); err != nil {
- t.Fatalf("decode request: %v", err)
- }
- w.WriteHeader(http.StatusCreated)
- json.NewEncoder(w).Encode(QuickstartBootstrapResponse{
- QuickstartToken: "qst_live_123",
- QuickstartTokenExpiresAt: time.Now().Add(30 * time.Minute).UTC().Format(time.RFC3339),
- CreditsRemaining: 17,
- CreditsTotal: 25,
- })
- }))
- defer server.Close()
-
- client := NewLicenseServerClient(server.URL)
- resp, err := client.BootstrapQuickstart(context.Background(), "pit_live_token", QuickstartBootstrapRequest{
- InstanceFingerprint: "fp-123",
- InstanceName: "pulse-test",
- UseCase: "patrol",
- })
- if err != nil {
- t.Fatalf("BootstrapQuickstart failed: %v", err)
- }
- if seenAuthorization != "Bearer pit_live_token" {
- t.Fatalf("Authorization = %q, want Bearer pit_live_token", seenAuthorization)
- }
- if seenRequest.UseCase != "patrol" {
- t.Fatalf("UseCase = %q, want patrol", seenRequest.UseCase)
- }
- if resp.QuickstartToken != "qst_live_123" {
- t.Fatalf("QuickstartToken = %q, want qst_live_123", resp.QuickstartToken)
- }
- if resp.CreditsRemaining != 17 || resp.CreditsTotal != 25 {
- t.Fatalf("credits = %d/%d, want 17/25", resp.CreditsRemaining, resp.CreditsTotal)
- }
- })
-
- t.Run("accepts token_expires_at alias from the server", func(t *testing.T) {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(http.StatusCreated)
- json.NewEncoder(w).Encode(map[string]any{
- "quickstart_token": "qst_live_456",
- "token_expires_at": "2026-04-03T18:30:00Z",
- "credits_remaining": 25,
- "credits_total": 25,
- })
- }))
- defer server.Close()
-
- client := NewLicenseServerClient(server.URL)
- resp, err := client.BootstrapQuickstart(context.Background(), "pit_live_token", QuickstartBootstrapRequest{
- InstanceFingerprint: "fp-123",
- })
- if err != nil {
- t.Fatalf("BootstrapQuickstart failed: %v", err)
- }
- if resp.QuickstartTokenExpiresAt != "2026-04-03T18:30:00Z" {
- t.Fatalf("QuickstartTokenExpiresAt = %q, want 2026-04-03T18:30:00Z", resp.QuickstartTokenExpiresAt)
- }
- })
-
- t.Run("requires installation bearer token", func(t *testing.T) {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- t.Fatal("bootstrap request should not reach the server without an installation token")
- }))
- defer server.Close()
-
- client := NewLicenseServerClient(server.URL)
- _, err := client.BootstrapQuickstart(context.Background(), "", QuickstartBootstrapRequest{
- InstanceFingerprint: "fp-123",
- UseCase: "patrol",
- })
- if err == nil {
- t.Fatal("expected missing installation token error")
- }
- apiErr, ok := err.(*LicenseServerError)
- if !ok {
- t.Fatalf("expected *LicenseServerError, got %T", err)
- }
- if apiErr.StatusCode != http.StatusUnauthorized {
- t.Fatalf("StatusCode = %d, want %d", apiErr.StatusCode, http.StatusUnauthorized)
- }
- if apiErr.Code != "activation_required" {
- t.Fatalf("Code = %q, want activation_required", apiErr.Code)
- }
- })
-}
diff --git a/pkg/licensing/quickstart_bootstrap.go b/pkg/licensing/quickstart_bootstrap.go
deleted file mode 100644
index 214d0ab76d..0000000000
--- a/pkg/licensing/quickstart_bootstrap.go
+++ /dev/null
@@ -1,23 +0,0 @@
-package licensing
-
-// QuickstartBootstrapRequest is sent to the license server to exchange a
-// runtime identity for a server-issued quickstart token.
-//
-// Activated installs authenticate the request with their installation token.
-// Entitlement-backed runtimes authenticate the request with their signed
-// entitlement lease JWT. The request body supplies only binding metadata.
-type QuickstartBootstrapRequest struct {
- InstanceFingerprint string `json:"instance_fingerprint,omitempty"`
- InstanceName string `json:"instance_name,omitempty"`
- UseCase string `json:"use_case,omitempty"`
-}
-
-// QuickstartBootstrapResponse contains the server-issued quickstart token and
-// the current authoritative quickstart inventory snapshot.
-type QuickstartBootstrapResponse struct {
- QuickstartToken string `json:"quickstart_token"`
- QuickstartTokenExpiresAt string `json:"quickstart_token_expires_at,omitempty"`
- TokenExpiresAt string `json:"token_expires_at,omitempty"`
- CreditsRemaining int `json:"credits_remaining"`
- CreditsTotal int `json:"credits_total"`
-}
diff --git a/pkg/licensing/quickstart_credits.go b/pkg/licensing/quickstart_credits.go
index 2efc87f76f..68ac92ccb0 100644
--- a/pkg/licensing/quickstart_credits.go
+++ b/pkg/licensing/quickstart_credits.go
@@ -1,13 +1,12 @@
package licensing
-import "time"
-
-// QuickstartCreditsTotal is the number of free hosted Patrol runs granted
-// to every new workspace.
+// QuickstartCreditsTotal is retained only for historical billing-state
+// compatibility. New v6 workspaces must not mint hosted-AI quickstart credits.
const QuickstartCreditsTotal = 25
-// QuickstartCreditsRemaining returns the number of unused quickstart credits.
-// Returns 0 if credits were never granted.
+// QuickstartCreditsRemaining returns the historical unused quickstart credits
+// recorded in old billing state. It is read-only compatibility, not an active
+// entitlement source.
func (b *BillingState) QuickstartCreditsRemaining() int {
if b == nil || !b.QuickstartCreditsGranted {
return 0
@@ -23,25 +22,3 @@ func (b *BillingState) QuickstartCreditsRemaining() int {
func (b *BillingState) HasQuickstartCredits() bool {
return b.QuickstartCreditsRemaining() > 0
}
-
-// GrantQuickstartCredits marks quickstart credits as granted (idempotent).
-// Returns true if credits were newly granted, false if already granted.
-func (b *BillingState) GrantQuickstartCredits() bool {
- if b.QuickstartCreditsGranted {
- return false
- }
- b.QuickstartCreditsGranted = true
- now := time.Now().Unix()
- b.QuickstartCreditsGrantedAt = &now
- return true
-}
-
-// ConsumeQuickstartCredit decrements one quickstart credit.
-// Returns false if no credits remain.
-func (b *BillingState) ConsumeQuickstartCredit() bool {
- if !b.HasQuickstartCredits() {
- return false
- }
- b.QuickstartCreditsUsed++
- return true
-}
diff --git a/pkg/licensing/quickstart_credits_test.go b/pkg/licensing/quickstart_credits_test.go
index 6ca3f7487e..6d295ac486 100644
--- a/pkg/licensing/quickstart_credits_test.go
+++ b/pkg/licensing/quickstart_credits_test.go
@@ -63,52 +63,3 @@ func TestHasQuickstartCredits(t *testing.T) {
})
}
}
-
-func TestGrantQuickstartCredits_Idempotent(t *testing.T) {
- bs := &BillingState{}
- if !bs.GrantQuickstartCredits() {
- t.Fatal("first grant should return true")
- }
- if !bs.QuickstartCreditsGranted {
- t.Fatal("should be granted")
- }
- if bs.QuickstartCreditsGrantedAt == nil {
- t.Fatal("granted_at should be set")
- }
- firstGrantedAt := *bs.QuickstartCreditsGrantedAt
-
- // Second grant should be idempotent
- if bs.GrantQuickstartCredits() {
- t.Fatal("second grant should return false")
- }
- if *bs.QuickstartCreditsGrantedAt != firstGrantedAt {
- t.Fatal("granted_at should not change on second grant")
- }
-}
-
-func TestConsumeQuickstartCredit(t *testing.T) {
- bs := &BillingState{QuickstartCreditsGranted: true}
-
- // Consume all credits
- for i := 0; i < QuickstartCreditsTotal; i++ {
- if !bs.ConsumeQuickstartCredit() {
- t.Fatalf("consume at iteration %d should succeed", i)
- }
- }
-
- // Next consume should fail
- if bs.ConsumeQuickstartCredit() {
- t.Fatal("consume after exhaustion should return false")
- }
-
- if bs.QuickstartCreditsUsed != QuickstartCreditsTotal {
- t.Errorf("expected %d used, got %d", QuickstartCreditsTotal, bs.QuickstartCreditsUsed)
- }
-}
-
-func TestConsumeQuickstartCredit_NotGranted(t *testing.T) {
- bs := &BillingState{}
- if bs.ConsumeQuickstartCredit() {
- t.Fatal("consume without grant should return false")
- }
-}