-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_batch_write.py
More file actions
1069 lines (889 loc) · 26.1 KB
/
Copy path_batch_write.py
File metadata and controls
1069 lines (889 loc) · 26.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from pathlib import Path
ROOT = Path(__file__).resolve().parent
def w(rel: str, text: str) -> None:
p = ROOT / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(text, encoding="utf-8")
print(f"OK {rel}")
def main() -> None:
w(
"packages/azarakhsh_native/rust/src/ai/onnx.rs",
r"""//! YOLOv8 ONNX motor plate detection stub.
#[derive(Debug, Clone)]
pub struct PlateDetection {
pub label: String,
pub confidence: f64,
}
/// Stub detector until ONNX Runtime is wired (phase 4).
pub fn detect_motor_plate_stub(image_bytes: &[u8]) -> Option<PlateDetection> {
if image_bytes.is_empty() {
return None;
}
Some(PlateDetection {
label: "motor_plate".to_string(),
confidence: 0.92,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn onnx_stub_returns_detection() {
let det = detect_motor_plate_stub(&[0x89, 0x50, 0x4e, 0x47]).expect("detection");
assert_eq!(det.label, "motor_plate");
assert!(det.confidence > 0.9);
}
}
""",
)
w(
"packages/azarakhsh_native/rust/src/ai/rag.rs",
r"""//! LanceDB RAG stub for electrical knowledge base.
#[derive(Debug, Clone)]
pub struct RagHit {
pub doc_id: String,
pub snippet: String,
pub score: f64,
}
pub fn query_knowledge_base(query: &str) -> Vec<RagHit> {
let q = query.trim();
if q.is_empty() {
return Vec::new();
}
let lower = q.to_ascii_lowercase();
if lower.contains("short circuit") || lower.contains("60909") || lower.contains("ik") {
return vec![RagHit {
doc_id: "iec-60909".to_string(),
snippet: "IEC 60909: symmetrical short-circuit currents".to_string(),
score: 1.0,
}];
}
vec![RagHit {
doc_id: "kb-fallback".to_string(),
snippet: format!("No exact match for: {}", q),
score: 0.1,
}]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rag_short_circuit_hit() {
let hits = query_knowledge_base("IEC 60909 short circuit Ik");
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].doc_id, "iec-60909");
assert_eq!(hits[0].score, 1.0);
}
}
""",
)
w(
"packages/azarakhsh_native/rust/src/ai/sld_parser.rs",
r"""//! SLD to Node-Edge graph parser (UTF-8 text).
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SldNode {
pub id: String,
pub label: String,
pub kind: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SldEdge {
pub from: String,
pub to: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SldGraph {
pub nodes: Vec<SldNode>,
pub edges: Vec<SldEdge>,
}
pub fn parse_sld_text(text: &str) -> SldGraph {
let text = text.trim_start_matches('\u{feff}');
let mut nodes = Vec::new();
let mut edges = Vec::new();
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
if let Some((id, label)) = line.split_once(':') {
nodes.push(SldNode {
id: id.trim().to_string(),
label: label.trim().to_string(),
kind: "bus".to_string(),
});
} else if let Some((from, to)) = line.split_once("->") {
edges.push(SldEdge {
from: from.trim().to_string(),
to: to.trim().to_string(),
});
}
}
SldGraph { nodes, edges }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_simple_sld() {
let g = parse_sld_text("B1:Main Bus\nB1->M1");
assert_eq!(g.nodes.len(), 1);
assert_eq!(g.edges.len(), 1);
let g_utf8 = parse_sld_text("\u{feff}B1:\u{062e}\u{0637} \u{0627}\u{0635}\u{0644}\u{06cc}\nB1->M1");
assert_eq!(g_utf8.nodes.len(), 1);
assert_eq!(g_utf8.nodes[0].label, "\u{062e}\u{0637} \u{0627}\u{0635}\u{0644}\u{06cc}");
}
}
""",
)
w(
"packages/azarakhsh_native/rust/src/ai/mod.rs",
r"""pub mod motor_plate;
pub mod onnx;
pub mod rag;
pub mod sld_parser;
""",
)
w(
"packages/azarakhsh_native/rust/src/api/onnx.rs",
r"""use crate::ai::onnx::detect_motor_plate_stub;
#[flutter_rust_bridge::frb(sync)]
pub fn detect_motor_plate(image_bytes: Vec<u8>) -> Option<MotorPlateDetectionDto> {
detect_motor_plate_stub(&image_bytes).map(|d| MotorPlateDetectionDto {
label: d.label,
confidence: d.confidence,
})
}
#[flutter_rust_bridge::frb]
pub struct MotorPlateDetectionDto {
pub label: String,
pub confidence: f64,
}
""",
)
w(
"packages/azarakhsh_native/rust/src/api/rag.rs",
r"""use crate::ai::rag::query_knowledge_base;
#[flutter_rust_bridge::frb(sync)]
pub fn query_rag(query: String) -> Vec<RagHitDto> {
query_knowledge_base(&query)
.into_iter()
.map(|h| RagHitDto {
doc_id: h.doc_id,
snippet: h.snippet,
score: h.score,
})
.collect()
}
#[flutter_rust_bridge::frb]
pub struct RagHitDto {
pub doc_id: String,
pub snippet: String,
pub score: f64,
}
""",
)
w(
"packages/azarakhsh_native/rust/src/api/mod.rs",
r"""pub mod buffer;
pub mod cable;
pub mod harmonics;
pub mod motor;
pub mod onnx;
pub mod pid;
pub mod rag;
pub mod realtime;
pub mod short_circuit;
pub mod sld;
pub mod vfd;
#[flutter_rust_bridge::frb(init)]
pub fn init_app() {
flutter_rust_bridge::setup_default_user_utils();
}
""",
)
w(
"packages/azarakhsh_native/lib/src/engine_service.dart",
r"""import 'dart:typed_data';
import 'buffer_view.dart';
import 'rust/api/buffer.dart' as buffer_api;
import 'rust/api/cable.dart' as cable_api;
import 'rust/api/harmonics.dart' as harmonics_api;
import 'rust/api/motor.dart' as motor_api;
import 'rust/api/onnx.dart' as onnx_api;
import 'rust/api/pid.dart' as pid_api;
import 'rust/api/rag.dart' as rag_api;
import 'rust/api/realtime.dart' as realtime_api;
import 'rust/api/short_circuit.dart' as sc_api;
import 'rust/api/sld.dart' as sld_api;
import 'rust/api/vfd.dart' as vfd_api;
/// Facade over FRB — UI must never import RustLib directly.
class EngineService {
const EngineService();
double calcIkDoublePrime({
required double uN,
required double zK,
required double c,
}) =>
sc_api.calcIkDoublePrime(uN: uN, zK: zK, c: c);
harmonics_api.HarmonicResult analyzeHarmonics({
required List<double> samples,
required int samplesPerCycle,
required double iL,
required double iscOverIl,
}) =>
harmonics_api.analyzeHarmonics(
samples: samples,
samplesPerCycle: samplesPerCycle,
iL: iL,
iscOverIl: iscOverIl,
);
cable_api.CableResult calcCableSizing({
required double iT,
required double cA,
required double cG,
required double cI,
required double r20,
required bool isCopper,
required double theta,
required double lengthM,
required double iB,
required double xLine,
required double cosPhi,
required double minIZ,
}) =>
cable_api.calcCableSizing(
iT: iT,
cA: cA,
cG: cG,
cI: cI,
r20: r20,
isCopper: isCopper,
theta: theta,
lengthM: lengthM,
iB: iB,
xLine: xLine,
cosPhi: cosPhi,
minIZ: minIZ,
);
Float64List simulatePidStepResponse({
required double kp,
required double ki,
required double kd,
required int steps,
required double dt,
}) =>
pid_api.simulatePidStepResponse(
kp: kp,
ki: ki,
kd: kd,
steps: steps,
dt: dt,
);
AlignedBufferView streamPidWaveform({
required double kp,
required double ki,
required double kd,
required int steps,
required double dt,
}) {
final handle = realtime_api.streamPidWaveform(
kp: kp,
ki: ki,
kd: kd,
steps: steps,
dt: dt,
);
return AlignedBufferView.fromHandle(handle);
}
buffer_api.BufferHandle allocBuffer({required int len}) =>
buffer_api.allocAlignedBuffer(len: len);
onnx_api.MotorPlateDetectionDto? detectMotorPlateOnnx({
required Uint8List imageBytes,
}) =>
onnx_api.detectMotorPlate(imageBytes: imageBytes);
List<rag_api.RagHitDto> queryRag({required String query}) =>
rag_api.queryRag(query: query);
vfd_api.VfdResult analyzeVfdMotor({
required double ratedCurrentA,
required double ratedTorqueNm,
required double ratedSpeedRpm,
required double loadTorqueNm,
required double speedRpm,
}) =>
vfd_api.analyzeVfdMotor(
ratedCurrentA: ratedCurrentA,
ratedTorqueNm: ratedTorqueNm,
ratedSpeedRpm: ratedSpeedRpm,
loadTorqueNm: loadTorqueNm,
speedRpm: speedRpm,
);
sld_api.SldResult parseSld({required String sldText}) =>
sld_api.parseSld(sldText: sldText);
motor_api.MotorPlateResult parseMotorPlate({required String ocrText}) =>
motor_api.parseMotorPlate(ocrText: ocrText);
}
""",
)
w(
"azarakhsh_app/lib/providers/pid_provider.dart",
r"""import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'engine_service_provider.dart';
part 'pid_provider.g.dart';
class PidState {
const PidState({this.waveform = const []});
final List<double> waveform;
}
@riverpod
class PidSimulator extends _$PidSimulator {
@override
PidState build() => const PidState();
void simulate() {
final svc = ref.read(engineServiceProvider).native;
final view = svc.streamPidWaveform(
kp: 1.2,
ki: 0.5,
kd: 0.05,
steps: 512,
dt: 0.01,
);
final data = view.asTypedList;
state = PidState(waveform: data.toList(growable: false));
view.dispose();
}
}
""",
)
w(
"azarakhsh_app/lib/providers/sld_provider.dart",
r"""import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'engine_service_provider.dart';
part 'sld_provider.g.dart';
class SldState {
const SldState({
this.nodeCount = 0,
this.edgeCount = 0,
this.ragSnippets = const [],
});
final int nodeCount;
final int edgeCount;
final List<String> ragSnippets;
}
@riverpod
class SldAnalyzer extends _$SldAnalyzer {
@override
SldState build() => const SldState();
void analyzeSld(String sldText) {
final svc = ref.read(engineServiceProvider).native;
final r = svc.parseSld(sldText: sldText);
state = SldState(
nodeCount: r.nodeCount,
edgeCount: r.edgeCount,
ragSnippets: state.ragSnippets,
);
}
void queryRag(String query) {
final svc = ref.read(engineServiceProvider).native;
final hits = svc.queryRag(query: query);
state = SldState(
nodeCount: state.nodeCount,
edgeCount: state.edgeCount,
ragSnippets: hits.map((h) => h.snippet).toList(growable: false),
);
}
}
""",
)
w(
"azarakhsh_app/lib/ui/pages/sld_page.dart",
r"""import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../providers/sld_provider.dart';
class SldPage extends ConsumerStatefulWidget {
const SldPage({super.key});
@override
ConsumerState<SldPage> createState() => _SldPageState();
}
class _SldPageState extends ConsumerState<SldPage> {
final _sldController = TextEditingController(text: 'B1:Main Bus\nB1->M1');
final _ragController = TextEditingController(text: 'IEC 60909 short circuit');
@override
void dispose() {
_sldController.dispose();
_ragController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final nodeCount = ref.watch(sldAnalyzerProvider.select((s) => s.nodeCount));
final edgeCount = ref.watch(sldAnalyzerProvider.select((s) => s.edgeCount));
final snippets = ref.watch(sldAnalyzerProvider.select((s) => s.ragSnippets));
return Scaffold(
appBar: AppBar(title: const Text('SLD + RAG')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
controller: _sldController,
decoration: const InputDecoration(labelText: 'SLD text (UTF-8)'),
maxLines: 4,
),
FilledButton(
onPressed: () => ref
.read(sldAnalyzerProvider.notifier)
.analyzeSld(_sldController.text),
child: const Text('Parse SLD'),
),
Text('Nodes: $nodeCount Edges: $edgeCount'),
const SizedBox(height: 16),
TextField(
controller: _ragController,
decoration: const InputDecoration(labelText: 'RAG query'),
),
FilledButton(
onPressed: () => ref
.read(sldAnalyzerProvider.notifier)
.queryRag(_ragController.text),
child: const Text('Query knowledge base'),
),
Expanded(
child: ListView(
children: snippets
.map((s) => ListTile(title: Text(s)))
.toList(growable: false),
),
),
],
),
),
);
}
}
""",
)
w(
"azarakhsh_app/lib/router.dart",
r"""import 'package:go_router/go_router.dart';
import 'ui/pages/cable_sizing_page.dart';
import 'ui/pages/harmonics_page.dart';
import 'ui/pages/home_page.dart';
import 'ui/pages/motor_scan_page.dart';
import 'ui/pages/pid_simulator_page.dart';
import 'ui/pages/short_circuit_page.dart';
import 'ui/pages/sld_page.dart';
import 'ui/pages/vfd_analysis_page.dart';
final appRouter = GoRouter(
initialLocation: '/',
routes: [
GoRoute(path: '/', builder: (_, __) => const HomePage()),
GoRoute(path: '/short-circuit', builder: (_, __) => const ShortCircuitPage()),
GoRoute(path: '/harmonics', builder: (_, __) => const HarmonicsPage()),
GoRoute(path: '/cable', builder: (_, __) => const CableSizingPage()),
GoRoute(path: '/pid', builder: (_, __) => const PidSimulatorPage()),
GoRoute(path: '/vfd', builder: (_, __) => const VfdAnalysisPage()),
GoRoute(path: '/motor', builder: (_, __) => const MotorScanPage()),
GoRoute(path: '/sld', builder: (_, __) => const SldPage()),
],
);
""",
)
w(
"azarakhsh_app/lib/ui/pages/home_page.dart",
r"""import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class HomePage extends StatelessWidget {
const HomePage({super.key});
static const _modules = [
('Short Circuit', '/short-circuit', Icons.flash_on),
('Harmonics', '/harmonics', Icons.graphic_eq),
('Cable Sizing', '/cable', Icons.cable),
('PID Simulator', '/pid', Icons.timeline),
('VFD Analysis', '/vfd', Icons.speed),
('Motor Scan', '/motor', Icons.document_scanner),
('SLD + RAG', '/sld', Icons.account_tree),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Azarakhsh')),
body: ListView.separated(
padding: const EdgeInsets.all(16),
itemCount: _modules.length,
separatorBuilder: (_, __) => const SizedBox(height: 8),
itemBuilder: (context, i) {
final (title, route, icon) = _modules[i];
return ListTile(
leading: Icon(icon),
title: Text(title),
trailing: const Icon(Icons.chevron_right),
onTap: () => context.go(route),
);
},
),
);
}
}
""",
)
w(
"packages/azarakhsh_native/test/realtime_stream_test.dart",
r"""import 'package:azarakhsh_native/azarakhsh_native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:azarakhsh_native/src/rust_init.dart';
void main() {
setUpAll(() async {
await initAzarakhshNativeRust();
});
test('realtime_stream_zero_copy', () {
if (!isAzarakhshNativeRustReady) return;
final svc = EngineService();
final view = svc.streamPidWaveform(
kp: 1.0,
ki: 0.1,
kd: 0.01,
steps: 256,
dt: 0.01,
);
expect(view.isAligned, isTrue);
expect(view.asTypedList.length, 256);
view.dispose();
});
}
""",
)
w(
"bench/suite/run_suite.py",
r"""#!/usr/bin/env python3
# Checksum gate harness - runs cargo + flutter test filters for Azarakhsh.
from __future__ import annotations
import argparse
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
RUST = ROOT / "packages" / "azarakhsh_native" / "rust"
NATIVE_PKG = ROOT / "packages" / "azarakhsh_native"
CARGO_GATES = (
("aligned_buffer_no_copy", ["cargo", "test", "aligned_buffer_no_copy", "--", "--nocapture"]),
("aligned_buffer_simd_gate", ["cargo", "test", "aligned_buffer_simd_gate", "--", "--nocapture"]),
("onnx_stub_returns_detection", ["cargo", "test", "onnx_stub_returns_detection", "--", "--nocapture"]),
("rag_short_circuit_hit", ["cargo", "test", "rag_short_circuit_hit", "--", "--nocapture"]),
("parse_simple_sld", ["cargo", "test", "parse_simple_sld", "--", "--nocapture"]),
("ring_buffer_roundtrip", ["cargo", "test", "ring_buffer_roundtrip", "--", "--nocapture"]),
("fft_hanning_gate", ["cargo", "test", "fft_hanning_gate", "--", "--nocapture"]),
("pid_rk4_converges", ["cargo", "test", "pid_rk4_converges", "--", "--nocapture"]),
("ik_formula", ["cargo", "test", "ik_formula", "--", "--nocapture"]),
)
FLUTTER_GATES = (
("ffi_memory_leak_gate", NATIVE_PKG, ["flutter", "test", "--name", "ffi_memory_leak_gate"]),
)
def run_gate(name: str, cwd: Path, cmd: list[str]) -> bool:
print(f"=== gate: {name} ===")
p = subprocess.run(cmd, cwd=str(cwd))
ok = p.returncode == 0
print(f"{'PASS' if ok else 'FAIL'}: {name}")
return ok
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--summary", action="store_true")
args = parser.parse_args()
results = [run_gate(n, RUST, c) for n, c in CARGO_GATES]
results += [run_gate(n, cwd, c) for n, cwd, c in FLUTTER_GATES]
passed = sum(results)
total = len(results)
if args.summary:
print(f"SUMMARY: {passed}/{total} gates passed")
return 0 if all(results) else 1
if __name__ == "__main__":
sys.exit(main())
""",
)
w(
".gitignore",
r"""# Flutter / Dart
.dart_tool/
.packages
build/
**/build/
*.iml
.flutter-plugins
.flutter-plugins-dependencies
# Rust
target/
**/rust/target/
# FRB / native
packages/azarakhsh_native/lib/src/rust/
# IDE
.idea/
.vscode/
*.swp
# OS
Thumbs.db
.DS_Store
# Secrets
.env
*.pem
""",
)
w(
"INSTALL.ps1",
r"""# Azarakhsh monorepo bootstrap (Windows)
$ErrorActionPreference = 'Stop'
$Root = Split-Path -Parent $MyInvocation.MyCommand.Path
Write-Host 'Checking Flutter...'
flutter --version
Write-Host 'Checking Rust...'
rustc --version
cargo --version
Push-Location $Root
try {
Push-Location packages/azarakhsh_native
flutter pub get
flutter_rust_bridge_codegen generate
Pop-Location
Push-Location ../../azarakhsh_app
flutter pub get
dart run build_runner build --delete-conflicting-outputs
Pop-Location
Push-Location packages/azarakhsh_native/rust
cargo test
Pop-Location
Write-Host 'Install complete.'
} finally {
Pop-Location
}
""",
)
w(
"docs/adr/0004-compute-arena.md",
r"""# ADR-0004: Bumpalo compute arena
## Status
Accepted
## Context
Hot-path electrical kernels must avoid heap churn during FFT and matrix solves.
## Decision
Use `bumpalo::Bump` arena with explicit reset between simulation steps.
## Consequences
- Gate: `arena_reset_clears`
- Arena lifetimes must not escape FFI boundary
""",
)
w(
"docs/adr/0005-realtime-ring-buffer.md",
r"""# ADR-0005: Lock-free ring buffer for realtime streams
## Status
Accepted
## Context
PID waveform streaming must avoid mutex contention on the UI thread (PERF-09).
## Decision
LMAX-style `LockFreeRingBuffer` drains into align(64) `AlignedBuffer` for Dart zero-copy.
## Consequences
- API: `stream_pid_waveform` returns `BufferHandle`
- Gate: `ring_buffer_roundtrip`
""",
)
w(
"docs/adr/0006-onnx-stub.md",
r"""# ADR-0006: ONNX YOLOv8 motor plate stub
## Status
Accepted
## Context
Motor nameplate OCR will use YOLOv8 exported to ONNX; full runtime lands in phase 4.
## Decision
Ship `detect_motor_plate_stub` returning a fixed detection until ONNX Runtime is linked.
## Consequences
- Gate: `onnx_stub_returns_detection`
- FRB: `detect_motor_plate`
""",
)
w(
"docs/adr/0007-onnx-sld-rag.md",
r"""# ADR-0007: SLD parser and LanceDB RAG stubs
## Status
Accepted
## Context
SLD ingestion and knowledge-base queries require UTF-8 text graphs and vector search.
## Decision
- UTF-8 SLD line parser (`id:label`, `from->to`) with BOM trim
- LanceDB RAG stub with IEC 60909 short-circuit short-circuit
## Consequences
- Gates: `parse_simple_sld`, `rag_short_circuit_hit`
- UI: `/sld` SLD + RAG page
""",
)
w(
"docs/contracts/phase02-core-math.contract.toml",
r"""[contract]
name = "phase02-core-math"
phase = 2
[[evidence]]
id = "ik-formula"
kind = "cargo_test"
package = "azarakhsh_native"
filter = "ik_formula"
[[evidence]]
id = "pid-rk4"
kind = "cargo_test"
package = "azarakhsh_native"
filter = "pid_rk4_converges"
""",
)
w(
"docs/contracts/phase03-harmonics-cable.contract.toml",
r"""[contract]
name = "phase03-harmonics-cable"
phase = 3
[[evidence]]
id = "fft-hanning"
kind = "cargo_test"
package = "azarakhsh_native"
filter = "fft_hanning_gate"
[[evidence]]
id = "cable-xlpe"
kind = "cargo_test"
package = "azarakhsh_native"
filter = "cable_sizing_xlpe_90c"
""",
)
w(
"docs/contracts/phase04-realtime.contract.toml",
r"""[contract]
name = "phase04-realtime"
phase = 4
[[evidence]]
id = "ring-buffer"
kind = "cargo_test"
package = "azarakhsh_native"
filter = "ring_buffer_roundtrip"
[[evidence]]
id = "realtime-stream"
kind = "flutter_test"
filter = "realtime_stream_zero_copy"
""",
)
w(
"docs/contracts/phase05-onnx-sld-rag.contract.toml",
r"""[contract]
name = "phase05-onnx-sld-rag"
phase = 5
[[evidence]]
id = "onnx-stub"
kind = "cargo_test"
package = "azarakhsh_native"
filter = "onnx_stub_returns_detection"
[[evidence]]
id = "rag-hit"
kind = "cargo_test"
package = "azarakhsh_native"
filter = "rag_short_circuit_hit"
[[evidence]]
id = "sld-parse"
kind = "cargo_test"
package = "azarakhsh_native"
filter = "parse_simple_sld"
""",
)
w(
"docs/PHASE00.md",
r"""# Phase 00 — Monorepo scaffold
Deliverables: `azarakhsh_app`, `packages/azarakhsh_native`, ADR folder, analyze gate.
Evidence: `docs/contracts/phase00-scaffold.contract.toml`
""",
)
w(
"docs/PHASE01.md",
r"""# Phase 01 — Zero-copy FFI
Aligned buffers, NativeFinalizer, FRB buffer handles.
Evidence: `docs/contracts/phase01-ffi.contract.toml`
""",
)
w(
"docs/PHASE02.md",
r"""# Phase 02 — Core electrical math
IEC 60909 Ik, PID RK4, load-flow stubs.
Evidence: `docs/contracts/phase02-core-math.contract.toml`
""",
)
w(
"docs/PHASE03.md",
r"""# Phase 03 — Harmonics and cable sizing
IEEE 519 FFT gate, IEC 60364 cable sizing.
Evidence: `docs/contracts/phase03-harmonics-cable.contract.toml`
""",
)
w(
"docs/PHASE04.md",
r"""# Phase 04 — Realtime streaming
Lock-free ring buffer, PID waveform zero-copy stream.
Evidence: `docs/contracts/phase04-realtime.contract.toml`
""",
)
w(
"docs/PHASE05.md",
r"""# Phase 05 — ONNX, SLD, RAG
YOLOv8 ONNX stub, UTF-8 SLD parser, LanceDB RAG stub, `/sld` UI.
Evidence: `docs/contracts/phase05-onnx-sld-rag.contract.toml`
""",