This repository was archived by the owner on Sep 9, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchitty.js
More file actions
executable file
·1302 lines (1106 loc) · 35.5 KB
/
Copy pathchitty.js
File metadata and controls
executable file
·1302 lines (1106 loc) · 35.5 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
#!/usr/bin/env node
/**
* ChittyCLI - Unified Command-Line Client
* Enterprise Evidence Management with cutting-edge Cloudflare services
*/
import { Command } from "commander";
import chalk from "chalk";
import ora from "ora";
import Table from "cli-table3";
import inquirer from "inquirer";
import fs from "fs/promises";
import path from "path";
import crypto from "crypto";
import os from "os";
import dotenv from "dotenv";
// Load environment variables
dotenv.config();
const program = new Command();
// CLI Configuration
const CLI_VERSION = "ChittyOS Framework v1.0.0";
const API_BASE = process.env.CHITTY_API_BASE || "https://api.chittyos.com";
const API_KEY = process.env.CHITTY_API_KEY;
// Service configurations
const SERVICES = {
pipelines: {
validation: "chittyid-validation",
evidence: "evidence-processing",
monitoring: "real-time-monitoring",
litigation: "litigation-workflow",
},
containers: {
evidenceProcessor: "evidence-processor:latest",
aiAnalyzer: "ai-analyzer:gpu",
ocrProcessor: "ocr-processor:v2",
litigationPipeline: "litigation-pipeline:v1",
},
regions: {
us: "us-central1",
eu: "eu-west1",
apac: "asia-southeast1",
},
endpoints: {
chittyId: "https://id.chitty.cc/v1",
chittySchema: "https://schema.chitty.cc/api/v1",
chittyVerify: "https://verify.chitty.cc/api/v1",
chittyCheck: "https://check.chitty.cc/api/v1",
chittyRegistry: "https://registry.chitty.cc/api/v1",
},
};
// Utility functions
const logger = {
info: (msg) => console.log(chalk.blue("ℹ"), msg),
success: (msg) => console.log(chalk.green("✅"), msg),
warn: (msg) => console.log(chalk.yellow("⚠"), msg),
error: (msg) => console.log(chalk.red("❌"), msg),
debug: (msg) => process.env.DEBUG && console.log(chalk.gray("🐛"), msg),
};
// API client
class ChittyAPI {
constructor(baseUrl = API_BASE, apiKey = API_KEY) {
this.baseUrl = baseUrl;
this.apiKey = apiKey;
}
async request(endpoint, options = {}) {
const url = `${this.baseUrl}${endpoint}`;
const headers = {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
"User-Agent": `ChittyCLI/${CLI_VERSION}`,
...options.headers,
};
logger.debug(`${options.method || "GET"} ${url}`);
try {
const response = await fetch(url, {
...options,
headers,
});
if (!response.ok) {
const error = await response.text();
throw new Error(`API Error (${response.status}): ${error}`);
}
const contentType = response.headers.get("content-type");
if (contentType?.includes("application/json")) {
return await response.json();
}
return await response.text();
} catch (error) {
logger.error(`API request failed: ${error.message}`);
throw error;
}
}
// Evidence management
async uploadEvidence(file, chittyId, options = {}) {
const formData = new FormData();
const fileBuffer = await fs.readFile(file);
const blob = new Blob([fileBuffer]);
formData.append("file", blob, path.basename(file));
formData.append("chittyId", chittyId);
formData.append("metadata", JSON.stringify(options));
return await this.request("/api/v1/evidence/upload", {
method: "POST",
headers: {
Authorization: `Bearer ${this.apiKey}`,
},
body: formData,
});
}
// Pipeline operations
async triggerPipeline(pipelineType, data) {
return await this.request(`/api/v1/pipeline/${pipelineType}/trigger`, {
method: "POST",
body: JSON.stringify(data),
});
}
async getPipelineStatus(pipelineId) {
return await this.request(`/api/v1/pipeline/${pipelineId}/status`);
}
// Container processing
async processWithContainer(chittyId, file, processingType, options = {}) {
const formData = new FormData();
const fileBuffer = await fs.readFile(file);
const blob = new Blob([fileBuffer]);
formData.append("file", blob, path.basename(file));
formData.append("chittyId", chittyId);
formData.append("processingType", processingType);
formData.append("options", JSON.stringify(options));
return await this.request("/api/v1/container/process", {
method: "POST",
headers: {
Authorization: `Bearer ${this.apiKey}`,
},
body: formData,
});
}
// Browser rendering
async captureWebsite(chittyId, url, options = {}) {
return await this.request("/api/v1/capture/web", {
method: "POST",
body: JSON.stringify({
chittyId,
url,
options,
}),
});
}
// Image processing
async processImage(chittyId, imagePath, options = {}) {
const formData = new FormData();
const fileBuffer = await fs.readFile(imagePath);
const blob = new Blob([fileBuffer]);
formData.append("image", blob, path.basename(imagePath));
formData.append(
"metadata",
JSON.stringify({
chittyId,
...options,
}),
);
return await this.request("/api/v1/image/process", {
method: "POST",
headers: {
Authorization: `Bearer ${this.apiKey}`,
},
body: formData,
});
}
// Privacy protection
async protectPII(chittyId, data, options = {}) {
return await this.request("/api/v1/privacy/protect", {
method: "POST",
body: JSON.stringify({
chittyId,
data,
context: options,
}),
});
}
// Monitoring
async getMetrics(timeRange = "1h") {
return await this.request(`/api/v1/metrics?range=${timeRange}`);
}
async getHealth() {
return await this.request("/health");
}
}
const api = new ChittyAPI();
// ChittyID validation
function validateChittyID(chittyId) {
const pattern =
/^[0-9]{2}-[0-9]{1}-[A-Z]{3}-[0-9]{4}-[A-Z]{1}-[0-9]{6}-[0-9]{1}-[0-9]{1,2}$/;
return pattern.test(chittyId);
}
// §36 Compliance: ChittyID generation must use service - local generation removed
// Progress tracking
class ProgressTracker {
constructor() {
this.spinner = null;
this.steps = [];
this.current = 0;
}
start(message) {
this.spinner = ora(message).start();
}
step(message) {
if (this.spinner) {
this.spinner.text = message;
}
}
succeed(message) {
if (this.spinner) {
this.spinner.succeed(message);
this.spinner = null;
}
}
fail(message) {
if (this.spinner) {
this.spinner.fail(message);
this.spinner = null;
}
}
info(message) {
if (this.spinner) {
this.spinner.info(message);
} else {
logger.info(message);
}
}
}
// Command implementations
program
.name("chitty")
.description(
"ChittyOS Framework CLI - Unified Command-Line Client\nAlias: ccli",
)
.version(CLI_VERSION)
.option("--yes", "Auto-approve prompts")
.helpOption("-h, --help", "Show help");
// Evidence upload command
program
.command("upload")
.description("Upload evidence file with ChittyID")
.argument("<chittyId>", "ChittyID for the evidence")
.argument("<file>", "File path to upload")
.option(
"-t, --type <type>",
"Evidence type (document, image, video)",
"document",
)
.option("-r, --region <region>", "Storage region (us, eu, apac)", "us")
.option("--redact-pii", "Enable PII redaction")
.option("--ai-analysis", "Enable AI analysis")
.option(
"--priority <level>",
"Processing priority (low, normal, high)",
"normal",
)
.action(async (chittyId, file, options) => {
const progress = new ProgressTracker();
try {
// Validate ChittyID
if (!validateChittyID(chittyId)) {
logger.error("Invalid ChittyID format");
process.exit(1);
}
// Check file exists
try {
await fs.access(file);
} catch {
logger.error(`File not found: ${file}`);
process.exit(1);
}
progress.start("Uploading evidence...");
// Upload with options
const uploadOptions = {
type: options.type,
region: options.region,
redactPii: options.redactPii,
aiAnalysis: options.aiAnalysis,
priority: options.priority,
};
const result = await api.uploadEvidence(file, chittyId, uploadOptions);
progress.succeed(`Evidence uploaded successfully`);
// Display results
const table = new Table({
head: ["Property", "Value"],
style: { head: ["cyan"] },
});
table.push(
["ChittyID", result.chittyId],
["Evidence ID", result.evidenceId],
["File Hash", result.fileHash],
["Storage Region", options.region],
["Processing Status", result.status || "Queued"],
);
console.log(table.toString());
if (result.pipelineId) {
logger.info(`Processing pipeline started: ${result.pipelineId}`);
// Monitor pipeline if requested
if (options.aiAnalysis) {
progress.start("Running AI analysis...");
await monitorPipeline(result.pipelineId, progress);
}
}
} catch (error) {
progress.fail(`Upload failed: ${error.message}`);
process.exit(1);
}
});
// Web capture command
program
.command("capture")
.description("Capture web evidence")
.argument("<chittyId>", "ChittyID for the capture")
.argument("<url>", "URL to capture")
.option("--pdf", "Generate PDF")
.option("--full-page", "Full page screenshot")
.option("--viewport <size>", "Viewport size (WxH)", "1920x1080")
.option("--wait <ms>", "Wait time after load", "2000")
.action(async (chittyId, url, options) => {
const progress = new ProgressTracker();
try {
if (!validateChittyID(chittyId)) {
logger.error("Invalid ChittyID format");
process.exit(1);
}
// Parse viewport
const [width, height] = options.viewport.split("x").map(Number);
progress.start(`Capturing ${url}...`);
const captureOptions = {
includePdf: options.pdf,
viewport: { width, height },
waitTime: parseInt(options.wait),
fullPage: options.fullPage,
};
const result = await api.captureWebsite(chittyId, url, captureOptions);
progress.succeed("Web capture completed");
const table = new Table({
head: ["Property", "Value"],
style: { head: ["cyan"] },
});
table.push(
["ChittyID", chittyId],
["Evidence ID", result.evidenceId],
["URL", url],
["Screenshot Size", `${(result.screenshotSize / 1024).toFixed(1)} KB`],
[
"PDF Size",
result.pdfSize ? `${(result.pdfSize / 1024).toFixed(1)} KB` : "N/A",
],
["Metadata", `${Object.keys(result.metadata).length} fields`],
);
console.log(table.toString());
} catch (error) {
progress.fail(`Capture failed: ${error.message}`);
process.exit(1);
}
});
// Container processing command
program
.command("process")
.description("Process evidence with containers")
.argument("<chittyId>", "ChittyID for processing")
.argument("<file>", "File to process")
.option(
"-t, --type <type>",
"Processing type (ocr, ai-analysis, pdf-extract)",
"ai-analysis",
)
.option("--gpu", "Use GPU acceleration")
.option("--cpu <cores>", "CPU cores", "2")
.option("--memory <size>", "Memory limit", "2Gi")
.option("--redact-pii", "Enable PII redaction")
.option("--timeout <seconds>", "Processing timeout", "300")
.action(async (chittyId, file, options) => {
const progress = new ProgressTracker();
try {
if (!validateChittyID(chittyId)) {
logger.error("Invalid ChittyID format");
process.exit(1);
}
try {
await fs.access(file);
} catch {
logger.error(`File not found: ${file}`);
process.exit(1);
}
progress.start("Starting container processing...");
const processOptions = {
gpu: options.gpu,
resources: {
cpu: options.cpu,
memory: options.memory,
},
redactPii: options.redactPii,
timeout: parseInt(options.timeout) * 1000,
};
const result = await api.processWithContainer(
chittyId,
file,
options.type,
processOptions,
);
progress.succeed("Container processing completed");
const table = new Table({
head: ["Property", "Value"],
style: { head: ["cyan"] },
});
table.push(
["ChittyID", chittyId],
["Execution ID", result.executionId],
["Processing Type", options.type],
["Status", result.status],
["Processing Time", `${result.processingTime}ms`],
[
"Resources Used",
`${result.resourceUsage?.cpu || "N/A"} CPU, ${result.resourceUsage?.memory || "N/A"} Memory`,
],
);
console.log(table.toString());
if (result.output) {
logger.info("Processing Results:");
console.log(JSON.stringify(result.output, null, 2));
}
} catch (error) {
progress.fail(`Processing failed: ${error.message}`);
process.exit(1);
}
});
// Pipeline management commands
program.command("pipeline").description("Pipeline management commands");
// Litigation workflow commands - §36 compliant
program
.command("litigation")
.description("Litigation workflow management (§36 compliant)");
program
.command("litigation:ingest")
.description("Ingest evidence following §36 architecture")
.argument("<file>", "Evidence file path")
.option("-p, --places <places>", "Comma-separated places")
.option("-r, --properties <properties>", "Comma-separated properties")
.option("--case-id <caseId>", "Associated case ChittyID")
.action(async (file, options) => {
const progress = new ProgressTracker();
try {
progress.start("Starting §36 evidence ingestion...");
// Dynamic import of the evidence pipeline
const { EvidenceIngestionPipeline } = await import(
"./evidence-ingestion.js"
);
const pipeline = new EvidenceIngestionPipeline();
const meta = {
places: options.places ? options.places.split(",") : [],
properties: options.properties ? options.properties.split(",") : [],
caseId: options.caseId,
};
const result = await pipeline.ingestEvidence(file, meta);
progress.succeed("Evidence ingested successfully");
const table = new Table({
head: ["Property", "Value"],
colWidths: [20, 50],
});
table.push(
["ChittyID", result.chitty_id],
["Verify Status", result.verify.status || "unknown"],
["Compliance Score", result.compliance.score || "unknown"],
["Trust Score", result.verify.trust_score || "unknown"],
);
console.log(table.toString());
} catch (error) {
progress.fail(`Evidence ingestion failed: ${error.message}`);
process.exit(1);
}
});
program
.command("litigation:validate")
.description("Validate evidence chain integrity")
.argument("<chittyId>", "Evidence ChittyID")
.action(async (chittyId) => {
const progress = new ProgressTracker();
try {
if (!validateChittyID(chittyId)) {
logger.error("Invalid ChittyID format");
process.exit(1);
}
progress.start("Validating evidence chain...");
// Call ChittyVerify service
const response = await fetch(
`${SERVICES.endpoints.chittyVerify}/evidence/verify`,
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.CHITTY_VERIFY_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ chitty_id: chittyId }),
},
);
if (!response.ok) {
throw new Error(`Verification failed: ${response.status}`);
}
const result = await response.json();
progress.succeed("Evidence validation complete");
const table = new Table({
head: ["Check", "Status", "Score"],
colWidths: [25, 15, 10],
});
table.push(
[
"Integrity",
result.integrity || "unknown",
result.integrity_score || "N/A",
],
[
"Custody Chain",
result.custody || "unknown",
result.custody_score || "N/A",
],
[
"Authenticity",
result.authenticity || "unknown",
result.auth_score || "N/A",
],
[
"Overall Trust",
result.status || "unknown",
result.trust_score || "N/A",
],
);
console.log(table.toString());
} catch (error) {
progress.fail(`Validation failed: ${error.message}`);
process.exit(1);
}
});
program
.command("litigation:case")
.description("Create new legal case")
.option("-t, --title <title>", "Case title")
.option("-d, --description <description>", "Case description")
.option("-j, --jurisdiction <jurisdiction>", "Legal jurisdiction")
.option("-c, --court <court>", "Court identifier")
.action(async (options) => {
const progress = new ProgressTracker();
try {
progress.start("Creating legal case...");
// Request ChittyID for the case
const idResponse = await fetch(`${SERVICES.endpoints.chittyId}/mint`, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.CHITTY_ID_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ domain: "legal", subtype: "case" }),
});
if (!idResponse.ok) {
throw new Error(`ChittyID service error: ${await idResponse.text()}`);
}
const { chitty_id } = await idResponse.json();
// Store case via ChittySchema
const caseData = {
chitty_id,
title: options.title || "Untitled Case",
description: options.description || "",
jurisdiction: options.jurisdiction || "",
court: options.court || "",
created_at: new Date().toISOString(),
status: "active",
};
const storeResponse = await fetch(
`${SERVICES.endpoints.chittySchema}/store/case`,
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.CHITTY_ID_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify(caseData),
},
);
progress.succeed("Legal case created successfully");
logger.info(`Case ChittyID: ${chitty_id}`);
logger.info(`Title: ${caseData.title}`);
logger.info(`Jurisdiction: ${caseData.jurisdiction}`);
} catch (error) {
progress.fail(`Case creation failed: ${error.message}`);
process.exit(1);
}
});
program
.command("pipeline:trigger")
.description("Trigger a processing pipeline")
.argument("<type>", "Pipeline type (validation, evidence, monitoring)")
.argument("<chittyId>", "ChittyID to process")
.option("-d, --data <data>", "Additional data (JSON string)")
.action(async (type, chittyId, options) => {
const progress = new ProgressTracker();
try {
if (!validateChittyID(chittyId)) {
logger.error("Invalid ChittyID format");
process.exit(1);
}
progress.start(`Triggering ${type} pipeline...`);
const data = {
chittyId,
...(options.data ? JSON.parse(options.data) : {}),
};
const result = await api.triggerPipeline(type, data);
progress.succeed("Pipeline triggered successfully");
logger.info(`Pipeline ID: ${result.pipelineId}`);
logger.info(`Status: ${result.status}`);
if (result.estimatedDuration) {
logger.info(`Estimated duration: ${result.estimatedDuration}ms`);
}
} catch (error) {
progress.fail(`Pipeline trigger failed: ${error.message}`);
process.exit(1);
}
});
program
.command("pipeline:status")
.description("Check pipeline status")
.argument("<pipelineId>", "Pipeline ID")
.option("-w, --watch", "Watch for status changes")
.action(async (pipelineId, options) => {
try {
if (options.watch) {
await watchPipelineStatus(pipelineId);
} else {
const status = await api.getPipelineStatus(pipelineId);
displayPipelineStatus(status);
}
} catch (error) {
logger.error(`Status check failed: ${error.message}`);
process.exit(1);
}
});
// Image processing command
program
.command("image")
.description("Process images with variants and OCR")
.argument("<chittyId>", "ChittyID for the image")
.argument("<image>", "Image file path")
.option(
"--variants <types>",
"Image variants (thumbnail,display,evidence)",
"thumbnail,display",
)
.option("--ocr", "Extract text with OCR")
.option("--redact <areas>", "Redaction areas (JSON array)")
.action(async (chittyId, image, options) => {
const progress = new ProgressTracker();
try {
if (!validateChittyID(chittyId)) {
logger.error("Invalid ChittyID format");
process.exit(1);
}
try {
await fs.access(image);
} catch {
logger.error(`Image not found: ${image}`);
process.exit(1);
}
progress.start("Processing image...");
const processOptions = {
variants: options.variants.split(","),
ocr: options.ocr,
redactionAreas: options.redact ? JSON.parse(options.redact) : null,
requiresRedaction: !!options.redact,
};
const result = await api.processImage(chittyId, image, processOptions);
progress.succeed("Image processing completed");
const table = new Table({
head: ["Property", "Value"],
style: { head: ["cyan"] },
});
table.push(
["ChittyID", chittyId],
["Image ID", result.imageId],
["Delivery URL", result.deliveryUrl],
["Variants", Object.keys(result.variants).join(", ")],
["OCR Extracted", result.ocrText ? "Yes" : "No"],
);
console.log(table.toString());
if (result.ocrText) {
logger.info("Extracted Text:");
console.log(result.ocrText);
}
} catch (error) {
progress.fail(`Image processing failed: ${error.message}`);
process.exit(1);
}
});
// Privacy protection command
program
.command("protect")
.description("Protect PII in documents")
.argument("<chittyId>", "ChittyID for the data")
.argument("<file>", "File to protect")
.option("--mode <mode>", "Redaction mode (mask, tokenize, hash)", "mask")
.option(
"--types <types>",
"PII types to detect",
"ssn,credit_card,email,phone",
)
.option("--output <file>", "Output file path")
.action(async (chittyId, file, options) => {
const progress = new ProgressTracker();
try {
if (!validateChittyID(chittyId)) {
logger.error("Invalid ChittyID format");
process.exit(1);
}
const data = await fs.readFile(file, "utf8");
progress.start("Detecting and protecting PII...");
const protectionOptions = {
redactionMode: options.mode,
dataId: chittyId,
detectionTypes: options.types.split(","),
};
const result = await api.protectPII(chittyId, data, protectionOptions);
progress.succeed("PII protection completed");
const table = new Table({
head: ["Property", "Value"],
style: { head: ["cyan"] },
});
table.push(
["ChittyID", chittyId],
["PII Detected", result.piiDetected],
["Audit ID", result.auditId],
["Compliance Status", result.complianceStatus],
["Redaction Mode", options.mode],
);
console.log(table.toString());
// Save protected data
const outputFile = options.output || `${file}.protected`;
await fs.writeFile(outputFile, result.redactedData);
logger.success(`Protected data saved to: ${outputFile}`);
} catch (error) {
progress.fail(`PII protection failed: ${error.message}`);
process.exit(1);
}
});
// Monitoring commands
program
.command("status")
.description("Check system health and status")
.option("-d, --detailed", "Show detailed status")
.action(async (options) => {
const progress = new ProgressTracker();
try {
progress.start("Checking system health...");
const health = await api.getHealth();
progress.succeed("Health check completed");
// Overall status
const statusColor =
health.overall.status === "healthy"
? "green"
: health.overall.status === "degraded"
? "yellow"
: "red";
console.log(
`\nSystem Status: ${chalk[statusColor](health.overall.status.toUpperCase())}`,
);
console.log(
`Operational Services: ${health.overall.operationalServices}/${health.overall.totalServices} (${health.overall.percentage.toFixed(1)}%)`,
);
// Services table
if (options.detailed) {
const servicesTable = new Table({
head: ["Service", "Status", "Circuit Breaker"],
style: { head: ["cyan"] },
});
Object.entries(health.services).forEach(([name, service]) => {
const statusText =
service.status === "healthy"
? chalk.green("Healthy")
: chalk.red("Unhealthy");
const cbText =
service.circuitBreaker === "closed"
? chalk.green("Closed")
: chalk.red(service.circuitBreaker);
servicesTable.push([name, statusText, cbText]);
});
console.log("\nServices:");
console.log(servicesTable.toString());
// Storage status
const storageTable = new Table({
head: ["Storage", "Status"],
style: { head: ["cyan"] },
});
Object.entries(health.storage).forEach(([name, storage]) => {
const statusText = storage.healthy
? chalk.green("Healthy")
: chalk.red("Unhealthy");
storageTable.push([name.toUpperCase(), statusText]);
});
console.log("\nStorage:");
console.log(storageTable.toString());
}
} catch (error) {
progress.fail(`Health check failed: ${error.message}`);
process.exit(1);
}
});
program
.command("metrics")
.description("View system metrics")
.option("-r, --range <range>", "Time range (1h, 24h, 7d)", "1h")
.action(async (options) => {
const progress = new ProgressTracker();
try {
progress.start("Fetching metrics...");
const metrics = await api.getMetrics(options.range);
progress.succeed("Metrics retrieved");
const table = new Table({
head: ["Metric", "Value"],
style: { head: ["cyan"] },
});
table.push(
["Total Requests", metrics.summary.totalRequests.toLocaleString()],
["Total Errors", metrics.summary.totalErrors.toLocaleString()],
["Average Latency", `${metrics.summary.averageLatency}ms`],
[
"Error Rate",
`${((metrics.summary.totalErrors / metrics.summary.totalRequests) * 100).toFixed(2)}%`,
],
);
console.log(`\nMetrics (${options.range}):`);
console.log(table.toString());
// Service metrics
if (metrics.summary.services) {
const serviceTable = new Table({
head: ["Service", "Success", "Failure", "Success Rate"],
style: { head: ["cyan"] },
});
Object.entries(metrics.summary.services).forEach(([name, service]) => {
const total = service.success + service.failure;
const successRate =
total > 0 ? ((service.success / total) * 100).toFixed(1) : "0.0";
serviceTable.push([
name,
service.success.toLocaleString(),
service.failure.toLocaleString(),
`${successRate}%`,
]);