@llm-dev-ops/agentics-cli 2.7.37 → 2.7.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/adapters/base-adapter.d.ts.map +1 -1
  2. package/dist/adapters/base-adapter.js.map +1 -1
  3. package/dist/agents/repo-agent-runner.d.ts.map +1 -1
  4. package/dist/agents/repo-agent-runner.js +0 -2
  5. package/dist/agents/repo-agent-runner.js.map +1 -1
  6. package/dist/agents/system-prompts.d.ts.map +1 -1
  7. package/dist/agents/system-prompts.js +0 -19
  8. package/dist/agents/system-prompts.js.map +1 -1
  9. package/dist/commands/agents.d.ts +4 -24
  10. package/dist/commands/agents.d.ts.map +1 -1
  11. package/dist/commands/agents.js +6 -36
  12. package/dist/commands/agents.js.map +1 -1
  13. package/dist/pipeline/auto-chain.d.ts.map +1 -1
  14. package/dist/pipeline/auto-chain.js +82 -6
  15. package/dist/pipeline/auto-chain.js.map +1 -1
  16. package/dist/pipeline/exemplars.d.ts +34 -0
  17. package/dist/pipeline/exemplars.d.ts.map +1 -0
  18. package/dist/pipeline/exemplars.js +101 -0
  19. package/dist/pipeline/exemplars.js.map +1 -0
  20. package/dist/pipeline/output-validator.d.ts +38 -0
  21. package/dist/pipeline/output-validator.d.ts.map +1 -0
  22. package/dist/pipeline/output-validator.js +152 -0
  23. package/dist/pipeline/output-validator.js.map +1 -0
  24. package/dist/pipeline/phase2/phases/adr-generator.d.ts.map +1 -1
  25. package/dist/pipeline/phase2/phases/adr-generator.js +21 -3
  26. package/dist/pipeline/phase2/phases/adr-generator.js.map +1 -1
  27. package/dist/pipeline/phase4-adrs/phase4-adrs-coordinator.d.ts.map +1 -1
  28. package/dist/pipeline/phase4-adrs/phase4-adrs-coordinator.js +17 -5
  29. package/dist/pipeline/phase4-adrs/phase4-adrs-coordinator.js.map +1 -1
  30. package/dist/pipeline/phase7/deliverables-registry.js +1 -1
  31. package/dist/pipeline/phase7/deliverables-registry.js.map +1 -1
  32. package/dist/pipeline/ruflo-phase-executor.d.ts +2 -5
  33. package/dist/pipeline/ruflo-phase-executor.d.ts.map +1 -1
  34. package/dist/pipeline/ruflo-phase-executor.js +55 -66
  35. package/dist/pipeline/ruflo-phase-executor.js.map +1 -1
  36. package/dist/routing/domain-boundary.d.ts +4 -20
  37. package/dist/routing/domain-boundary.d.ts.map +1 -1
  38. package/dist/routing/domain-boundary.js +6 -81
  39. package/dist/routing/domain-boundary.js.map +1 -1
  40. package/dist/routing/graph-router.d.ts.map +1 -1
  41. package/dist/routing/graph-router.js +0 -22
  42. package/dist/routing/graph-router.js.map +1 -1
  43. package/docs/ecosystem.graph.json +15 -65
  44. package/docs/templates/ADR-Good-Example.md +787 -0
  45. package/docs/templates/Implementation-Prompts-Good-Example.md +1158 -0
  46. package/docs/templates/promotion-changelog.md +94 -0
  47. package/docs/templates/regression-changelog.md +86 -0
  48. package/docs/templates/sparc-specification-good-example.md +600 -0
  49. package/package.json +2 -1
  50. package/dist/config/qe-gating.d.ts +0 -81
  51. package/dist/config/qe-gating.d.ts.map +0 -1
  52. package/dist/config/qe-gating.js +0 -138
  53. package/dist/config/qe-gating.js.map +0 -1
  54. package/dist/pipeline/phase5-build/qe-gating-executor.d.ts +0 -73
  55. package/dist/pipeline/phase5-build/qe-gating-executor.d.ts.map +0 -1
  56. package/dist/pipeline/phase5-build/qe-gating-executor.js +0 -134
  57. package/dist/pipeline/phase5-build/qe-gating-executor.js.map +0 -1
@@ -0,0 +1,1158 @@
1
+ # Protein-Engine Implementation Prompts
2
+
3
+ Sequential, copy-paste-ready prompts for building the platform. Each prompt references the specific ADRs and DDDs it depends on. Execute in order — each prompt's outputs are inputs to subsequent prompts.
4
+
5
+ ---
6
+
7
+ ## Prompt 01: Workspace Scaffold and Cargo Configuration
8
+
9
+ ```
10
+ Set up the Rust workspace for Protein-Engine. Create the directory structure exactly as defined in the SPARC specification (plans/sparc-specification.md, "Repository Structure" section).
11
+
12
+ Create:
13
+ 1. Root Cargo.toml with all 14 workspace members and all workspace dependencies exactly as specified in plans/research.md ("Workspace Cargo.toml" section). Include every dependency with its exact version, git URL, and feature flags.
14
+ 2. .cargo/config.toml with target-specific rustflags for wasm32-unknown-unknown, x86_64-unknown-linux-musl, and aarch64-unknown-linux-gnu as specified in the research doc.
15
+ 3. A minimal Cargo.toml for each of the 14 crates under crates/ — each should have:
16
+ - workspace package inheritance (version, edition, license, authors, repository, description)
17
+ - the correct subset of workspace dependencies for that crate
18
+ - feature flags following ADR-003 (plans/adr-003-feature-flag-native-vs-wasm.md): native vs wasm mutual exclusivity
19
+ - dev-dependencies: mockall (workspace) per ADR-002
20
+ - pe-core must have NO feature flags and NO std dependency (ADR-009)
21
+ 4. A placeholder lib.rs for each crate that compiles (just `//! Crate description` comment)
22
+ 5. Stub directories for services/chemiq-sidecar/, services/instrument-bridge/, web/, docker/ as shown in the repo structure
23
+
24
+ Verify: `cargo check --workspace` succeeds. `cargo check --target wasm32-unknown-unknown -p pe-core` succeeds (no_std validation).
25
+
26
+ Reference: plans/research.md (full Cargo.toml), ADR-003, ADR-009
27
+ ```
28
+
29
+ ---
30
+
31
+ ## Prompt 02: pe-core Domain Types
32
+
33
+ ```
34
+ Implement the pe-core crate with all domain types defined in DDD-001 (plans/ddd-001-protein-engineering-domain-model.md, "Variant Design Context" and "Fitness Evaluation Context") and DDD-003 (plans/ddd-003-aggregate-specifications.md, Aggregates 1, 2, and 6).
35
+
36
+ The crate MUST be #![no_std] with extern crate alloc per ADR-009 (plans/adr-009-nostd-core-domain-types.md). Use BTreeMap not HashMap. Import from alloc, not std.
37
+
38
+ Implement these types with all invariants from DDD-003:
39
+
40
+ 1. AminoAcid — enum of 20 standard residues (A,C,D,E,F,G,H,I,K,L,M,N,P,Q,R,S,T,V,W,Y) with from_char/to_char conversions
41
+ 2. AminoAcidSequence — validated, immutable sequence wrapper. Constructor rejects empty sequences and invalid residue chars. Implements Deref<Target=[AminoAcid]> for easy access.
42
+ 3. YamanakaFactor — enum: OCT4, SOX2, KLF4, CMYC
43
+ 4. Mutation — value object with position, from_residue, to_residue. Constructor enforces from != to (invariant PV-7).
44
+ 5. ProteinVariant — aggregate root with id (Uuid), name, sequence, target_factor, mutations, generation, parent_id. Factory methods:
45
+ - wild_type(name, sequence, target_factor) — generation 0, no parent (PV-3)
46
+ - from_mutation(parent, mutation) — validates PV-5, PV-6, increments generation (PV-4)
47
+ - from_crossover(parent_a, parent_b, crossover_point) — validates same length, combines sequences
48
+ 6. FitnessScore — value object with reprogramming_efficiency, expression_stability, structural_plausibility, safety_score, composite. Constructor clamps to [0.0, 1.0] and computes weighted composite (invariants FS-1 through FS-4). Include FitnessWeights.
49
+ 7. AssayType — enum: FlowCytometry, WesternBlot, QPCR, PlateReader, CellViability, Custom(String)
50
+ 8. ExperimentResult — entity with variant_id, assay_type, measured_values (BTreeMap<String, f64>), timestamp, instrument_id, notes. Constructor enforces ER-1 through ER-4.
51
+ 9. ScoredVariant — tuple struct (ProteinVariant, FitnessScore)
52
+ 10. Embedding320 — newtype wrapper around [f32; 320] with basic operations (cosine_similarity, etc.)
53
+
54
+ Write London School TDD unit tests for every invariant listed in DDD-003. No mocks needed — pe-core is the leaf node. Test every factory method, every validation rule, every rejection case.
55
+
56
+ All types must derive Serialize, Deserialize, Clone, Debug. PartialEq where specified in DDD-003.
57
+
58
+ Verify: `cargo test -p pe-core` passes. `cargo check --target wasm32-unknown-unknown -p pe-core` compiles.
59
+
60
+ Reference: ADR-009, DDD-001, DDD-003 (Aggregates 1, 2, 6)
61
+ ```
62
+
63
+ ---
64
+
65
+ ## Prompt 03: pe-rvf Segment Types and RVF Builder
66
+
67
+ ```
68
+ Implement the pe-rvf crate with the RVF builder and segment definitions defined in ADR-001 (plans/adr-001-rvf-universal-deployment-artifact.md) and DDD-003 (plans/ddd-003-aggregate-specifications.md, Aggregate 4: RvfFile).
69
+
70
+ Implement:
71
+
72
+ 1. SegmentType — enum with discriminants for all 15 segments (MANIFEST_SEG 0x00 through KERNEL_SEG 0x0E) as listed in ADR-001's segment allocation table.
73
+ 2. Capability — enum: VecSearch, ProteinScoring, Evolution, WasmRuntime, QuantumVqe, P2pSync, McpAgent, TeeAttestation
74
+ 3. Manifest — struct with name, version, capabilities, parent_hash, signing_key_fingerprint, created_at. Validation per RF-7.
75
+ 4. SegmentProducer trait (from ADR-004, plans/adr-004-trait-boundary-dependency-injection.md):
76
+ ```rust
77
+ pub trait SegmentProducer: Send + Sync {
78
+ fn segment_type(&self) -> SegmentType;
79
+ fn produce(&self) -> Result<Vec<u8>>;
80
+ }
81
+ ```
82
+ 5. RvfBuilder trait and concrete implementation:
83
+ ```rust
84
+ pub trait RvfAssembler: Send + Sync {
85
+ fn set_manifest(&mut self, manifest: Manifest);
86
+ fn add_segment(&mut self, seg_type: SegmentType, data: Vec<u8>) -> Result<()>;
87
+ fn build(self) -> Result<RvfFile>;
88
+ }
89
+ ```
90
+ 6. RvfFile — struct holding manifest + BTreeMap<SegmentType, Vec<u8>> + file_hash. Enforce invariants RF-1 through RF-6 from DDD-003.
91
+ 7. Serialization: RvfFile can serialize to bytes and deserialize back. Use a simple binary format: manifest length (u32) + manifest bytes + for each segment: type (u8) + length (u32) + data bytes. Compute file_hash as SHA3-256 of the complete output.
92
+ 8. Auto-capability inference: build() must scan present segments and populate capabilities (RF-2 through RF-4). If VEC_SEG present → VecSearch capability. If WASM_SEG → WasmRuntime. Etc.
93
+
94
+ Write London School TDD tests using mockall. Mock SegmentProducer to return fixture bytes. Test every invariant from DDD-003 Aggregate 4:
95
+ - build with all segments produces valid RvfFile
96
+ - build fails without MANIFEST_SEG (RF-1)
97
+ - capabilities auto-populated from present segments (RF-2, RF-3, RF-4)
98
+ - segments ordered by type ID in output (RF-5)
99
+ - parent_hash links child to parent
100
+ - file_hash is deterministic for same inputs (RF-6)
101
+ - round-trip serialize/deserialize preserves all segments
102
+
103
+ Verify: `cargo test -p pe-rvf` passes.
104
+
105
+ Reference: ADR-001, ADR-004, DDD-003 (Aggregate 4)
106
+ ```
107
+
108
+ ---
109
+
110
+ ## Prompt 04: pe-vector Embedding Store and Traits
111
+
112
+ ```
113
+ Implement the pe-vector crate with vector storage, embedding traits, and HNSW search as specified in DDD-001 (plans/ddd-001-protein-engineering-domain-model.md, "Fitness Evaluation Context") and DDD-002 (plans/ddd-002-bounded-context-integration-patterns.md, section 1).
114
+
115
+ This crate depends on pe-core (for domain types) and integrates with RuVector for the actual vector database.
116
+
117
+ Implement:
118
+
119
+ 1. EmbeddingModel trait (from ADR-004):
120
+ ```rust
121
+ #[cfg_attr(test, automock)]
122
+ pub trait EmbeddingModel: Send + Sync {
123
+ fn embed(&self, sequence: &AminoAcidSequence) -> Result<Embedding320>;
124
+ }
125
+ ```
126
+
127
+ 2. VariantMeta — filterable metadata stored alongside each embedding:
128
+ - variant_id, target_factor, generation, composite_score, design_method
129
+
130
+ 3. VectorStore trait (from ADR-004):
131
+ ```rust
132
+ #[cfg_attr(test, automock)]
133
+ pub trait VectorStore: Send + Sync {
134
+ fn insert(&mut self, id: Uuid, embedding: Embedding320, meta: VariantMeta) -> Result<()>;
135
+ fn search_nearest(&self, query: &Embedding320, k: usize) -> Result<Vec<(Uuid, f32)>>;
136
+ fn get_meta(&self, id: Uuid) -> Result<Option<VariantMeta>>;
137
+ fn count(&self) -> usize;
138
+ }
139
+ ```
140
+
141
+ 4. InMemoryVectorStore — a pure-Rust in-memory implementation of VectorStore using brute-force cosine similarity. This serves as:
142
+ - The WASM-target implementation (no RuVector dependency)
143
+ - The reference implementation for testing
144
+ - Serializable to/from VEC_SEG + INDEX_SEG byte formats (implement SegmentProducer from pe-rvf)
145
+
146
+ 5. RuVectorStore (behind `native` feature flag) — wraps ruvector::Database, implements VectorStore trait. HNSW config: M=16, ef_construction=200, metric=Cosine per the research doc.
147
+
148
+ 6. GraphStore trait — for GNN protein interaction network (GRAPH_SEG):
149
+ ```rust
150
+ pub trait GraphStore: Send + Sync {
151
+ fn add_edge(&mut self, from: Uuid, to: Uuid, weight: f32) -> Result<()>;
152
+ fn neighbors(&self, id: Uuid) -> Result<Vec<(Uuid, f32)>>;
153
+ }
154
+ ```
155
+
156
+ Write London School TDD tests. Mock EmbeddingModel (returns fixed 320-dim vectors). Test VectorStore with real InMemoryVectorStore:
157
+ - insert variant embedding and retrieve by ID
158
+ - search_nearest returns k closest by cosine similarity (insert 100 known vectors, verify ordering)
159
+ - search returns empty vec for empty store
160
+ - get_meta returns None for unknown ID
161
+ - count reflects number of inserted embeddings
162
+ - VEC_SEG + INDEX_SEG round-trip: serialize → deserialize → same search results
163
+
164
+ Verify: `cargo test -p pe-vector` passes. `cargo check --target wasm32-unknown-unknown -p pe-vector --no-default-features --features wasm` compiles.
165
+
166
+ Reference: ADR-003, ADR-004, DDD-001 (Fitness Evaluation Context), DDD-002 (Integration 1)
167
+ ```
168
+
169
+ ---
170
+
171
+ ## Prompt 05: pe-neural Fitness Scoring Ensemble
172
+
173
+ ```
174
+ Implement the pe-neural crate with the fitness prediction ensemble as specified in DDD-001 (plans/ddd-001-protein-engineering-domain-model.md, "Fitness Evaluation Context") and the SPARC pseudocode (plans/sparc-specification.md, Phase 3).
175
+
176
+ This crate depends on pe-core (domain types) and pe-vector (EmbeddingModel trait).
177
+
178
+ Implement:
179
+
180
+ 1. SubModelScorer trait (from ADR-004):
181
+ ```rust
182
+ #[cfg_attr(test, automock)]
183
+ pub trait SubModelScorer: Send + Sync {
184
+ fn score(&self, variant: &ProteinVariant, embedding: &Embedding320) -> Result<f64>;
185
+ fn model_name(&self) -> &str;
186
+ }
187
+ ```
188
+
189
+ 2. FitnessPredictor trait (from ADR-004):
190
+ ```rust
191
+ #[cfg_attr(test, automock)]
192
+ pub trait FitnessPredictor: Send + Sync {
193
+ fn predict(&self, variant: &ProteinVariant, embedding: &Embedding320) -> Result<FitnessScore>;
194
+ }
195
+ ```
196
+
197
+ 3. EnsemblePredictor<T, L, N> — generic over three SubModelScorers (Transformer, LSTM, N-BEATS). Implements FitnessPredictor. Takes FitnessWeights to compute the composite score.
198
+
199
+ 4. Stub scorer implementations (real model loading comes later):
200
+ - TransformerScorer — placeholder that scores based on sequence composition heuristics (e.g., hydrophobicity distribution). Must implement SubModelScorer.
201
+ - LstmScorer — placeholder scoring based on sequence length and mutation count.
202
+ - NBeatsScorer — placeholder returning a configurable baseline score.
203
+
204
+ 5. ModelLoader trait — for loading weights from QUANT_SEG bytes:
205
+ ```rust
206
+ pub trait ModelLoader: Send + Sync {
207
+ fn load_from_bytes(data: &[u8]) -> Result<Self> where Self: Sized;
208
+ }
209
+ ```
210
+
211
+ 6. Implement SegmentProducer (from pe-rvf) for QUANT_SEG — serializes model weights.
212
+
213
+ Write London School TDD tests. Mock all three SubModelScorers:
214
+ - EnsemblePredictor aggregates three sub-model scores with correct weights
215
+ - predict returns error when any sub-model fails (one mock returns Err)
216
+ - composite score is correctly weighted (mock transformer=0.8, lstm=0.7, nbeats=0.9, verify exact composite)
217
+ - safety_score inversion in composite calculation
218
+ - EnsemblePredictor with all mocks returning 0.5 produces composite = 0.5
219
+ - model_name() returns correct identifier for each scorer
220
+
221
+ Verify: `cargo test -p pe-neural` passes.
222
+
223
+ Reference: ADR-002, ADR-004, DDD-001 (Fitness Evaluation), SPARC Phase 3
224
+ ```
225
+
226
+ ---
227
+
228
+ ## Prompt 06: pe-solver Sparse Energy Minimization
229
+
230
+ ```
231
+ Implement the pe-solver crate with sparse energy minimization backed by the sublinear-time-solver.
232
+
233
+ This crate depends on pe-core (domain types).
234
+
235
+ Implement:
236
+
237
+ 1. EnergySolver trait:
238
+ ```rust
239
+ #[cfg_attr(test, automock)]
240
+ pub trait EnergySolver: Send + Sync {
241
+ fn minimize(&self, energy_landscape: &EnergyLandscape) -> Result<MinimizationResult>;
242
+ }
243
+ ```
244
+
245
+ 2. EnergyLandscape — represents a sparse energy surface over protein conformational space:
246
+ - dimensions: usize
247
+ - sparse_entries: Vec<(Vec<usize>, f64)> — (coordinate indices, energy value)
248
+
249
+ 3. MinimizationResult — the solver output:
250
+ - minimum_energy: f64
251
+ - optimal_coordinates: Vec<f64>
252
+ - iterations: usize
253
+ - converged: bool
254
+
255
+ 4. SublinearSolver — wraps pe-sublinear (sublinear-time-solver crate). Implements EnergySolver.
256
+
257
+ 5. SimpleGradientSolver — a pure-Rust fallback for WASM targets. Implements EnergySolver.
258
+
259
+ 6. Implement SegmentProducer for storing solver results in JOURNAL_SEG format.
260
+
261
+ Write London School TDD tests:
262
+ - minimize returns convergence on a known convex energy surface
263
+ - minimize handles empty landscape gracefully
264
+ - result contains correct iteration count
265
+ - round-trip serialization of MinimizationResult
266
+
267
+ Verify: `cargo test -p pe-solver` passes.
268
+
269
+ Reference: SPARC Phase 3, DDD-001 (Fitness Evaluation Context)
270
+ ```
271
+
272
+ ---
273
+
274
+ ## Prompt 07: pe-quantum-wasm Local Quantum Simulator
275
+
276
+ ```
277
+ Implement the pe-quantum-wasm crate — the pure-Rust statevector quantum simulator that runs on ALL targets including WASM, as specified in ADR-006 (plans/adr-006-quantum-backend-routing.md).
278
+
279
+ This crate has NO feature flags. It must compile everywhere: native, wasm32, aarch64, no_std+alloc.
280
+
281
+ Implement:
282
+
283
+ 1. Statevector simulator:
284
+ - Qubit — representation of a quantum bit
285
+ - StateVector — 2^n complex amplitude vector (use num-complex)
286
+ - Gate operations: H (Hadamard), X, Y, Z, CNOT, RX, RY, RZ, CZ
287
+ - Measurement: collapse statevector, return classical bit string with probabilities
288
+
289
+ 2. Circuit representation:
290
+ - QuantumCircuit — ordered list of gate applications
291
+ - CircuitBuilder — fluent API for constructing circuits
292
+
293
+ 3. VQE implementation:
294
+ - MolecularHamiltonian — from pe-core or defined here, matrix of Pauli terms
295
+ - VqeRunner — classical optimizer loop (gradient-free: COBYLA or Nelder-Mead) that minimizes <psi|H|psi> by varying circuit parameters
296
+ - VqeResult — ground state energy, optimal parameters, convergence flag, iteration count
297
+
298
+ 4. QAOA implementation:
299
+ - QuboInstance — symmetric matrix encoding the optimization problem
300
+ - QaoaRunner — p-layer QAOA with parameter optimization
301
+ - QaoaResult — best solution bitstring, cost, iterations
302
+
303
+ 5. BackendCapabilities for the local simulator: max_qubits = 20 (practical limit for statevector), is_simulator = true
304
+
305
+ Write unit tests (no mocks — this is a leaf crate):
306
+ - H gate on |0⟩ produces equal superposition
307
+ - X gate flips |0⟩ to |1⟩
308
+ - CNOT entangles two qubits correctly
309
+ - VQE on H2 molecule (2-qubit, known ground state ≈ -1.137 Ha) converges within tolerance
310
+ - QAOA on a trivial 2-variable QUBO finds the optimal solution
311
+ - Measurement probabilities match theoretical predictions (statistical test)
312
+ - Simulator rejects circuits requiring > 20 qubits
313
+
314
+ Verify: `cargo test -p pe-quantum-wasm` passes. `cargo check --target wasm32-unknown-unknown -p pe-quantum-wasm` compiles.
315
+
316
+ Reference: ADR-006, DDD-001 (Quantum Simulation Context), DDD-003 (Aggregate 5: QuantumJob)
317
+ ```
318
+
319
+ ---
320
+
321
+ ## Prompt 08: pe-quantum Backend Router
322
+
323
+ ```
324
+ Implement the pe-quantum crate — the hardware-agnostic quantum router as specified in ADR-006 (plans/adr-006-quantum-backend-routing.md) and DDD-001 (plans/ddd-001-protein-engineering-domain-model.md, "Quantum Simulation Context").
325
+
326
+ This crate is native-only (feature = "native"). It depends on pe-core, pe-quantum-wasm, and pe-rvf.
327
+
328
+ Implement:
329
+
330
+ 1. QuantumBackend trait (from ADR-004/ADR-006):
331
+ ```rust
332
+ #[async_trait]
333
+ #[cfg_attr(test, automock)]
334
+ pub trait QuantumBackend: Send + Sync {
335
+ async fn submit_vqe(&self, hamiltonian: MolecularHamiltonian) -> Result<VqeResult>;
336
+ async fn submit_qaoa(&self, qubo: QuboInstance) -> Result<QaoaResult>;
337
+ fn capabilities(&self) -> BackendCapabilities;
338
+ }
339
+ ```
340
+
341
+ 2. BackendCapabilities — max_qubits, gate_set (HashSet<GateType>), is_simulator, provider (ProviderName enum)
342
+
343
+ 3. QuantumRouter — holds Vec<Box<dyn QuantumBackend>>. Routing logic per ADR-006:
344
+ - Filter by qubit count >= job requirement
345
+ - Filter by gate set superset
346
+ - Filter by reachability (health check)
347
+ - Sort by closest qubit count match
348
+ - Fallback to LocalSimulator (pe-quantum-wasm)
349
+ - Return Err(NoSuitableBackend) if nothing qualifies
350
+
351
+ 4. LocalSimulatorBackend — wraps pe-quantum-wasm's VqeRunner/QaoaRunner, implements QuantumBackend
352
+
353
+ 5. QuantumJob entity (DDD-003, Aggregate 5):
354
+ - State machine: Created → Submitted → Running → Completed | Failed
355
+ - Enforce all invariants QJ-1 through QJ-5
356
+
357
+ 6. VQE result caching: implement SegmentProducer for SKETCH_SEG (VQE snapshots)
358
+
359
+ Write London School TDD tests. Mock QuantumBackend for each provider:
360
+ - router selects best backend for VQE by qubit count (mock_origin=72, mock_ibm=127, mock_local=20; job=50 qubits → origin selected)
361
+ - router falls back to local WASM simulator when all remotes fail
362
+ - router returns NoSuitableBackend when job exceeds all backends
363
+ - job state machine: full lifecycle test
364
+ - job rejects invalid transitions (cannot complete without submit)
365
+ - VQE snapshots round-trip through SKETCH_SEG
366
+
367
+ Verify: `cargo test -p pe-quantum` passes.
368
+
369
+ Reference: ADR-006, ADR-004, DDD-001 (Quantum Simulation), DDD-003 (Aggregate 5)
370
+ ```
371
+
372
+ ---
373
+
374
+ ## Prompt 09: pe-chemistry pyChemiQ HTTP Bridge
375
+
376
+ ```
377
+ Implement the pe-chemistry crate — the HTTP bridge to the pyChemiQ Python sidecar as specified in ADR-008 (plans/adr-008-python-sidecar-quantum-chemistry.md).
378
+
379
+ This crate is native-only. It depends on pe-core, pe-quantum (for QuantumBackend trait), and reqwest.
380
+
381
+ Implement:
382
+
383
+ 1. ChemiqBridge struct:
384
+ - base_url: String (e.g., "http://chemiq-sidecar:8100")
385
+ - client: reqwest::Client
386
+ - timeout: Duration (configurable, default 30s)
387
+
388
+ 2. Implement QuantumBackend for ChemiqBridge:
389
+ - submit_vqe: POST /vqe with JSON body {molecule, basis_set, ansatz, max_iterations}. Translate domain MolecularHamiltonian → sidecar JSON. Translate response → VqeResult.
390
+ - submit_qaoa: POST /qaoa with JSON body {qubo_matrix, p_layers}. Translate QuboInstance → JSON. Translate response → QaoaResult.
391
+ - capabilities: GET /capabilities → BackendCapabilities
392
+
393
+ 3. Health checking: GET /health → sidecar status. Cache result for 30s.
394
+
395
+ 4. Anti-corruption layer (DDD-001): ChemiqBridge translates between domain types and the sidecar's Python-centric JSON format. Domain types never leak sidecar-specific fields. Sidecar errors are mapped to domain error types.
396
+
397
+ 5. Request/response DTOs (internal, not public): ChemiqVqeRequest, ChemiqVqeResponse, ChemiqQaoaRequest, ChemiqQaoaResponse — serde(rename_all = "snake_case")
398
+
399
+ 6. Also create the Python sidecar stub: services/chemiq-sidecar/main.py with FastAPI endpoints matching the API surface in ADR-008. Include services/chemiq-sidecar/requirements.txt (pychemiq, pyqpanda3, fastapi, uvicorn) and services/chemiq-sidecar/Dockerfile.
400
+
401
+ Write London School TDD tests. Mock HTTP responses (use mockall on a trait wrapping reqwest, or use a test HTTP server):
402
+ - submit_vqe translates domain Hamiltonian to correct JSON and parses response
403
+ - submit_qaoa translates domain QUBO to correct JSON and parses response
404
+ - capabilities returns correct BackendCapabilities from sidecar response
405
+ - timeout error is mapped to domain error
406
+ - malformed JSON response returns parse error, not panic
407
+ - health check caches result for 30s
408
+
409
+ Verify: `cargo test -p pe-chemistry` passes.
410
+
411
+ Reference: ADR-008, ADR-006, DDD-001 (Quantum Simulation, Anti-Corruption Layer)
412
+ ```
413
+
414
+ ---
415
+
416
+ ## Prompt 10: pe-ledger Cryptographic Journal and Witness Chain
417
+
418
+ ```
419
+ Implement the pe-ledger crate with the append-only journal, hash chaining, and ML-DSA signing as specified in ADR-005 (plans/adr-005-post-quantum-cryptography.md), ADR-010 (plans/adr-010-append-only-journal-cryptographic-chaining.md), and DDD-003 (plans/ddd-003-aggregate-specifications.md, Aggregate 3: JournalChain).
420
+
421
+ This crate depends on pe-core, pe-rvf, pqcrypto-mldsa, pqcrypto-mlkem, and sha3.
422
+
423
+ Implement:
424
+
425
+ 1. CryptoSigner trait (from ADR-004/ADR-005):
426
+ ```rust
427
+ #[cfg_attr(test, automock)]
428
+ pub trait CryptoSigner: Send + Sync {
429
+ fn sign(&self, data: &[u8]) -> Result<MlDsaSignature>;
430
+ fn verify(&self, data: &[u8], sig: &MlDsaSignature) -> Result<bool>;
431
+ }
432
+ ```
433
+
434
+ 2. MlDsaSigner — real implementation using pqcrypto-mldsa (native only). Holds signing key.
435
+
436
+ 3. MlDsaSignature — newtype wrapper around the signature bytes.
437
+
438
+ 4. EntryHash — newtype around [u8; 32] (SHA3-256).
439
+
440
+ 5. EntryType — enum of all 9 auditable event types from ADR-010: VariantDesigned, FitnessScored, StructureValidated, SafetyScreened, ExperimentRecorded, ModelUpdated, VqeCompleted, CycleCompleted, AgentRetired.
441
+
442
+ 6. JournalEntry — struct with sequence_number, timestamp, prev_hash, entry_type, payload, signature. Enforce all invariants from DDD-003.
443
+
444
+ 7. JournalChain — aggregate root (DDD-003, Aggregate 3):
445
+ - new() → empty chain, tip_hash = [0u8; 32]
446
+ - append_entry(entry_type, payload, signer) → Result<EntryHash>
447
+ Enforces JC-1 through JC-5. Computes SHA3, signs, chains.
448
+ - verify_chain() → Result<bool>
449
+ Traverses all entries checking hash chain (JC-2) + signatures (JC-4). Returns Err(TamperDetected{index}) on failure.
450
+ - len() → number of entries
451
+ - tip_hash() → current chain tip
452
+
453
+ 8. LedgerWriter trait (from ADR-004):
454
+ ```rust
455
+ #[cfg_attr(test, automock)]
456
+ pub trait LedgerWriter: Send + Sync {
457
+ fn append_entry(&mut self, entry_type: EntryType, payload: Vec<u8>) -> Result<EntryHash>;
458
+ fn verify_chain(&self) -> Result<bool>;
459
+ fn len(&self) -> usize;
460
+ }
461
+ ```
462
+
463
+ 9. SegmentProducer implementations:
464
+ - JOURNAL_SEG: serialize JournalChain entries
465
+ - WITNESS_SEG: serialize in QuDAG-compatible witness format
466
+
467
+ Write London School TDD tests. Mock CryptoSigner (returns deterministic 64-byte signature, verify always returns true):
468
+ - append to empty chain sets prev_hash to zeros (JC-3)
469
+ - append chains hashes correctly across 3 entries (JC-2)
470
+ - verify_chain succeeds on valid chain (JC-6)
471
+ - verify_chain detects tampered payload
472
+ - verify_chain detects tampered prev_hash
473
+ - verify_chain detects invalid signature (mock verify returns false)
474
+ - sequence_numbers are strictly sequential (JC-1)
475
+ - round-trip through JOURNAL_SEG preserves all entries
476
+ - WITNESS_SEG serialization produces parseable output
477
+
478
+ Also write one integration test with real MlDsaSigner (pqcrypto-mldsa): append 3 entries, verify chain with real crypto.
479
+
480
+ Verify: `cargo test -p pe-ledger` passes.
481
+
482
+ Reference: ADR-005, ADR-010, ADR-004, DDD-003 (Aggregate 3), DDD-001 (Trust & Audit Context)
483
+ ```
484
+
485
+ ---
486
+
487
+ ## Prompt 11: pe-governance Lifecycle Management
488
+
489
+ ```
490
+ Implement the pe-governance crate with autonomous agent lifecycle management backed by the daa framework, as specified in ADR-007 (plans/adr-007-safla-closed-loop-orchestration.md) and DDD-001 (plans/ddd-001-protein-engineering-domain-model.md, "Trust & Audit Context").
491
+
492
+ This crate depends on pe-core and daa.
493
+
494
+ Implement:
495
+
496
+ 1. AgentMetrics — performance stats for a swarm agent:
497
+ - agent_id: Uuid
498
+ - role: AgentRole (enum matching the 6 roles from ADR-007)
499
+ - cycles_completed: u64
500
+ - avg_quality_score: f64 (average fitness of variants this agent contributed to)
501
+ - avg_latency_ms: f64
502
+ - error_count: u64
503
+
504
+ 2. BudgetAllocation — compute budget assigned per agent per cycle:
505
+ - allocations: BTreeMap<Uuid, BudgetEntry>
506
+ - BudgetEntry: max_compute_ms, max_variants, priority_weight
507
+
508
+ 3. LifecycleManager trait (from ADR-004):
509
+ ```rust
510
+ #[cfg_attr(test, automock)]
511
+ pub trait LifecycleManager: Send + Sync {
512
+ fn should_retire(&self, agent: &AgentMetrics) -> bool;
513
+ fn allocate_budget(&self, agents: &[AgentMetrics], cycle_config: &CycleConfig) -> BudgetAllocation;
514
+ fn adjust_priorities(&mut self, cycle_result: &CycleResult);
515
+ }
516
+ ```
517
+
518
+ 4. DaaLifecycleManager — concrete implementation using daa framework:
519
+ - Retirement rule: retire if avg_quality_score < threshold AND cycles_completed > min_cycles
520
+ - Budget allocation: proportional to avg_quality_score * priority_weight
521
+ - Priority adjustment: increase exploration budget for under-represented Yamanaka factors
522
+
523
+ Write London School TDD tests (no mocks needed — leaf-like crate):
524
+ - should_retire returns true for low-quality agent past minimum cycles
525
+ - should_retire returns false for new agent (below min_cycles)
526
+ - should_retire returns false for high-quality agent
527
+ - allocate_budget distributes proportionally to quality
528
+ - allocate_budget gives minimum budget to all agents (floor)
529
+ - adjust_priorities increases budget for under-explored factor
530
+
531
+ Verify: `cargo test -p pe-governance` passes.
532
+
533
+ Reference: ADR-007, DDD-001 (Trust & Audit Context)
534
+ ```
535
+
536
+ ---
537
+
538
+ ## Prompt 12: pe-stream Lab Instrument Ingestion
539
+
540
+ ```
541
+ Implement the pe-stream crate for live laboratory instrument data ingestion as specified in DDD-001 (plans/ddd-001-protein-engineering-domain-model.md, "Experiment & Lab Context") and DDD-002 (plans/ddd-002-bounded-context-integration-patterns.md, Integration 3).
542
+
543
+ This crate is native-only. It depends on pe-core, midstream, and tokio.
544
+
545
+ Implement:
546
+
547
+ 1. InstrumentType — enum: Opentrons, Hamilton, FlowCytometer, PlateReader
548
+
549
+ 2. InstrumentReading — raw data point:
550
+ - instrument_type: InstrumentType
551
+ - instrument_id: String
552
+ - timestamp: DateTime<Utc>
553
+ - raw_data: BTreeMap<String, f64>
554
+ - channel: Option<String>
555
+
556
+ 3. InstrumentSource trait (from ADR-004):
557
+ ```rust
558
+ #[async_trait]
559
+ #[cfg_attr(test, automock)]
560
+ pub trait InstrumentSource: Send + Sync {
561
+ async fn read_next(&mut self) -> Result<Option<InstrumentReading>>;
562
+ fn instrument_type(&self) -> InstrumentType;
563
+ }
564
+ ```
565
+
566
+ 4. ReadingNormalizer — anti-corruption layer (DDD-001) that converts raw InstrumentReadings into ExperimentResult domain types:
567
+ - Maps instrument-specific field names to canonical metric names
568
+ - Validates readings (reject NaN, Inf, out-of-range values)
569
+ - Associates readings with variant IDs via plate map or barcode lookup
570
+
571
+ 5. StreamProcessor — consumes an InstrumentSource stream and produces normalized ExperimentResults:
572
+ ```rust
573
+ pub struct StreamProcessor<S: InstrumentSource> {
574
+ source: S,
575
+ normalizer: ReadingNormalizer,
576
+ }
577
+ impl<S: InstrumentSource> StreamProcessor<S> {
578
+ pub async fn process_next(&mut self) -> Result<Option<ExperimentResult>>;
579
+ pub async fn process_batch(&mut self, max: usize) -> Result<Vec<ExperimentResult>>;
580
+ }
581
+ ```
582
+
583
+ 6. MidstreamSource — wraps midstream crate for real-time AI stream analysis (native only).
584
+
585
+ Write London School TDD tests. Mock InstrumentSource:
586
+ - process_next returns ExperimentResult from mocked instrument reading
587
+ - process_next returns None when source is exhausted
588
+ - normalizer rejects NaN values in raw data
589
+ - normalizer maps instrument-specific field names to canonical names
590
+ - process_batch collects up to max results
591
+ - instrument_type is correctly propagated
592
+
593
+ Verify: `cargo test -p pe-stream` passes.
594
+
595
+ Reference: DDD-001 (Experiment & Lab Context), DDD-002 (Integration 3), ADR-004
596
+ ```
597
+
598
+ ---
599
+
600
+ ## Prompt 13: pe-swarm Agent Orchestration and SAFLA Loop
601
+
602
+ ```
603
+ Implement the pe-swarm crate — the multi-agent orchestration layer with the SAFLA closed loop as specified in ADR-007 (plans/adr-007-safla-closed-loop-orchestration.md), DDD-001 (plans/ddd-001-protein-engineering-domain-model.md, "Variant Design Context"), and DDD-002 (plans/ddd-002-bounded-context-integration-patterns.md, all integration patterns).
604
+
605
+ This crate depends on pe-core, pe-neural (FitnessPredictor), pe-vector (VectorStore, EmbeddingModel), pe-quantum (QuantumBackend), pe-ledger (LedgerWriter), pe-stream (InstrumentSource), pe-governance (LifecycleManager), and pe-rvf (SegmentProducer for HOT_SEG).
606
+
607
+ Implement:
608
+
609
+ 1. AgentRole — enum: SequenceExplorer, FitnessScorer, StructuralValidator, ToxicityScreener, ExperimentDesigner, QuantumDispatcher
610
+
611
+ 2. AgentTask / AgentResult — enums wrapping the input/output for each role
612
+
613
+ 3. SwarmAgent trait (from ADR-004):
614
+ ```rust
615
+ #[async_trait]
616
+ #[cfg_attr(test, automock)]
617
+ pub trait SwarmAgent: Send + Sync {
618
+ async fn execute(&self, task: AgentTask) -> Result<AgentResult>;
619
+ fn role(&self) -> AgentRole;
620
+ }
621
+ ```
622
+
623
+ 4. EvolutionEngine trait (from SPARC pseudocode):
624
+ ```rust
625
+ #[cfg_attr(test, automock)]
626
+ pub trait EvolutionEngine: Send + Sync {
627
+ fn mutate(&self, variant: &ProteinVariant) -> Result<ProteinVariant>;
628
+ fn crossover(&self, a: &ProteinVariant, b: &ProteinVariant) -> Result<ProteinVariant>;
629
+ fn select(&self, population: &[ScoredVariant], top_k: usize) -> Vec<ScoredVariant>;
630
+ }
631
+ ```
632
+
633
+ 5. Concrete agent implementations (each implements SwarmAgent):
634
+ - SequenceExplorerAgent — uses EvolutionEngine to mutate/crossover
635
+ - FitnessScorerAgent — delegates to FitnessPredictor + EmbeddingModel
636
+ - StructuralValidatorAgent — uses VectorStore HNSW search for plausibility
637
+ - ToxicityScreenerAgent — classifies oncogenic risk based on known oncogene similarity
638
+ - ExperimentDesignerAgent — generates lab protocol stubs for Opentrons
639
+ - QuantumDispatcherAgent — submits VQE/QAOA via QuantumBackend
640
+
641
+ 6. CycleConfig — generation number, population_size, mutation_rate, crossover_rate, quantum_enabled, top_k for promotion
642
+
643
+ 7. CycleResult — promoted variants, generation number, stats (variants_created, scored, validated, screened)
644
+
645
+ 8. SwarmCoordinator trait and DefaultCoordinator implementation:
646
+ ```rust
647
+ #[async_trait]
648
+ pub trait SwarmCoordinator: Send + Sync {
649
+ async fn run_design_cycle(&mut self, config: CycleConfig) -> Result<CycleResult>;
650
+ }
651
+ ```
652
+ DefaultCoordinator orchestrates the SAFLA loop exactly as specified in ADR-007:
653
+ DESIGN → SCORE → VALIDATE → SCREEN → (QUANTUM) → LOG → (LEARN) → PROMOTE
654
+
655
+ 9. SimpleEvolutionEngine — concrete EvolutionEngine:
656
+ - mutate: random single-point amino acid substitution
657
+ - crossover: single-point crossover at random position
658
+ - select: sort by composite score, take top_k
659
+
660
+ 10. HOT_SEG SegmentProducer — serializes top-100 promoted candidates.
661
+
662
+ Write London School TDD tests. Mock ALL collaborators (this is the critical London School layer):
663
+ - SAFLA closed loop test: mock_explorer returns 10 variants, mock_scorer scores them, mock_validator passes 8/10, mock_screener passes 7/8. Assert result.promoted.len() == 7. Verify call counts on each mock.
664
+ - Agent retirement: mock LifecycleManager returns retire=true for slow agent. Verify agent is removed.
665
+ - Quantum dispatch: when config.quantum_enabled, verify mock QuantumBackend.submit_vqe is called for top-N candidates.
666
+ - Ledger integration: verify LedgerWriter.append_entry called with CycleCompleted event.
667
+ - Evolution engine: mutate produces valid child variant. Crossover combines parents. Select returns top_k.
668
+ - Empty population: run_design_cycle with 0 population returns empty result, no errors.
669
+
670
+ Verify: `cargo test -p pe-swarm` passes.
671
+
672
+ Reference: ADR-007, ADR-002, ADR-004, DDD-001 (Variant Design), DDD-002 (all integrations)
673
+ ```
674
+
675
+ ---
676
+
677
+ ## Prompt 14: pe-api Axum HTTP/WebSocket Server
678
+
679
+ ```
680
+ Implement the pe-api crate — the axum HTTP/WebSocket API layer as specified in the SPARC specification (plans/sparc-specification.md, Phase 8) and DDD-002 (plans/ddd-002-bounded-context-integration-patterns.md).
681
+
682
+ This crate is native-only. It depends on pe-core, pe-swarm (SwarmCoordinator), pe-neural (FitnessPredictor), pe-vector (VectorStore, EmbeddingModel), pe-ledger (LedgerWriter), pe-quantum (QuantumBackend), and pe-rvf.
683
+
684
+ Implement:
685
+
686
+ 1. AppState — holds all domain trait objects via dependency injection (ADR-004):
687
+ ```rust
688
+ pub struct AppState {
689
+ pub scorer: Arc<dyn FitnessPredictor>,
690
+ pub store: Arc<RwLock<dyn VectorStore>>,
691
+ pub embedder: Arc<dyn EmbeddingModel>,
692
+ pub ledger: Arc<RwLock<dyn LedgerWriter>>,
693
+ pub coordinator: Arc<RwLock<dyn SwarmCoordinator>>,
694
+ }
695
+ ```
696
+
697
+ 2. REST endpoints (axum handlers):
698
+ - POST /api/variants — create a new ProteinVariant (wild_type or from_mutation)
699
+ - POST /api/variants/score — score a variant, returns FitnessScore JSON
700
+ - GET /api/variants/:id — get variant by ID
701
+ - GET /api/variants/search?sequence=...&k=5 — nearest-neighbor search by sequence embedding
702
+ - POST /api/evolution/cycle — trigger a design cycle, returns CycleResult
703
+ - GET /api/evolution/top?k=10 — get top-k promoted candidates from HOT_SEG
704
+ - GET /api/ledger/verify — verify journal chain integrity
705
+ - GET /api/ledger/entries?limit=50&offset=0 — paginated journal entries
706
+ - GET /api/health — health check
707
+
708
+ 3. WebSocket endpoint:
709
+ - WS /api/ws/evolution — streams CycleResult events as design cycles complete
710
+
711
+ 4. Error handling: map domain errors to appropriate HTTP status codes (400 for validation, 404 for not found, 500 for internal). Use a consistent JSON error response format.
712
+
713
+ 5. CORS configuration for browser WASM clients.
714
+
715
+ 6. Router construction: pub fn build_router(state: AppState) -> axum::Router
716
+
717
+ Write London School TDD tests. Mock ALL domain traits in AppState:
718
+ - POST /api/variants/score returns 200 with FitnessScore JSON (mock scorer returns predetermined score)
719
+ - POST /api/variants/score with invalid sequence returns 400
720
+ - GET /api/variants/:id returns 404 for unknown ID
721
+ - GET /api/variants/search returns k results (mock store returns fixture)
722
+ - POST /api/evolution/cycle returns CycleResult (mock coordinator)
723
+ - GET /api/ledger/verify returns {valid: true} (mock ledger)
724
+ - GET /api/health returns 200
725
+
726
+ Use axum::test for HTTP testing.
727
+
728
+ Verify: `cargo test -p pe-api` passes.
729
+
730
+ Reference: SPARC Phase 8, ADR-004, DDD-002
731
+ ```
732
+
733
+ ---
734
+
735
+ ## Prompt 15: pe-wasm Browser WASM Entry Point
736
+
737
+ ```
738
+ Implement the pe-wasm crate — the WASM browser entry point as specified in the SPARC specification (plans/sparc-specification.md, Phase 8) and ADR-003 (plans/adr-003-feature-flag-native-vs-wasm.md).
739
+
740
+ This crate is wasm-only (feature = "wasm"). It depends on pe-core, pe-vector (InMemoryVectorStore), pe-neural (EnsemblePredictor with stub scorers), pe-quantum-wasm (LocalSimulator), and pe-rvf.
741
+
742
+ Implement:
743
+
744
+ 1. WASM-exported functions via #[wasm_bindgen]:
745
+ - score_sequence(sequence: &str) -> JsValue — validates sequence, embeds, scores, returns FitnessScore as JSON
746
+ - run_evolution_step(population_json: &str, config_json: &str) -> JsValue — runs one evolution generation, returns CycleResult as JSON
747
+ - run_local_quantum_sim(hamiltonian_json: &str) -> JsValue — runs VQE on local simulator, returns VqeResult as JSON
748
+ - search_similar(sequence: &str, k: u32) -> JsValue — embeds sequence, searches nearest neighbors, returns results as JSON
749
+ - verify_ledger() -> JsValue — verifies local journal chain, returns {valid: bool}
750
+
751
+ 2. WasmEngine — internal struct holding:
752
+ - InMemoryVectorStore
753
+ - EnsemblePredictor (with stub scorers)
754
+ - LocalSimulatorBackend (pe-quantum-wasm)
755
+ - JournalChain (local, verification-only — no signing in WASM per ADR-005)
756
+
757
+ 3. Initialization:
758
+ - init() — #[wasm_bindgen(start)], sets up panic hook (console_error_panic_hook), initializes tracing-wasm
759
+ - load_rvf(data: &[u8]) -> JsValue — loads an .rvf file, populates WasmEngine from segments (VEC_SEG → store, QUANT_SEG → models, JOURNAL_SEG → ledger)
760
+
761
+ 4. Error handling: all exported functions return Result<JsValue, JsValue> where errors are JSON {error: string}.
762
+
763
+ 5. Memory management: use serde-wasm-bindgen for type conversion. Avoid large allocations; stream RVF segments.
764
+
765
+ Write tests that can run under wasm-pack test --node:
766
+ - score_sequence with valid sequence returns parseable JSON with composite in [0, 1]
767
+ - score_sequence with invalid sequence returns error JSON
768
+ - run_evolution_step with small population returns next generation
769
+ - search_similar returns k results
770
+ - verify_ledger returns {valid: true} on empty/valid chain
771
+
772
+ Verify: `wasm-pack build crates/pe-wasm --target bundler -- --no-default-features --features wasm` succeeds. Bundle < 10 MB.
773
+
774
+ Reference: ADR-003, ADR-005 (WASM crypto constraint), ADR-009, SPARC Phase 8
775
+ ```
776
+
777
+ ---
778
+
779
+ ## Prompt 16: pe-cli Command-Line Interface
780
+
781
+ ```
782
+ Implement the pe-cli crate — the native CLI entry point as specified in the SPARC specification (plans/sparc-specification.md, Phase 8).
783
+
784
+ This crate is native-only. It depends on pe-core, pe-swarm, pe-neural, pe-vector, pe-quantum, pe-ledger, pe-rvf, pe-stream, pe-governance, and pe-api.
785
+
786
+ Implement using clap for argument parsing:
787
+
788
+ 1. Commands:
789
+ - `protein-engine init` — create a new empty .rvf file with MANIFEST_SEG
790
+ - `protein-engine score <sequence>` — score a protein sequence, print FitnessScore
791
+ - `protein-engine evolve --generations N --population-size M` — run N evolution cycles, print summary per generation
792
+ - `protein-engine search <sequence> --k K` — find K nearest neighbors by embedding similarity
793
+ - `protein-engine quantum vqe <molecule>` — run VQE simulation, print energy
794
+ - `protein-engine quantum qaoa <qubo-file>` — run QAOA optimization, print solution
795
+ - `protein-engine ledger verify` — verify journal chain integrity
796
+ - `protein-engine ledger show --limit N` — show last N journal entries
797
+ - `protein-engine rvf build --output <path>` — assemble .rvf from current state
798
+ - `protein-engine rvf inspect <path>` — show .rvf manifest and segment summary
799
+ - `protein-engine serve --port 8080` — start the axum HTTP server (delegates to pe-api)
800
+
801
+ 2. Dependency wiring: construct all real implementations and wire them into trait objects per ADR-004. This is the composition root.
802
+
803
+ 3. Output formatting: structured JSON (--json flag) or human-readable table (default).
804
+
805
+ 4. Configuration: read from environment variables (CHEMIQ_URL, QUANTUM_BACKEND, etc.) or --config file.
806
+
807
+ Write integration tests:
808
+ - `init` creates a valid .rvf file
809
+ - `score` with valid sequence prints a composite score
810
+ - `evolve --generations 1` completes and prints generation summary
811
+ - `ledger verify` on fresh .rvf returns "valid"
812
+ - `rvf inspect` on a built .rvf shows correct segment count
813
+
814
+ Verify: `cargo test -p pe-cli` passes. `cargo build -p pe-cli --features native` produces a working binary.
815
+
816
+ Reference: SPARC Phase 8, ADR-004 (composition root)
817
+ ```
818
+
819
+ ---
820
+
821
+ ## Prompt 17: Python Sidecar Implementation
822
+
823
+ ```
824
+ Implement the full chemiq-sidecar Python service as specified in ADR-008 (plans/adr-008-python-sidecar-quantum-chemistry.md).
825
+
826
+ Create services/chemiq-sidecar/ with:
827
+
828
+ 1. main.py — FastAPI application with these endpoints:
829
+ - POST /vqe — accepts {molecule: str, basis_set: str, ansatz: str, max_iterations: int}. Uses pyChemiQ to run VQE. Returns {energy: float, parameters: [float], iterations: int, converged: bool}.
830
+ - POST /qaoa — accepts {qubo_matrix: [[float]], p_layers: int}. Uses pyqpanda-algorithm for QAOA. Returns {solution: [int], cost: float, iterations: int}.
831
+ - GET /health — returns {status: "ok", backend: "origin_quantum"|"simulator"}
832
+ - GET /capabilities — returns {max_qubits: int, available_ansatze: [str], backend: str}
833
+
834
+ 2. requirements.txt:
835
+ - pychemiq
836
+ - pyqpanda3
837
+ - pyqpanda_alg
838
+ - fastapi
839
+ - uvicorn
840
+ - pydantic
841
+
842
+ 3. Dockerfile:
843
+ - FROM python:3.11-slim
844
+ - Install requirements
845
+ - EXPOSE 8100
846
+ - CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8100"]
847
+
848
+ 4. Error handling: if pyChemiQ is not available (import fails), fall back to a simple numpy-based simulator and set backend to "simulator" in /health and /capabilities.
849
+
850
+ 5. Input validation with Pydantic models for all request/response types.
851
+
852
+ Write pytest tests:
853
+ - /health returns 200 with status "ok"
854
+ - /vqe with H2 molecule returns energy within tolerance of -1.137 Ha
855
+ - /qaoa with trivial QUBO returns correct solution
856
+ - /vqe with invalid molecule returns 400
857
+ - /capabilities returns correct max_qubits
858
+
859
+ Reference: ADR-008
860
+ ```
861
+
862
+ ---
863
+
864
+ ## Prompt 18: Docker and Docker Compose Configuration
865
+
866
+ ```
867
+ Create the Docker infrastructure for Protein-Engine as specified in the research doc (plans/research.md, "Repository Structure" and "Deployment Philosophy").
868
+
869
+ Create:
870
+
871
+ 1. docker/Dockerfile.node — full server node:
872
+ - Multi-stage build: Rust builder stage (cargo build --release --features native) → minimal runtime image
873
+ - COPY the built binary and any required assets
874
+ - EXPOSE 8080
875
+ - CMD starts pe-cli serve
876
+
877
+ 2. docker/Dockerfile.chemiq — pyChemiQ sidecar:
878
+ - FROM python:3.11-slim
879
+ - COPY services/chemiq-sidecar/
880
+ - Install dependencies
881
+ - EXPOSE 8100
882
+
883
+ 3. docker/Dockerfile.wasm-builder — wasm-pack build container:
884
+ - FROM rust with wasm-pack installed
885
+ - Runs wasm-pack build crates/pe-wasm
886
+
887
+ 4. docker-compose.yml — production stack:
888
+ - protein-engine service (Dockerfile.node)
889
+ - chemiq-sidecar service (Dockerfile.chemiq)
890
+ - Health checks on both services
891
+ - Environment variables: CHEMIQ_URL=http://chemiq-sidecar:8100
892
+ - Volumes for .rvf file persistence
893
+
894
+ 5. docker-compose.dev.yml — dev stack:
895
+ - Same services with hot reload (cargo-watch or similar)
896
+ - Exposed ports for debugging
897
+ - Volume mounts for source code
898
+
899
+ 6. build-wasm.sh — one-command WASM build script:
900
+ - Runs wasm-pack build with correct flags
901
+ - Copies output to web/pkg/
902
+ - Prints bundle size
903
+
904
+ 7. build-rvf.sh — one-command .rvf assembly script:
905
+ - Builds native binary
906
+ - Runs pe-cli rvf build
907
+ - Prints segment summary
908
+
909
+ All Dockerfiles should be minimal, use multi-stage builds, and not include unnecessary tools.
910
+
911
+ Reference: plans/research.md (Deployment Philosophy, Repository Structure), ADR-001
912
+ ```
913
+
914
+ ---
915
+
916
+ ## Prompt 19: Web Frontend Scaffold
917
+
918
+ ```
919
+ Create the web frontend scaffold for Protein-Engine as specified in the research doc (plans/research.md, "Repository Structure").
920
+
921
+ Create web/ with:
922
+
923
+ 1. package.json — dependencies: vite, typescript, vite-plugin-wasm
924
+ - scripts: dev, build, preview
925
+ - devDependencies: vite, typescript, vite-plugin-wasm
926
+
927
+ 2. vite.config.ts — configured with vite-plugin-wasm for loading pe-wasm WASM module
928
+
929
+ 3. tsconfig.json — strict TypeScript config
930
+
931
+ 4. index.html — minimal shell that loads main.ts
932
+
933
+ 5. src/main.ts — TypeScript entry point:
934
+ - Imports pe-wasm WASM module (from ../pkg/ after wasm-pack build)
935
+ - Initializes the WASM engine
936
+ - Demonstrates: score a hardcoded sequence, display result
937
+ - Placeholder for loading .rvf file from user upload or URL
938
+
939
+ 6. src/types.ts — TypeScript interfaces matching pe-core types:
940
+ - ProteinVariant, FitnessScore, CycleResult, VqeResult
941
+
942
+ 7. src/components/ — placeholder files:
943
+ - sequence-editor.ts — text input for amino acid sequences
944
+ - fitness-chart.ts — placeholder for fitness visualization
945
+ - dag-viewer.ts — placeholder for lineage DAG visualization
946
+
947
+ This is a scaffold only — functional UI comes later. The goal is to verify the WASM module loads and executes in a browser context.
948
+
949
+ Reference: plans/research.md (Web Frontend), ADR-003 (wasm feature)
950
+ ```
951
+
952
+ ---
953
+
954
+ ## Prompt 20: Integration Tests — Cross-Crate Wiring
955
+
956
+ ```
957
+ Create a top-level integration test suite that verifies real crate-to-crate interactions, replacing London School mocks with real implementations one layer at a time per the SPARC refinement plan (plans/sparc-specification.md, "London School TDD Workflow Per Crate" step 7-8).
958
+
959
+ Create tests/ directory at workspace root with:
960
+
961
+ 1. tests/integration_scoring_pipeline.rs:
962
+ - Wire real pe-core types + real InMemoryVectorStore + real EnsemblePredictor (stub scorers)
963
+ - Create 50 ProteinVariants, embed them (use a deterministic test embedder), store in VectorStore
964
+ - Score all variants, verify FitnessScores are valid
965
+ - Search nearest neighbors, verify results are sorted by similarity
966
+ - No mocks — this validates the pe-core → pe-vector → pe-neural pipeline
967
+
968
+ 2. tests/integration_evolution_cycle.rs:
969
+ - Wire real SimpleEvolutionEngine + real EnsemblePredictor + real InMemoryVectorStore + mock LedgerWriter + mock QuantumBackend
970
+ - Run 3 evolution cycles with population of 20
971
+ - Verify population grows/evolves across generations
972
+ - Verify top candidates are correctly selected
973
+ - Verify LedgerWriter.append_entry was called per cycle
974
+
975
+ 3. tests/integration_ledger_chain.rs:
976
+ - Wire real JournalChain + real MlDsaSigner (actual post-quantum crypto)
977
+ - Append 100 entries of various types
978
+ - Verify chain integrity
979
+ - Serialize to JOURNAL_SEG, deserialize, re-verify
980
+ - Tamper with one entry, verify detection
981
+
982
+ 4. tests/integration_quantum_local.rs:
983
+ - Wire real QuantumRouter + real LocalSimulatorBackend (pe-quantum-wasm)
984
+ - No remote backends registered — router must fall back to local
985
+ - Run VQE on H2 molecule, verify energy ≈ -1.137 Ha
986
+ - Run QAOA on trivial QUBO, verify correct solution
987
+
988
+ 5. tests/integration_rvf_assembly.rs:
989
+ - Wire real RvfBuilder + real segment producers from all crates
990
+ - Build a complete .rvf file with all available segments
991
+ - Verify MANIFEST_SEG capabilities
992
+ - Verify parent_hash lineage
993
+ - Deserialize and verify all segments are intact
994
+ - Check file_hash is deterministic
995
+
996
+ 6. tests/integration_full_safla.rs:
997
+ - Wire the complete stack: all real implementations except QuantumBackend (use LocalSimulator) and InstrumentSource (mock — no lab hardware in CI)
998
+ - Run a complete SAFLA cycle: design → score → validate → screen → quantum → log → promote
999
+ - Verify promoted candidates are valid ProteinVariants with passing fitness, structure, and safety scores
1000
+ - Verify journal chain has entries for each step
1001
+ - This is the primary acceptance test for the platform
1002
+
1003
+ Reference: SPARC Completion (Test Pyramid), ADR-002 (step 7-8), DDD-002 (all integrations)
1004
+ ```
1005
+
1006
+ ---
1007
+
1008
+ ## Prompt 21: CI Pipeline Configuration
1009
+
1010
+ ```
1011
+ Create the CI/CD pipeline configuration as specified in the SPARC completion section (plans/sparc-specification.md, "CI Pipeline Stages").
1012
+
1013
+ Create .github/workflows/ci.yml with these stages:
1014
+
1015
+ 1. fmt — cargo fmt --check --all
1016
+ 2. clippy — cargo clippy --all-targets --features native -- -D warnings
1017
+ 3. test-native — cargo test --features native (unit + integration tests)
1018
+ 4. test-wasm — cargo test --target wasm32-unknown-unknown -p pe-core -p pe-quantum-wasm (no_std crates)
1019
+ 5. build-wasm — wasm-pack build crates/pe-wasm, check bundle size < 10 MB
1020
+ 6. cross-compile — cross build --target aarch64-unknown-linux-gnu --features native (verify Raspberry Pi target)
1021
+ 7. build-rvf — ./build-rvf.sh, validate the output artifact
1022
+ 8. docker — docker compose -f docker-compose.dev.yml up --build --abort-on-container-exit (full stack smoke test)
1023
+
1024
+ Matrix strategy: run on ubuntu-latest. Cache cargo registry and target dir. Install wasm-pack, cross, and wasm32-unknown-unknown target.
1025
+
1026
+ Also create:
1027
+ - .github/workflows/release.yml — triggered on tags, builds release binaries for x86_64 + aarch64, builds WASM, assembles .rvf, creates GitHub release with all artifacts
1028
+ - Makefile or justfile at root with convenience targets: make test, make build, make wasm, make rvf, make docker
1029
+
1030
+ Reference: SPARC Completion (CI Pipeline Stages, Definition of Done)
1031
+ ```
1032
+
1033
+ ---
1034
+
1035
+ ## Prompt 22: MCP Server Integration
1036
+
1037
+ ```
1038
+ Create the MCP (Model Context Protocol) server integration that allows Claude Code to operate the entire platform, as specified in FR-12 and the research doc (plans/research.md).
1039
+
1040
+ This wraps the existing @ruvector/rvf-mcp-server npm package with Protein-Engine-specific tool definitions.
1041
+
1042
+ Create mcp/ directory with:
1043
+
1044
+ 1. mcp/protein-engine-mcp.json — MCP server configuration:
1045
+ - Tool definitions for all pe-cli commands exposed as MCP tools:
1046
+ - score_sequence(sequence: string) → FitnessScore
1047
+ - evolve(generations: int, population_size: int) → CycleResult
1048
+ - search_similar(sequence: string, k: int) → Vec<ScoredVariant>
1049
+ - quantum_vqe(molecule: string) → VqeResult
1050
+ - ledger_verify() → {valid: bool}
1051
+ - rvf_inspect(path: string) → ManifestSummary
1052
+ - create_variant(name: string, sequence: string, factor: string) → ProteinVariant
1053
+
1054
+ 2. mcp/server.ts — thin TypeScript wrapper:
1055
+ - Imports @ruvector/rvf-mcp-server
1056
+ - Registers Protein-Engine-specific tools
1057
+ - Delegates to pe-cli binary via child process or to pe-api HTTP endpoints
1058
+
1059
+ 3. mcp/package.json — dependencies: @ruvector/rvf-mcp-server, @ruvector/rvf-node
1060
+
1061
+ 4. Instructions in mcp/README.md for adding to Claude Code config:
1062
+ ```json
1063
+ {
1064
+ "mcpServers": {
1065
+ "protein-engine": {
1066
+ "command": "npx",
1067
+ "args": ["@ruvector/rvf-mcp-server", "protein-engine.rvf"]
1068
+ }
1069
+ }
1070
+ }
1071
+ ```
1072
+
1073
+ Reference: FR-12, plans/research.md (MCP interface)
1074
+ ```
1075
+
1076
+ ---
1077
+
1078
+ ## Prompt 23: E2E Smoke Tests
1079
+
1080
+ ```
1081
+ Create end-to-end smoke tests that verify the platform works across deployment targets as specified in the SPARC completion section (plans/sparc-specification.md, "Test Pyramid" — E2E layer).
1082
+
1083
+ Create tests/e2e/ with:
1084
+
1085
+ 1. tests/e2e/test_docker_stack.sh:
1086
+ - docker compose up -d
1087
+ - Wait for health checks to pass
1088
+ - curl POST /api/variants/score with a test sequence → verify 200
1089
+ - curl POST /api/evolution/cycle → verify CycleResult JSON
1090
+ - curl GET /api/ledger/verify → verify {valid: true}
1091
+ - curl GET /api/health → verify 200
1092
+ - docker compose down
1093
+
1094
+ 2. tests/e2e/test_cli.sh:
1095
+ - Build pe-cli binary
1096
+ - Run `protein-engine init --output /tmp/test.rvf`
1097
+ - Run `protein-engine score MKWVTFISLLLLFSSAYS` → verify output contains "composite"
1098
+ - Run `protein-engine evolve --generations 2 --population-size 10` → verify output contains "Generation 2"
1099
+ - Run `protein-engine ledger verify` → verify "valid"
1100
+ - Run `protein-engine rvf inspect /tmp/test.rvf` → verify segment count
1101
+
1102
+ 3. tests/e2e/test_wasm.js (Node.js):
1103
+ - Load pe-wasm package from web/pkg/
1104
+ - Call init()
1105
+ - Call score_sequence("MKWVTFISLLLLFSSAYS") → verify parseable result with composite in [0, 1]
1106
+ - Call verify_ledger() → verify {valid: true}
1107
+
1108
+ These tests are the top of the test pyramid — run in CI after all other stages pass.
1109
+
1110
+ Reference: SPARC Completion (Test Pyramid, Definition of Done for Platform)
1111
+ ```
1112
+
1113
+ ---
1114
+
1115
+ ## Dependency Graph Summary
1116
+
1117
+ ```
1118
+ Prompt 01: Workspace scaffold (no dependencies)
1119
+ Prompt 02: pe-core (depends on: 01)
1120
+ Prompt 03: pe-rvf (depends on: 01, 02)
1121
+ Prompt 04: pe-vector (depends on: 02, 03)
1122
+ Prompt 05: pe-neural (depends on: 02, 04)
1123
+ Prompt 06: pe-solver (depends on: 02)
1124
+ Prompt 07: pe-quantum-wasm (depends on: 02)
1125
+ Prompt 08: pe-quantum (depends on: 02, 03, 07)
1126
+ Prompt 09: pe-chemistry (depends on: 02, 08)
1127
+ Prompt 10: pe-ledger (depends on: 02, 03)
1128
+ Prompt 11: pe-governance (depends on: 02)
1129
+ Prompt 12: pe-stream (depends on: 02)
1130
+ Prompt 13: pe-swarm (depends on: 02, 04, 05, 08, 10, 11, 12)
1131
+ Prompt 14: pe-api (depends on: 02, 04, 05, 08, 10, 13)
1132
+ Prompt 15: pe-wasm (depends on: 02, 04, 05, 07)
1133
+ Prompt 16: pe-cli (depends on: all crates)
1134
+ Prompt 17: Python sidecar (depends on: 09 for API contract)
1135
+ Prompt 18: Docker (depends on: 16, 17)
1136
+ Prompt 19: Web frontend (depends on: 15)
1137
+ Prompt 20: Integration tests (depends on: all crates)
1138
+ Prompt 21: CI pipeline (depends on: 18, 19, 20)
1139
+ Prompt 22: MCP server (depends on: 14 or 16)
1140
+ Prompt 23: E2E smoke tests (depends on: 18, 19, 22)
1141
+ ```
1142
+
1143
+ ### Parallelization Opportunities
1144
+
1145
+ These groups can be executed concurrently within each tier:
1146
+
1147
+ ```
1148
+ Tier 0: [01]
1149
+ Tier 1: [02]
1150
+ Tier 2: [03, 06, 07, 11, 12] ← 5 prompts in parallel
1151
+ Tier 3: [04, 08, 10] ← 3 prompts in parallel
1152
+ Tier 4: [05, 09] ← 2 prompts in parallel
1153
+ Tier 5: [13, 15, 17] ← 3 prompts in parallel
1154
+ Tier 6: [14, 16] ← 2 prompts in parallel
1155
+ Tier 7: [18, 19, 22] ← 3 prompts in parallel
1156
+ Tier 8: [20]
1157
+ Tier 9: [21, 23] ← 2 prompts in parallel
1158
+ ```