# PA Agent Migration Plan

Status as of 2026-07-23: this plan is implemented as the **price-action
foundation** inside Moonfish. It is no longer the only product direction. The
active product surface is now the native systematic A-share MoonPack described
in `README.mbt.md`, `moonpack/`, `suitepack/`, `ashare/`, and `cmd/`.

The PA foundation remains important because it proves suite-native boundaries:
deterministic contracts, MoonBook evidence, replay/export, app-tool projection,
release, rollback, and day-2 operations readiness. New work should reuse those
patterns without adding PA compatibility shims or treating `../paa` as a
runtime dependency.

## Phase Status

The PA migration phases below are complete as a deterministic, tested
foundation: behavior inventory, pack/book contracts, model-gateway contracts,
domain tools, routine projections, MoonBook migration records, Moondesk
app-tool projections, parity/safety evidence, cutover/decommission evidence,
and day-2 operations reports are all present in MoonBit packages.

The active A-share product has now crossed a separate productization milestone:

| Productization phase | Status |
| --- | --- |
| Installable domain pack and authority contracts | Complete |
| Native deterministic scoring/ranking command | Complete |
| Generic installed MoonClaw workflow execution | Complete |
| MoonBook request/result persistence | Complete |
| Moondesk `finance.moonfish` app handover | Complete |
| Fresh installed fixture workflow | Usable and tested |
| Licensed provider acquisition | Not implemented; fails closed |
| Model-backed dossiers and independent review | Not implemented |
| Named-human release and paper-account operations | Contracted, not executable |
| Generic suite lifecycle for starting the pack app service | Remaining integration work |

The current usable product is therefore a native fixture-backed vertical slice,
not the full 26-step research and paper-account contract.

This document describes how to migrate the existing PA Agent in `../paa` into a
MoonSuite-native system. The goal is not to rewrite the Python app as a single
MoonBit monolith. The target shape is a suite pack with clear ownership:

- MoonGate owns model/provider discovery, proxying, health, model catalog,
  usage, and suite integration status.
- MoonClaw owns agent execution: model calls, tool loops, routines, jobs,
  events, context management, retries, and durable execution.
- MoonBook owns durable workspace state: raw evidence, generated records, wiki
  pages, skills, schemas, review queues, and book-owned tools.
- Moondesk owns the operator shell: inspection, configuration, run history, and
  UI surfaces. It must not absorb trading-specific rules.
- The price-action domain pack owns trading vocabulary, schemas, prompt assets,
  strategy routing, data adapters, chart/rendering tools, and analysis records.

The suite-native rule is:

> MoonClaw reasons and executes bounded tools; MoonBook remembers; MoonGate
> routes model traffic; Moondesk observes and operates; domain packages own
> domain rules.

## Source Inventory

The current PA Agent is organized as one Python desktop application:

- `../paa/pa_agent/orchestrator/two_stage.py`: deterministic Stage 1 -> validate
  -> route -> Stage 2 -> validate -> persist workflow.
- `../paa/pa_agent/orchestrator/free_chat.py`: post-analysis chat behavior.
- `../paa/pa_agent/ai/prompts/schemas.py`: Stage 1 and Stage 2 JSON contracts.
- `../paa/pa_agent/ai/json_validator.py`: JSON validation categories and
  validation result handling.
- `../paa/pa_agent/ai/stage1_normalizer.py` and
  `../paa/pa_agent/ai/stage2_normalizer.py`: legacy repair behavior to record
  as intentional incompatibilities, not as standalone Moonfish compatibility
  code.
- `../paa/pa_agent/ai/pattern_routing.py`: Stage 1 pattern tags to Stage 2
  strategy-file routing.
- `../paa/prompt_engineering/`: price-action prompt files and strategy text.
- `../paa/experience/`: cycle-position examples and memory.
- `../paa/pa_agent/data/`: MT5, TradingView, yfinance, AkShare, and related
  market data adapters.
- `../paa/pa_agent/indicators/`: ATR, EMA, and related indicator calculations.
- `../paa/pa_agent/gui/`: PyQt chart, settings, decision flow, debug, and
  conversation UI.
- `../paa/pa_agent/records/`: analysis history, pending records, trade logs,
  schema definitions, and persistence helpers.
- `../paa/tests/`: unit, property, integration, and smoke coverage that should
  become migration parity tests.

## Target Pack Shape

The migrated system should be organized as a `price-action` suite pack/book:

```text
price-action-book/
  raw/
    market-data/
    model-replies/
    run-events/
  wiki/
    concepts/
    strategy-notes/
    review-pages/
  skills/
    market-diagnosis/
    strategy-routing/
    trade-decision/
    free-chat/
  schemas/
    stage1.schema.json
    stage2.schema.json
    analysis-record.schema.json
    kline-frame.schema.json
  tools/
    prepare_analysis_workspace
    prepare_suite_settings_plan
    run_two_stage_routine
    prepare_acceptance_report
    prepare_parity_report
    prepare_cutover_readiness_report
    prepare_cutover_plan
    prepare_operator_handoff_report
    prepare_decommission_report
    prepare_moonfish_product_status
    prepare_product_launch_manifest
    prepare_product_rehearsal_report
    prepare_release_certificate
    prepare_rollback_window_report
    prepare_operations_readiness_report
    prepare_legacy_import_plan
    materialize_legacy_import_projection
    select_experience_memories
    prepare_analysis_plan
    prepare_analysis_job
    prepare_retry_decision
    fetch_kline_snapshot
    compute_indicators
    compute_structure_levels
    classify_market_structure
    route_strategy_files
    validate_stage_json
    write_analysis_record
    prepare_book_commit_report
    queue_analysis_review
    prepare_followup_context
    prepare_followup_session_plan
    prepare_replay_plan
    prepare_export_manifest
    evaluate_decision_policy
    prepare_safety_report
    render_chart_frame
    prepare_moondesk_app_smoke_report
    render_operator_run_view
    render_moondesk_app_tool_manifest
    render_run_history
    ingest_market_snapshot
  apps/
    moondesk-price-action/
  records/
    analyses/
    pending/
    reviews/
    operations/
```

The exact physical layout may change as MoonBook packaging conventions mature,
but the ownership boundaries should remain stable.

## Phase 0: Freeze Behavior And Define Parity

Purpose: capture what the Python PA Agent does today before moving pieces.

Source inputs:

- `../paa/README.md`
- `../paa/PA_Agent使用文档.md`
- `../paa/pa_agent/orchestrator/two_stage.py`
- `../paa/tests/unit/`
- `../paa/tests/property/`
- `../paa/tests/integration/`
- `../paa/tests/e2e/`

Work:

1. Document current workflows:
   - market-data snapshot creation
   - Stage 1 diagnosis
   - JSON validation and retry
   - pattern/strategy routing
   - experience lookup
   - Stage 2 decision
   - persistence
   - free chat after analysis
   - UI inspection and debug behavior
2. Classify tests into migration groups:
   - schema and explicit policy parity
   - data-frame and indicator parity
   - strategy-routing parity
   - two-stage routine parity
   - persistence and redaction parity
   - UI smoke parity
3. Choose golden fixtures from PA Agent tests and records.
4. Define non-goals:
   - no broker connection
   - no order execution
   - no trading-specific logic in Moondesk core
   - no bespoke one-off orchestrator when MoonClaw routines can own the flow

Deliverables:

- PA Agent behavior inventory.
- Fixture list and parity matrix.
- Known incompatibility list.

Exit criteria:

- Every source subsystem has an intended MoonSuite owner.
- The initial parity matrix identifies which tests must pass before cutover.

## Phase 1: Create The Price-Action Book Skeleton

Purpose: establish the domain pack/book as the durable home for prompts,
schemas, records, and tools.

Work:

1. Create a `price-action` book structure with `raw/`, `wiki/`, `skills/`,
   `schemas/`, `tools/`, `apps/`, and `records/`.
2. Move PA prompt assets conceptually from `../paa/prompt_engineering/` into
   book-owned skills and strategy notes.
3. Convert hardcoded stage contracts from Python into schema files:
   - `schemas/stage1.schema.json`
   - `schemas/stage2.schema.json`
   - `schemas/analysis-record.schema.json`
   - `schemas/kline-frame.schema.json`
4. Define record IDs, run IDs, source IDs, and timestamps consistently.
5. Define the data retention model:
   - raw market snapshots are immutable evidence
   - model requests/replies are immutable evidence
   - normalized stage outputs are generated records
   - review decisions are user-authored records

Deliverables:

- Book skeleton.
- Schema files.
- Prompt/skill file map.
- Record naming convention.

Exit criteria:

- The price-action pack can store raw evidence and generated analysis records
  without calling a model.
- Prompt files and schema files are externally inspectable, not embedded in UI
  code.

Current Moonfish implementation:

- `pack/` declares MoonBook-owned paths for raw evidence, wiki concepts,
  strategy notes, skills, records, reviews, imports, replays, exports, safety,
  product status, and skill migrations.
- `skills/` exposes a prompt/strategy catalog and a typed skill migration plan
  that maps all 32 `../paa/prompt_engineering` source files into MoonBook skill,
  strategy-note, and concept-reference targets.
- `schemas/` includes the skill migration input, source-ref, and plan contracts
  so the mapping is inspectable as suite evidence rather than embedded in UI
  code.

## Phase 2: Wire MoonGate Model Discovery

Purpose: replace PA Agent's local provider settings and direct client wiring
with suite model discovery.

Source inputs:

- `../paa/pa_agent/ai/deepseek_client.py`
- `../paa/pa_agent/ai/cursor_sdk_client.py`
- `../paa/pa_agent/ai/qclaw_connector.py`
- `../paa/pa_agent/config/settings.py`
- MoonGate status file: `<MoonSuiteRoot>/.moonsuite/suite-status.json`

Work:

1. Read MoonGate suite status to discover:
   - `openaiBaseUrl`
   - available model catalog
   - provider health
   - usage and quota signals
   - integration contracts
2. Build MoonClaw model config from MoonGate rather than PA Agent settings.
3. Preserve PA Agent semantics that matter:
   - model name selection
   - reasoning/thinking mode metadata
   - context window hints
   - token usage capture
   - provider error normalization
4. Remove direct domain dependency on provider-specific clients where possible.

Deliverables:

- Model discovery adapter.
- Provider-health and quota mapping.
- Compatibility notes for PA Agent provider settings.

Exit criteria:

- A price-action routine can make a model call through MoonGate-provided base
  URL and model metadata.
- Provider secrets are not persisted into analysis records.

Current Moonfish implementation:

- `model/` represents MoonGate suite status with OpenAI-compatible base URL,
  default model, model catalog, usage/quota snapshot, integration contracts, and
  provider error normalization.
- `model/` prepares explicit context-budget plans from prompt packets and
  MoonGate catalog context windows. `orchestration/` blocks model calls when the
  prompt plus reserved completion budget exceeds the selected model window, and
  `book/` persists the report under `records/context-budgets/<run>.json`.
- `planning/` turns quota exhaustion into blocking plan issues and degraded
  integration contracts into explicit readiness warnings before a routine runs.
- `acceptance/` includes a model-discovery gate so cutover fixtures prove model
  URL, default model, quota state, and contract readiness are available.

## Phase 3: Port Domain Tools

Purpose: expose PA Agent capabilities as bounded MoonClaw tools with typed
contracts.

Source inputs:

- `../paa/pa_agent/data/`
- `../paa/pa_agent/indicators/`
- `../paa/pa_agent/ai/market_features.py`
- `../paa/pa_agent/ai/kline_features.py`
- `../paa/pa_agent/ai/structure_levels.py`
- `../paa/pa_agent/ai/pattern_routing.py`
- `../paa/pa_agent/ai/json_validator.py`
- `../paa/pa_agent/records/`

Tool set:

- `fetch_kline_snapshot`: fetch closed-bar market data from configured data
  source.
- `prepare_market_refresh_plan`: decide whether a market request can run now,
  should wait for the currently forming bar to close, should request an external
  snapshot, or needs timeframe review. This replaces UI-owned refresh loop
  timing with typed suite evidence.
- `ingest_market_snapshot`: accept externally fetched closed-bar snapshots for a
  planned request, reject mismatches as typed review issues, and avoid fake
  snapshots for unavailable providers.
- `prepare_analysis_plan`: turn operator intent plus MoonGate suite status into
  a typed pre-execution plan with market/model choices, routine phases,
  readiness flags, and validation issues.
- `prepare_analysis_workspace`: compose one product-level run workspace from
  planning, workflow, job, retry, app, replay, export, safety, and history
  projections.
- `prepare_suite_settings_plan`: migrate PA Agent provider, market, and
  validation settings into MoonGate suite status, typed market requests, and
  MoonClaw retry policy without copying plaintext secrets.
- `prepare_parity_report`: summarize deterministic parity groups, fixture
  references, semantic equivalence, and intentional differences.
- `prepare_cutover_readiness_report`: evaluate tool coverage, workspace
  execution, safety, replay, imports, operator surface, and export redaction
  before cutover.
- `prepare_cutover_plan`: turn readiness evidence and import plans into an
  operator checklist, rollback plan, imported-data manifest path, and
  decommission note.
- `prepare_operations_readiness_report`: prove the post-cutover day-2 operating
  surface across MoonGate suite health, primary workflow, rollback monitoring,
  replay/export, resilience, and Moondesk observability.
- `prepare_legacy_import_plan`: map legacy PA Agent records, pending analyses,
  experience entries, and trade logs into idempotent MoonBook target paths with
  review/skipped dispositions.
- `materialize_legacy_import_projection`: turn ready legacy import plan items
  into inspectable MoonBook record projections with source paths, schema
  versions, target paths, summaries, and replay anchors.
- `select_experience_memories`: choose bounded Stage 2 experience memory from
  MoonBook by cycle position, direction, pattern overlap, and recency.
- `prepare_analysis_job`: turn a plan plus optional run bundle, cancellation,
  failure, and retry policy into a durable MoonClaw job state.
- `prepare_retry_decision`: classify validation failures and decide whether a
  bounded model retry is allowed, including feedback targets and immutable-field
  guards.
- `compute_indicators`: calculate ATR, EMA, price tick, warmup state, and
  derived features.
- `compute_structure_levels`: derive deterministic support, resistance, and
  midline levels from closed-bar evidence for chart inspection and replay.
- `classify_market_structure`: compute deterministic candidates such as
  barbwire, trend context, support/resistance, and structure levels.
- `route_strategy_files`: map Stage 1 diagnosis tags to Stage 2 skill files.
- `validate_stage_json`: validate Stage 1 or Stage 2 output against schemas and
  semantic rules.
- `evaluate_decision_policy`: enforce standalone advisory hard bans that used to
  live mainly in prompt text, including no market orders, reversal-risk no-order
  boundaries, order confidence floor, and required risk notes.
- `write_analysis_record`: persist raw inputs, prompts, replies, normalized
  outputs, token usage, and validation events into MoonBook.
- `prepare_book_commit_report`: classify every planned artifact for
  idempotent MoonBook commit, including payload class, redaction boundary,
  readiness status, and stable idempotency key.
- `prepare_redaction_audit`: prove the no-plaintext secret and
  sensitive-evidence boundary across MoonGate provider metadata, MoonBook commit
  evidence, Moondesk app bindings, and public exports.
- `prepare_cancellation_report`: turn a cancelled MoonClaw routine result into
  inspectable evidence that an operator cancel emitted an event, preserved a
  partial analysis record path, and stopped without fabricating later-stage
  evidence.
- `prepare_provider_failure_report`: combine normalized MoonGate/provider error
  evidence with a failed routine result, proving retry disposition, no
  fabricated model-call evidence, and partial-record preservation for network
  or gateway failures.
- `prepare_record_integrity_report`: prove MoonBook record durability by
  checking the self-contained analysis record, write-plan declarations,
  idempotent commit readiness, replay anchors, and export anchors.
- `queue_analysis_review`: derive actionable MoonBook review items from missing
  market data, validation issues, and low-confidence decisions.
- `prepare_followup_context`: expose durable evidence anchors, review status,
  and suggested topics for post-analysis chat.
- `prepare_followup_session_plan`: prepare the bounded free-chat session
  contract with stable MoonBook prefix anchors, citation paths, sidecar turn
  persistence, and explicit reasoning-resend policy.
- `prepare_followup_response`: prepare a cited follow-up turn from durable
  analysis context without re-running the two-stage routine.
- `prepare_replay_plan`: build a deterministic replay plan from persisted
  MoonBook evidence without requiring live market data.
- `prepare_export_manifest`: build audit or public-summary export manifests
  from durable run artifacts.
- `prepare_safety_report`: produce explicit checks for broker execution paths,
  secret/sensitive-evidence redaction, public export redaction, replay over
  persisted evidence, and suite ownership.
- `render_chart_frame`: produce chart images or frames for operator review.
- `render_operator_run_view`: produce Moondesk app-tool panels, actions, status
  counts, and artifact links for one run without putting trading rules in
  Moondesk core.
- `render_run_history`: produce a Moondesk run-history index across analysis
  bundles.

Work:

1. Define JSON-schema contracts for every tool input and output.
2. Keep tools small and deterministic where possible.
3. Preserve redaction behavior from `../paa/pa_agent/util/mask_secret.py`.
4. Separate network/data-source errors from model/schema errors.
5. Keep any trading policy or strategy text in skills, not in tool code.

Deliverables:

- Tool descriptors and schemas.
- Tool implementations.
- Golden fixture tests for indicators, routing, validation, and records.

Exit criteria:

- Each tool can be invoked independently.
- Tool outputs are stable enough for MoonBook records and test fixtures.
- No tool performs unbounded model reasoning.

## Phase 4: Implement The MoonClaw Two-Stage Routine

Purpose: replace PA Agent's bespoke Python orchestrator with an explicit
MoonClaw routine/job.

Source inputs:

- `../paa/pa_agent/orchestrator/two_stage.py`
- `../paa/pa_agent/orchestrator/validation_retry.py`
- `../paa/pa_agent/ai/retry_policy.py`
- `../paa/pa_agent/ai/retry_feedback.py`
- `../paa/pa_agent/ai/trace_semantic_checks.py`
- `../paa/pa_agent/ai/coherence_checks.py`

Routine phases:

1. Create run context:
   - assign run ID
   - capture operator request
   - snapshot model configuration from MoonGate
   - initialize event stream
2. Snapshot market data:
   - call `fetch_kline_snapshot`
   - call `compute_indicators`
   - call `classify_market_structure`
   - persist raw evidence
3. Stage 1 diagnosis:
   - load diagnosis skill files from MoonBook
   - build prompt from schemas, market snapshot, deterministic features, and
     relevant examples
   - call model through MoonClaw model loop
   - capture raw reply and token usage
4. Stage 1 validation:
   - call `validate_stage_json`
   - reject invalid output or retry through explicit policy; do not carry a
     legacy compatibility normalizer into the standalone path
   - retry only according to explicit validation retry policy
   - persist validation result and retry feedback
5. Strategy routing:
   - call `route_strategy_files`
   - load Stage 2 strategy skills and experience entries from MoonBook
6. Stage 2 decision:
   - build prompt with Stage 1 output, strategy files, market evidence, and
     constraints
   - call model
   - capture raw reply and token usage
7. Stage 2 validation:
   - validate schema
   - run semantic checks
   - enforce no-order invariants
   - call `evaluate_decision_policy`
   - retry only when the error category permits retry
8. Persist analysis:
   - call `write_analysis_record`
   - write raw evidence and normalized result
   - emit final routine event
9. Open follow-up mode:
   - expose durable context for free chat
   - prepare a stable session prefix from completed analysis, market, model,
     memory, and chart evidence
   - keep provider reasoning out of resend payloads
   - keep follow-up turns attached to the analysis record

Deliverables:

- MoonClaw routine/job definition.
- Event schema for operator progress.
- Retry and cancellation policy.
- Parity tests for happy path, validation failure, network failure, user cancel,
  no-order decision, and mid-analysis switch.

Exit criteria:

- The routine can run Stage 1 -> route -> Stage 2 without Moondesk-specific
  code.
- The routine emits enough events for a UI, logs, and later replay.
- Partial records are persisted for failed or cancelled runs.

## Phase 5: Migrate Memory And Records Into MoonBook

Purpose: make MoonBook the durable workspace for evidence, experience, review,
and replay.

Source inputs:

- `../paa/experience/`
- `../paa/records/`
- `../paa/trade_records/`
- `../paa/pa_agent/records/analysis_history.py`
- `../paa/pa_agent/records/pending_writer.py`
- `../paa/pa_agent/records/experience_reader.py`
- `../paa/pa_agent/demo/`

Work:

1. Convert experience folders into book wiki pages or structured memory
   records, keyed by cycle position and strategy tag.
2. Convert pending records into MoonBook review queues.
3. Convert trade logs and analysis history into analysis records with explicit
   schema versions.
4. Preserve replay capability:
   - load historical records
   - reconstruct prompts and tool outputs
   - rerun validation
   - compare old and new model outputs
5. Add migration scripts that are idempotent and leave source data untouched.

Deliverables:

- Experience memory import.
- Analysis-record import.
- Review queue import.
- Replay fixtures.

Current Moonfish implementation:

- `config/` prepares suite settings migration plans from legacy PA Agent
  provider/general/validation settings, redacting provider secrets and routing
  model access through MoonGate.
- `orchestration/` runs the suite-native two-stage MoonClaw controller with
  explicit snapshot/model gates, bounded retry pauses, cancellation, partial
  record visibility, and no legacy compatibility normalizer path.
- `cancellation/` packages user-cancel behavior as a reusable report over the
  routine outcome, cancellation event phase, partial record path, and
  stage-boundary preservation.
- `resilience/` packages provider/network failure behavior as a reusable report
  over normalized provider errors, retryability, routine failure boundary, and
  partial analysis record paths. Provider-shaped validation failures remain
  non-retryable in `retry/`; transport retryability is recorded separately for
  bounded job-level handling.
- `integrity/` packages MoonBook record round-trip evidence as an inspectable
  report over the analysis record, write plan, commit report, replay plan, and
  export manifest.
- `policy/` evaluates advisory decision hard bans as typed evidence. Stage 2
  policy failures become retryable validation reports instead of hidden prompt
  assumptions.
- `parity/` prepares golden-fixture parity reports across schema validation,
  market features, routing, routine, persistence/redaction, operator surface,
  safety, and import traceability groups.
- `evaluation/` prepares cutover readiness reports from workspace, import,
  manifest, safety, replay, export, and operator evidence.
- `cutover/` prepares operator cutover checklists, rollback plans, imported-data
  manifest paths, and PA Agent decommission notes from readiness evidence.
- `migration/` prepares idempotent MoonBook import plans for legacy PA Agent
  analysis records, pending records, experience memory, and trade logs while
  leaving source data untouched.
- `migration/` also materializes ready import-plan items into inspectable
  MoonBook record projections with source paths, schema versions, target paths,
  summaries, and replay anchors.
- `memory/` selects suite-native experience memory for Stage 2 prompt evidence
  using the PA Agent reader's high-value behavior: cycle-position scope,
  direction/pattern ranking, recency, and bounded entry count.
- `workspace/` composes one product-level run workspace from the suite pack
  projections that were previously stitched together by the smoke command.
- `planning/` prepares pre-execution run plans from operator intent, MoonGate
  suite status, market adapter selection, closed-bar refresh readiness, and
  MoonClaw routine phases.
- `data/` keeps provider-specific adapters outside core while accepting
  externally submitted closed-bar snapshots through typed ingest contracts.
- `data/` also prepares refresh-readiness plans that preserve PA Agent's useful
  bar-close and slow-source throttling behavior without carrying over a hidden
  GUI refresh loop.
- `workflow/` can complete previously planned external runs once an accepted
  snapshot is submitted.
- `job/` prepares durable MoonClaw job states for ready, awaiting-data,
  completed, failed, and cancelled runs, including retry policy and partial
  record availability.
- `retry/` prepares validation retry decisions from stage validation reports,
  policy, and attempt count. Format issues can retry within budget; provider and
  safety failures do not retry.
- `review/` derives `ReviewQueue` records from analysis bundles without
  mutating workflow state.
- Missing external market snapshots become blocking review items.
- Validation errors become review items keyed to the failing contract path.
- Low-confidence Stage 2 decisions become operator-review items.
- `execution/` and `book/` persist the decision policy report under
  `records/policies/<run>.json` so replay, export, follow-up, and safety checks
  can cite the same evidence.
- `tools/` computes deterministic support, resistance, and midline levels from
  closed bars. `execution/` and `book/` persist those levels under
  `records/structure-levels/<run>.json`, and `chart/` surfaces them as operator
  annotations.
- `execution/` and `book/` also persist context-budget reports under
  `records/context-budgets/<run>.json`, giving replay, export, follow-up, app
  debug panels, and safety checks a shared model-window evidence anchor.
- `book/` prepares `BookCommitReport` records under
  `records/book-commits/<run>.json` so completed runs can prove each raw,
  generated, app, and import artifact is ready for idempotent MoonBook commit.
- `followup/` derives analysis-attached follow-up contexts and turn records from
  workflow bundles, review queues, and MoonBook artifact paths.
- `followup/` prepares bounded session plans that mirror PA Agent free-chat
  behavior while making the stable prompt prefix, citation paths, reasoning
  resend policy, and sidecar persistence explicit records.
- `followup/` prepares cited follow-up responses that keep operator questions
  attached to durable evidence and review state instead of hidden UI history.
- `replay/` derives replay plans from follow-up evidence anchors and marks
  whether a run can replay without live market data.
- `export/` derives internal audit and public-summary export manifests. Public
  summaries omit prompt packets and raw model exchanges.
- `safety/` derives explicit safety reports from the pack manifest,
  context-budget report, book commit report, decision policy report, replay
  plan, and public export manifest.

Exit criteria:

- Historical PA Agent records can be inspected in MoonBook.
- Imported records are traceable back to their source file and schema version.
- Replays can run without live market data.

## Phase 6: Build The Moondesk App-Tool Surface

Purpose: give operators a usable interface without putting price-action logic
inside Moondesk core.

Source inputs:

- `../paa/pa_agent/gui/main_window.py`
- `../paa/pa_agent/gui/chart_widget.py`
- `../paa/pa_agent/gui/decision_panel.py`
- `../paa/pa_agent/gui/decision_tree_panel.py`
- `../paa/pa_agent/gui/prompt_files_panel.py`
- `../paa/pa_agent/gui/debug_widget.py`
- `../paa/pa_agent/gui/conversation_widget.py`

Moondesk surface:

- data-source configuration
- symbol/timeframe selection
- chart and indicator inspection
- run button and cancellation
- routine event stream
- Stage 1 and Stage 2 JSON panes
- strategy routing view
- validation/retry debug pane
- prompt and raw-response inspection
- run history
- follow-up chat attached to a selected record
- follow-up session plan showing stable evidence anchors and sidecar storage
- export/replay actions

Work:

1. Implement the surface as a price-action app-tool pack.
2. Read and write through MoonBook and MoonClaw APIs.
3. Render charts using domain tool outputs.
4. Keep UI state separate from analysis state.
5. Ensure all sensitive provider settings come from suite configuration and are
   redacted in UI/debug views.

Deliverables:

- Moondesk app-tool manifest.
- Operator UI.
- Run-history and replay views.
- Debug panes for prompts, raw replies, validation, and events.

Current Moonfish implementation:

- `app/` derives `OperatorRunView` projections from workflow bundles.
- `app/` derives removable Moondesk app-tool manifests with controls, data
  bindings, panels, actions, required tools, and redacted debug bindings.
- `appsmoke/` prepares Moondesk app-tool smoke reports proving the removable
  mount, binding resolution, completed workflow, external snapshot ingest,
  redacted debug bindings, MoonBook-backed state, and required tool coverage.
- Data-source panels bind `market-refresh-plan` next to the market request and
  ingest contract, so operators can see whether the next step is run-now,
  wait-for-close, external snapshot, or timeframe review.
- Awaiting external-data runs expose a snapshot-ingest action bound to
  `market-ingest-input`, so the operator surface can complete the run without
  provider-specific code in Moondesk core.
- `history/` derives `RunHistoryIndex` projections for scanning completed,
  awaiting-data, review-blocked, replayable, and safety-flagged runs.
- Operator views expose chart availability, event count, book artifact count,
  review counts, follow-up topic count, replay status, export item count,
  panels, and enabled actions.
- External planned runs focus the operator on data-source configuration and
  review; completed runs expose chart, decision, events, prompts, follow-up,
  export, and replay actions.
- Follow-up panels bind both the session plan and response artifacts, so
  Moondesk can operate post-analysis chat without storing hidden trading state.

Exit criteria:

- Operators can run a full analysis from Moondesk.
- Domain behavior is removable by uninstalling the price-action pack.
- Moondesk core has no trading-specific imports or rules.

## Phase 7: Parity, Safety, And Evaluation

Purpose: prove the migrated system preserves critical behavior and improves
operability.

Source inputs:

- PA Agent test suite under `../paa/tests/`
- Golden PA Agent records
- Imported MoonBook records

Test groups:

- schema validation parity
- explicit policy parity
- routing determinism
- indicator and market-feature parity
- snapshot round trip
- stage retry policy
- no-order invariant
- record redaction
- event replay
- routine cancellation
- provider error normalization

Work:

1. Port deterministic Python tests first.
2. Add fixture-based MoonClaw routine tests.
3. Add MoonBook record round-trip tests.
4. Add Moondesk smoke tests around app-tool integration.
5. Compare old and new outputs on golden fixtures:
   - exact match where deterministic
   - semantically equivalent where model output varies
6. Add explicit safety checks:
   - no broker execution path
   - no plaintext API key in records
   - no UI-only hidden state required for analysis
   - no trading logic in Moondesk core

Current Moonfish implementation:

- `acceptance/` prepares fixture-driven product acceptance reports covering
  completed workspace execution, external data review, validation retry pause,
  cancellation report evidence with partial record preservation, app-tool
  contracts, Moondesk app-tool smoke, provider failure handling, record integrity, prompt-skill
  migration, import traceability, parity readiness, operator handoff readiness,
  decommission archive readiness, and safety/redaction.
- `parity/` prepares traced golden-fixture reports. Each parity case names the
  PA Agent fixture path, Moonfish evidence path, comparison expectation, concrete
  assertion, and any intentional known-difference note.
- `evaluation/` only treats parity as cutover-ready when every parity case is
  traced to both PA Agent source fixtures and Moonfish evidence, and only treats
  prompt migration as ready when every PA prompt source has an inspectable
  MoonBook skill, strategy-note, or concept target.
- `safety/` reports no broker/order execution tools in the suite manifest.
- `safety/` also fails a run whose decision policy report blocks order-shaped
  output.
- Public export redaction is verified by checking public-summary manifests omit
  prompt packets and raw model exchange artifacts.
- Replay safety is verified by requiring replay plans to use persisted evidence
  rather than live market data.
- Suite ownership is checked against MoonGate, MoonClaw, MoonBook, Moondesk, and
  PriceAction boundaries.

Deliverables:

- Migration parity test suite.
- Golden fixture report.
- Safety checklist.
- Known-difference report.

Exit criteria:

- Deterministic behavior matches PA Agent or has documented intentional
  differences.
- Model-dependent behavior is reproducible enough for review through records and
  event logs.
- Safety checks pass.

## Phase 8: Cutover And Decommission

Purpose: make the MoonSuite implementation the primary PA workflow while
preserving rollback and auditability.

Work:

1. Run both systems against the same golden fixtures.
2. Run both systems against a small set of live market snapshots, with records
   saved for comparison.
3. Freeze PA Agent feature development except for critical fixes.
4. Migrate user configuration into suite settings.
5. Migrate historical records and experience memory into MoonBook.
6. Switch operators to the Moondesk app-tool.
7. Keep PA Agent read-only for a defined rollback period.
8. Archive PA Agent migration notes and known differences.

Current Moonfish implementation:

- `comparison/` prepares phase 8 cutover comparison reports over traced golden
  parity evidence, an external closed-bar snapshot rehearsal, and read-only PA
  Agent rollback evidence.
- `evaluation/` requires the comparison report before cutover readiness can pass;
  fixture-only parity no longer proves readiness by itself.
- `cutover/` turns the readiness result into an operator checklist, rollback
  window, imported-data manifest path, and decommission note.
- `handoff/` consolidates acceptance, readiness, comparison, cutover, and
  Moondesk app-tool evidence into the operator launch path and runbook.
- `decommission/` prepares the PA Agent read-only decommission report, archive
  manifest, imported-record preservation evidence, rollback-window evidence, and
  final note.
- `product/` assembles the full workspace, settings, migration, skill migration,
  pack manifest, parity, comparison, acceptance, readiness, handoff, and
  decommission status into one suite-pack product report. Its product boundary
  now accepts prepared workspace, settings, legacy import, prompt-skill
  migration, comparison-run, and manifest evidence, so the standalone pack can
  be driven by real MoonSuite inputs without relying on a hidden smoke fixture.
- `product/` also prepares a Moondesk product launch manifest that binds the
  assembled product status to readiness, cutover, handoff, and decommission
  surfaces and suppresses unsafe launch/archive actions while gates are blocked.
- `product/` prepares a product rehearsal report that proves the daily cutover
  path across the launch surface, handoff workflow, replay/export evidence,
  golden/live comparisons, PA Agent read-only rollback, and archive readiness.
- `release/` prepares a release certificate that proves Moonfish is the
  standalone primary workflow, imported/historical records are replayable, the
  suite pack declares release contracts, export evidence is available, and PA
  Agent is only an archived read-only reference.
- `rollback/` prepares a rollback-window report that proves the defined
  read-only fallback period has monitor evidence, Moonfish primary workflow
  evidence, replay/export support, escalation paths, and archive retention.
- `operations/` prepares a day-2 operations readiness report that proves
  MoonGate suite health, Moonfish primary workflow, rollback monitoring,
  replay/export, resilience evidence, and Moondesk observability remain ready
  after cutover.
- `pack/` exposes the comparison input/report schemas and
  `prepare_cutover_comparison_report`, plus the handoff input/report schemas and
  `prepare_operator_handoff_report`, plus the decommission input/report schemas
  and `prepare_decommission_report`, plus the product status, product launch,
  product rehearsal, release certificate, rollback-window, and operations
  readiness schemas and tools, as suite-owned contracts.

Deliverables:

- Cutover checklist.
- Rollback plan.
- Imported data manifest.
- Final parity report.
- Decommission note for the Python app.

Exit criteria:

- Operators can complete the daily workflow in MoonSuite.
- Historical records are available for inspection and replay.
- The old app is no longer required for routine operation.

## Phase 9: Day-2 Operations

Purpose: keep the standalone Moonfish workflow operable after cutover without
sliding PA Agent back into the runtime path.

Work:

1. Continuously assemble product status, release certificate, and rollback
   window evidence into one operations report.
2. Prove suite health from MoonGate discovery, quota state, and integration
   contracts.
3. Prove the primary workflow still passes acceptance, readiness, handoff,
   release, and decommission gates.
4. Prove rollback monitoring remains configured during the fallback window.
5. Prove replay/export can run from persisted evidence without live market
   data.
6. Prove resilience from cancellation, provider failure, record integrity, and
   safety/redaction evidence.
7. Prove Moondesk observability from app-tool smoke, run history, event counts,
   redacted bindings, and run/replay/export surfaces.

Current Moonfish implementation:

- `operations/` prepares `OperationsReadinessReport` from product status,
  release certificate, and rollback-window report.
- `operations/` emits six explicit findings: suite health, primary workflow,
  rollback monitoring, replay/export, resilience evidence, and operator
  observability.
- `pack/` declares the operations input/finding/report schemas, the
  `records/operations` MoonBook path, and the
  `prepare_operations_readiness_report` tool contract.
- The root facade and `cmd/main` smoke path include the operations report after
  release and rollback.

Deliverables:

- Operations readiness report.
- Day-2 evidence path under `records/operations/<run>.json`.
- Moondesk surface hook for ongoing status and exportable evidence.

Exit criteria:

- Moonfish can prove it remains runnable, observable, replayable, and resilient
  after cutover without using PA Agent as an active runtime dependency.
- Any blocked day-2 gate points to the exact MoonBook or suite evidence path
  that must be repaired.

## Ownership Matrix

| PA Agent concern | MoonSuite owner | Migration note |
| --- | --- | --- |
| Provider settings and model client | MoonGate + MoonClaw | Discover model gateway from suite status. |
| Two-stage orchestration | MoonClaw | Implement as explicit routine/job phases. |
| Prompt files | MoonBook price-action skills | Keep as files with versioned skill metadata. |
| Stage schemas | MoonBook price-action schemas | Convert Python dictionaries to schema files. |
| JSON validation and retry | Domain tools + MoonClaw routine | Tools validate; routine decides retry. |
| Data adapters | Domain tools | Keep source-specific fetchers behind typed contracts. |
| Indicators and deterministic features | Domain tools | Fixture-test for parity. |
| Experience memory | MoonBook | Import by cycle position and strategy tag. |
| Analysis records | MoonBook | Persist raw evidence plus normalized projections. |
| PyQt operator UI | Moondesk app-tool | Rebuild as removable domain UI surface. |
| Free chat | MoonClaw + MoonBook | Prepare stable session plans, cite durable evidence, and attach follow-up turns to the analysis record. |
| Logs/debug panes | MoonBook + Moondesk | Store events and expose inspection views. |

## Implementation Order

The recommended build order is:

1. Schemas and record model.
2. Deterministic tools.
3. MoonGate model adapter.
4. MoonClaw two-stage routine.
5. MoonBook memory and record import.
6. Moondesk app-tool.
7. Parity harness.
8. Cutover scripts and documentation.
9. Day-2 operations monitoring.

This order keeps the riskiest model and UI work behind deterministic contracts,
so each phase can be tested before the next layer depends on it.

## Relationship To Current A-Share Product

The current Moonfish product has moved beyond the PA migration in these
directories:

- `moonpack/` declares the installable `Moonfish Systematic A-Share Research`
  pack.
- `suitepack/` validates the MoonPack manifest and authority classes.
- `ashare/` implements MoonBit systematic policy/math, factor scoring/ranking,
  pack-tool execution, MoonBook record persistence, app-service contracts, and
  MF3 evidence adapters/exporters.
- `cmd/moonfish_tool` is the verified native pack command.
- `cmd/moonfish_service` is the native Finance app service that submits the
  installed workflow to MoonClaw and stores request/result records in MoonBook.
- `moonpack/apps/daily` is the pack-owned operator UI mounted generically by
  Moondesk as `finance.moonfish`.

The PA migration packages should remain concise and green as reference
infrastructure. The next productization work belongs in licensed provider
acquisition, model-backed governed phases, and generic pack-service lifecycle
integration. Reintroducing a Python localhost runtime is not part of the plan.
