PlotDirector/Docs/Codex/DiscretionaryAi.md

12 KiB

Discretionary AI: implementation audit

Existing execution paths

Text-analysis provider calls use IStoryIntelligenceClient / StoryIntelligenceClient, the configured OpenAI Responses API client, existing concurrency limiter, stage model settings and structured-output contracts. The client retries a provider request up to three times. Its result exposes nullable input/output tokens, retry count, duration, model and nullable estimated cost. A missing cost is not actual zero expenditure.

Category Existing path Treatment
Initial import PersistedStoryIntelligenceRunner: chapter/scene analysis and corrective parse retries Existing Import/StoryIntelligence entitlement; excluded from discretionary credits
Initial import ManuscriptScanPreviewStore → CharacterSexHintAiService Import assistance; excluded
Initial import/materialisation CharacterIntelligenceService profile updates from persisted scene processing Part of existing analysis pipeline; excluded
Initial post-import enrichment CharacterEnrichmentService.QueueAfterCharacterResolutionAsync Import completion; excluded
Initial post-import narrative synthesis WholeBookPlotIntelligenceService.QueueAfterCharacterResolutionAsync Import completion; excluded
Discretionary author processing CharactersController.Reanalyse → CharacterService.QueueCharacterReanalysisAsync → single-character enrichment queue Central entitlement, reservation and provider budget required
Discretionary author processing IntentAssessmentController.Analyse → IntentAssessmentService.Analyse Existing reachable endpoint despite retired Intent workspace; must receive central enforcement without reviving its UI
Import recovery Onboarding character-enrichment and whole-book synthesis Retry endpoints Inspection of migrations 185 and 174 confirms these only retry Failed runs; they cannot repeat Completed results. Preserve their existing import recovery rules
Administrative illustration generation AdminController illustration queue/regeneration → IllustrationGenerationWorker → existing OpenAI Images API provider Shared illustration-library administration, not discretionary author processing. Preserve its existing separate image configuration and persisted generation metadata
Administrative diagnostics Story/Chapter dry runs, existing-chapter queue and full-chapter tests under AdminOnly Operational administrator actions; existing author subscription allowance is not the appropriate owner. Remain separately authorised and bounded; report separately
Ambiguous automatic processing ManuscriptStructureAnalysisService (including a corrective request) Used by paragraph/Word structural reconciliation as well as import. Do not put essential manuscript synchronisation behind discretionary credits without a product decision
New discretionary author processing Selected-name contextual verification Central entitlement/allowance; candidate search and valid cache reuse have no provider expenditure

Deterministic candidate preparation, persisted review reads, name catalogue searches, recorded identity matching, manual editing and reading stored results are not AI executions and must remain outside these allowances.

Subscription audit

Existing stable subscription names are DraftDesk, WritingRoom, StoryForge and AuthorStudio. SubscriptionService.GetEffectiveEntitlementAsync already resolves active paid/trial subscriptions and administrative subscription overrides. CanUseFeatureAsync currently gates activity, with Import/StoryIntelligence distinct feature identifiers. Billing records retain StartDateUTC, BillingInterval and current provider period boundaries, including annual subscriptions. Existing durable book-slot reservation infrastructure demonstrates the application's stored-procedure reservation pattern; it is not an AI allowance store.

Discretionary policy must be additive: DraftDesk has no discretionary entitlement, and no commercial price or existing subscription row should change. New operations and unconfigured tiers fail closed. AI allowance periods must be monthly even where the provider billing period is annual. Administrative test values are implementation configuration, not commercial recommendations.

Open product classification

The structural reconciliation path is automatic system processing and is provisionally excluded. The existing book enrichment/synthesis Retry procedures only accept Failed import runs, so these remain import recovery. Any future repeat-completed action requires a new central discretionary operation definition. Administrative provider expenditure is operational and should be inspectable separately from author credits. These distinctions do not authorise changing initial import prompts, defaults or classifications.

Implemented allowance contract

New policies are stored centrally in migration 326, separate from existing subscription records and prices. Stable initial operation identifiers are character.biography.regenerate, intent.assess and names.verify. Draft Desk is denied by both application entitlement checks and reservation SQL even if a tier policy is misconfigured. Unconfigured operations/tiers fail closed. Policies ship disabled, with zero tier allowances. Administrators configure them through /admin/ai; these changes reuse SubscriptionAdministrationAudit.

Allowances renew on the first day of each UTC calendar month, independently of annual billing. This avoids resets when a billing anchor, tier, override, device or session changes. Account overrides replace capacity, not consumed usage, have an expiry and cannot confer entitlement on Draft Desk. No rollover, additional purchasing or price changes are introduced.

Reservations serialise on an account application lock and persist idempotency keys. Their operation limits are snapshotted before execution. Queued biography reservations expire after 24 hours; synchronous operation reservations expire after their configured duration plus two minutes. A claimed operation has a maximum execution duration plus finalisation grace. Central maintenance recovers expired reservations every five minutes, releases blocked manual jobs and publishes their failure through the existing enrichment notifier. Durable claims prevent another worker from executing the same reservation. A process restart does not reset usage, request counts or token budgets.

The existing provider client allocates a durable request slot before each HTTP attempt, including retries. The token budget is conservative: encoded request bytes plus configured maximum output and envelope overhead. It is not billed-token telemetry. Actual returned input/output/cache tokens are recorded separately. Actual and estimated monetary costs remain nullable; the existing provider integration supplies no monetary billing receipt, so none is invented. Provider attempts remain inspectable when author credits are released, including unknown expenditure after an interrupted process.

The existing biography queue binds reservations to runs atomically in migration 327. Its canonical result save verifies the execution lease and settles credits in the same transaction as existing protected character updates. Imported enrichment runs remain outside discretionary allowance enforcement. Old queued manual runs without reservations cannot initiate new provider calls; they require a fresh confirmed request. Failed initial-import retry procedures remain unchanged.

The reachable Intent assessment endpoint uses the same central reservation/provider enforcement. Migration 328 saves validated evidence and settles credits atomically; a duplicate existing result releases the redundant reservation. Existing saved evidence and author decisions remain independently readable.

The shared PlotDirectorAi.confirm dialog shows entitlement restrictions, operation credit cost, remaining allowance and next renewal before author confirmation. Subscription comparison uses the existing Manage Account route. Account allowance is displayed only in Subscription; ordinary writing/catalogue screens have no persistent credit counter.

Development configuration and later commercial decisions

The disabled seed rows contain safety bounds and example operation costs only, not commercial pricing: biography 10 credits, one character, six HTTP requests, 1,500,000 conservative tokens, 16,000 output tokens/request, 900 seconds; name verification 1 credit, 100 candidate contexts, nine HTTP requests, 150,000 conservative tokens, 8,000 output tokens/request, 300 seconds; intent assessment 1 credit, one scene, three HTTP requests, 100,000 conservative tokens, 6,000 output tokens/request, 180 seconds. Disabled operations incur no calls. Isolated qualification tests temporarily enable synthetic five-credit allowances and restore the fixture policy afterwards.

The product owner must choose AI-enabled higher tiers, monthly credits by tier, operation credit costs, scope/request/token/duration bounds and enablement. These are database-administered settings and do not require deployment. The current UTC monthly renewal convention is explicit; any future change needs a durable period transition that cannot reset consumed usage. No final commercial decisions have been made.

Phase 4 verification

The normal build and executable full regression harness passed. Focused tests execute the real provider client against a mocked HTTP handler: every retry reserves a slot, budget exhaustion prevents another HTTP call, returned usage/cache telemetry is retained, and no monetary costs or external expenditure are fabricated. Biography gate tests cover missing confirmation, denied entitlement, character authorisation, coalescing/refund, duplicate request reuse and fail-closed legacy manual jobs.

--discretionary-ai-database runs only against a database whose name starts PlotDirector_Qualification_ and checks the connected database before writing. Disposable fixture checks passed for 20 concurrent requests against five credits, 10 simultaneous duplicate deliveries, execution claim exclusion, retry limits, settlement idempotence, failed-result refunds, abandoned reservations, expired manual-job recovery/progress events, stale cost/scope/unknown-operation rejection, Draft Desk denial despite misconfiguration, policy changes, expiring overrides, monthly renewal and administration auditing. Synthetic rows are removed and policy values restored.

Compiled Razor/browser fixture checks passed in normal Chromium and actual installed Chromium PWA mode. They cover locked feature discovery and subscription link, cost confirmation, cancellation without submission, one explicit confirmed request, account allowance presentation and all seven administration themes. Screenshots are in /tmp/pd-ai-allowances. These checks do not substitute for final authenticated Development smoke checks. No live migrations or deployment have occurred at this phase gate.

Development integration defaults

Migration 332 enables the three defined operations and gives Writing Room, Story Forge and Author Studio 100 monthly credits only on PlotDirector_Development or an isolated PlotDirector_Qualification_… database. Draft Desk and unknown tiers remain denied. Costs and execution limits remain the provisional values above (biography 10 credits; name verification and intent assessment 1 each). These are Development test settings, not commercial commitments. It updates only the new AI policy tables, and skips an installation with usage or configured/admin-modified policies. Existing subscriptions, prices and import entitlements are untouched. All settings remain editable under Admin → AI; an account override changes credit quantity without granting an otherwise denied entitlement.