systemg 0.33.0

A simple process manager.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
# SystemG UI — Lightweight Dashboard Spec

## Overview

A clever, static web dashboard for [systemg](https://github.com/ra0x3/systemg) that reads state directly from disk. No backend, no server—just a static HTML file that polls sysg's existing state files.

Open `index.html`, point it at your `~/.systemg` directory, and watch your processes in real-time.

---

## Important: Branch Requirement

**Branch ownership sits with the Team Lead.** The repo does not mandate a
specific branch name.

- At kickoff, the Owner records the current branch under
  `./snapshots/active_branch`.
- The Team Lead updates that file whenever they change the base branch,
  communicating the change in status updates.
- All other agents read the file and check out the recorded branch before
  working:
  ```bash
  ACTIVE_BRANCH=$(cat ./snapshots/active_branch)
  git checkout "$ACTIVE_BRANCH"
  ```

Feature branches (`feature/<area>-<slug>`) should be cut from the recorded
branch and merged back into it. If the branch does not exist locally, create it
with `git checkout -B "$ACTIVE_BRANCH"`.

---

## Implementation

### Team Roles & Responsibilities

#### Team Lead
**Primary responsibility**: Code review, repository management, and final integration

**Tasks**:
- Review all PRs from developers before merging
- Perform final code commits to main branch
- Ensure code quality standards (TypeScript strict mode, no any types)
- Coordinate between team members
- Make architectural decisions when conflicts arise
- Deploy production build to CDN/static hosting
- Enforce poller performance budgets (single-flight reads, 1 s steady-state cadence, exponential backoff on errors)
- Guard data hygiene (only sanitized env data in Redux, verify log truncation caps are honoured)
- Ensure all bot commits use `git commit -m "<msg>" --author="systemg-bot <systemg-bot@users.noreply.github.com>"`
- Require pushes via `git push https://systemg-bot:$YOUR_PAT@github.com/ra0x3/systemg.git` (PAT pulled from `.env`)
- Track token spend; block changes that increase prompt length needlessly

**Deliverables**:
- Approved and merged code
- Production releases
- Architecture decision records that document polling safeguards, sanitization points, and fallback flows
- Weekly token usage summaries shared with OWNER

#### Individual Contributors (Frontend Dev)
**Primary responsibility**: Implement UI components and core functionality

**Dev 1 - Core Infrastructure**:
- Set up Vite project with React 18 + TypeScript
- Implement Redux store with slices that only persist sanitized data
- Build the single-flight File API poller (no overlapping reads, exponential backoff, cached `lastModified`)
- Ship browser compatibility + manual snapshot fallback (unsupported browsers upload tarball from `systemg export`)
- Implement data transformation utilities and worker-based reducers for heavy JSON shaping
- Persist log offsets/metrics history in IndexedDB without leaking secrets

**Dev 2 - UI Components**:
- Build dashboard layout with Chakra UI
- Create process tree visualization
- Implement log viewer with virtual scrolling + chunked streaming (respect 1 MiB cap, show truncation warnings)
- Build ASCII sparkline charts for metrics backed by down-sampled worker data
- Add keyboard navigation (vim bindings)
- Surface polling/compatibility states (unsupported browser warning, degraded snapshot mode banner)

**Dev 3 - Features & Polish**:
- Implement search/filter functionality
- Add config viewer with syntax highlighting
- Create cron job scheduler view
- Build export functionality (CSV/JSON) that respects sanitization and truncation rules
- Implement dark/light theme toggle and remember preference without bloating prompts/config
- Instrument telemetry for polling duration, skipped snapshots, and token usage summaries surfaced to the Team Lead dashboard

**Submission process**:
1. Create feature branch from main (no direct commits to main)
2. Implement assigned features while enforcing poller guardrails, sanitization, and token-conscious copy
3. Run `npm run lint && npm run type-check && npm run test && npm run build`
4. Write unit/integration tests (≥80% coverage) covering happy path + failure modes (partial write, unsupported browser)
5. Commit with `git commit -m "<type>: <summary>" --author="systemg-bot <systemg-bot@users.noreply.github.com>"`
6. Push with `git push https://systemg-bot:$YOUR_PAT@github.com/ra0x3/systemg.git` (pull `$YOUR_PAT` from repo `.env`)
7. Submit code to QA for testing and respond to issues
8. Hand off to Team Lead for final review/merge once QA signs off

#### QA Tester
**Primary responsibility**: Validate functionality and ensure quality

**Test scenarios**:
- File API compatibility (Chrome/Edge happy path, Safari/Firefox fallback to manual snapshot upload)
- State polling performance with large datasets (1000+ processes, 10MB metrics blobs)
- UI responsiveness and frame budget while regex-searching 1 MiB log slices
- Memory usage during 1 hr sessions; ensure log truncation caps hold
- Error states (missing files, partial writes, permission denied, corrupt JSON)
- Keyboard navigation accessibility and screen reader announcements
- Token usage telemetry surfaces accurate counts to the Team Lead dashboard

**Process**:
1. Receive code from developers
2. Run test suite (unit + integration)
3. Perform manual testing per test plan
4. Document bugs with reproduction steps
5. Return to dev if issues found
6. Approve for Team Lead review when passing

**Testing checklist**:
- [ ] `npm run lint`, `type-check`, `test`, and `build` succeed
- [ ] No console errors in production build or worker threads
- [ ] File picker + manual snapshot fallback behave per spec
- [ ] Polling recovers after forced partial writes, file rotations, and permission changes
- [ ] UI updates reflect state changes without skipped frames (>55fps under load)
- [ ] Keyboard shortcuts and ARIA labels meet accessibility requirements
- [ ] Export/download functions respect sanitization + truncation
- [ ] Memory stays < 250 MB in Chrome Task Manager after 1 hr session
- [ ] Token usage estimates log to the Team Lead dashboard after each run

### Development Timeline

**Week 1**: Foundation
- Mon-Tue: Project setup, Redux store with sanitized slices (Dev 1)
- Wed: Implement single-flight poller + error backoff (Dev 1)
- Thu: Manual snapshot fallback + browser support matrix (Dev 1)
- Fri: Basic dashboard shell + compatibility banners (Dev 2)

**Week 2**: Core Features
- Mon: Process list & tree view with streaming updates (Dev 2)
- Tue: Log viewer chunked streaming + truncation warnings (Dev 2)
- Wed: Metrics worker + ASCII charts (Dev 3)
- Thu: Search/filter + config viewer w/ sanitization badges (Dev 3)
- Fri: Telemetry pipeline for polling stats & token usage (Dev 3)

**Week 3**: Polish & Testing
- Mon: Keyboard navigation, accessibility, theming (Dev 3)
- Tue: Export flows (CSV/JSON) with sanitization gates (Dev 3)
- Wed-Thu: QA sweep (performance, fallback, accessibility)
- Fri: Bug fixes + Team Lead dry run with token budget review

**Week 4**: Release
- Mon: Final QA pass on release candidate
- Tue: Production build optimization + bundle size audit
- Wed: Documentation updates (README, troubleshooting, manual snapshot guide)
- Thu: Deployment to static host + smoke test
- Fri: Launch + retro on performance budgets/token spend

---

## Design Philosophy

### Visual Direction
- **Clean & minimal** — focus on the data, not the chrome
- **Hacker aesthetic** — monospace fonts, ASCII art where it makes sense
- **Fast & responsive** — instant updates, no loading spinners
- **Dark mode by default** — easy on the eyes

### UX Philosophy
- **Zero friction** — open file, select directory, done
- **Glanceable status** — understand what's running instantly
- **Real-time** — poll state files every second
- **Keyboard-first** — vim-style shortcuts for power users

---

## Technical Stack

| Layer | Technology |
|-------|------------|
| Framework | React 18 + TypeScript |
| UI Library | Chakra UI (minimal theme) |
| Icons | Lucide React |
| State | Redux Toolkit |
| Data | File API (reads ~/.systemg/*) |
| Build | Vite |
| Backend | NONE - static HTML only |

---

## How It Works (No Backend!)

### SystemG Already Writes Everything We Need
SystemG continuously writes state to disk:
- `~/.systemg/state/supervisor.pid` - Daemon PID
- `~/.systemg/state/services.state` - Service states (JSON)
- `~/.systemg/state/cron.state` - Cron job states (JSON)
- `~/.systemg/logs/*.log` - Service logs
- `~/.systemg/metrics/*` - Performance metrics

### File API Polling
```typescript
// User selects their systemg directory
const dirHandle = await window.showDirectoryPicker();

const refreshIntervalMs = 1000;
let pollInFlight = false;
let pollTimer: number | undefined;
const lastSeenVersion = new Map<string, number>();

async function pollState() {
  if (pollInFlight) return; // never queue overlapping reads
  pollInFlight = true;

  try {
    const servicesHandle = await dirHandle.getFileHandle('state/services.state');
    const servicesFile = await servicesHandle.getFile();

    const servicesVersion = servicesFile.lastModified;
    if (lastSeenVersion.get('services') !== servicesVersion) {
      lastSeenVersion.set('services', servicesVersion);

      const servicesText = await servicesFile.text();
      const parsedServices = safeJsonParse(servicesText);

      if (parsedServices) {
        dispatch(updateServices(sanitizeServices(parsedServices)));
      }
    }
  } catch (error) {
    console.error('Polling error', error);
    dispatch(setPollingError(toPollingMessage(error)));
  } finally {
    pollInFlight = false;
    pollTimer = window.setTimeout(pollState, refreshIntervalMs);
  }
}

pollState();
```

```typescript
function safeJsonParse<T>(raw: string): T | null {
  try {
    return JSON.parse(raw) as T;
  } catch (error) {
    // Partial writes happen when systemg rewrites the file while we read it.
    // Retry on the next poll instead of crashing the UI.
    console.warn('Skipping malformed JSON snapshot', error);
    return null;
  }
}
```

**Polling guardrails**
- Always gate the poller with `pollInFlight` (or an `AbortController`) so large datasets cannot queue overlapping reads that hammer disk I/O.
- Cache the last `File.lastModified` (or a hash of the contents) and short-circuit unchanged snapshots—this keeps CPU usage low when nothing changes.
- Run sanitization before dispatching to Redux so sensitive environment variables never enter long-lived state; only short-lived local variables may touch raw values.
- On component unmount call `window.clearTimeout(pollTimer)` to stop polling immediately.
- When the browser throttles background tabs, back off by increasing `refreshIntervalMs` to avoid starving the main thread.

### Large snapshot handling
- Keep a per-file offset map for logs and metrics (`Map<string, number>`). Call `File.slice(offset)` so you only read the appended chunk instead of re-downloading multi-megabyte files.
- Cap log payloads: when a file grows beyond ~1 MiB, read only the trailing window and surface a UI hint that older lines were truncated for performance.
- Defer heavy parsing (`JSON.parse`, YAML highlighting) onto a `worker` when payloads exceed 256 KiB to prevent janking the main thread.
- Use `navigator.storage.estimate()` to detect when the browser sandbox is low on quota and prompt the user to clean up before continuing to stream logs.
- Persist the offset/state map in `IndexedDB` so reloads resume without hammering the filesystem.

### Redux State Shape
```typescript
interface SystemGState {
  services: ServiceState[];
  supervisor: SupervisorInfo;
  cron: CronJobState[];
  logs: LogEntry[];
  metrics: MetricsData;
  lastPoll: number;
}
```

---

## Core Features

### 1. Main Dashboard

Simple overview showing:
- **Process count** — How many things are running
- **CPU/Memory** — Total usage across all processes
- **Supervisor status** — Is sysg daemon alive?
- **Recent crashes** — Last 5 failed processes
- **Cron jobs** — Next scheduled runs

Components:
- `<QuickStats />` — Big numbers that matter
- `<ProcList />` — Flat list of all processes
- `<CronNext />` — What's running soon

---

### 2. Process Tree

Visual tree of processes and their spawn children:
- **PID & name** — Basic identifiers
- **Status indicator** — Green/red/yellow dots
- **CPU/Memory** — Live usage
- **Spawn children** — Nested tree view
- **Uptime** — How long it's been running

Interactions (READ-ONLY since we can't send commands):
- Click to expand/collapse children
- Double-click to see details
- Keyboard navigation (j/k vim-style)

---

### 3. Process Details

Click a process to see:
- **Command** — What's actually running
- **Sanitized environment** — Masked env vars only; raw values never leave the polling worker
- **Resource limits** — Configured limits
- **ASCII metrics** — CPU/Memory sparklines
- **Recent logs** — Last 100 lines
- **Exit codes** — History of crashes

---

### 4. Log Tail

Real-time log viewer:
- **Tail -f style** — Auto-scroll as new lines come in
- **Multiple streams** — stdout/stderr/supervisor
- **Search** — Regex search through logs
- **Jump to timestamp** — Navigate by time
- **Chunked reads** — Stream only appended data; cap payloads to prevent main-thread stalls

Implementation notes:
- Maintain a `Map<string, number>` of byte offsets per log file and call `file.slice(offset)`; skip work entirely if `file.size === offset`.
- Drop back to a worker thread (`Worker` + `TextDecoderStream`) for regex searching so the UI thread stays responsive during large scans.
- Apply sanitization before logs touch Redux; keep only the last 10 000 lines and expose a "download full log" action that uses the File API stream.

---

### 5. Config Viewer

Since we're read-only, show the current YAML config:
- **Syntax highlighting** — Colored YAML
- **Search** — Find services quickly
- **Copy button** — Copy config snippets
- **Validation indicators** — Show if config is valid

---

### 6. Metrics

Simple performance graphs:
- **ASCII charts** — Terminal-style graphs
- **CPU/Memory over time** — Last hour
- **Top consumers** — Which processes are hungry
- **Export** — Download as CSV

Implementation notes:
- Down-sample high-frequency metrics to 1 Hz before rendering; anything higher floods React with updates.
- Perform aggregation in a Web Worker so number crunching never blocks the main UI thread.
- Store only the past hour (3 600 points) in Redux and persist longer histories in IndexedDB for opt-in deep dives.

---

### 7. Cron Jobs

View scheduled tasks:
- **Next runs** — When stuff will execute
- **Last runs** — Recent execution history
- **Status** — Success/failure indicators

---

## Data Model

```typescript
// Complete type definitions for the SystemG UI

// Service/Process types
interface Process {
  name: string;
  pid: number;
  status: 'running' | 'stopped' | 'crashed' | 'starting' | 'stopping';
  command: string;
  startedAt: string;
  exitCode?: number;
  restartCount: number;

  // Resources
  cpuPercent: number;
  memoryMB: number;
  memoryLimit?: number;
  cpuLimit?: number;

  // Spawn tree
  parentPid?: number;
  children: Process[];

  // Configuration (sanitized before storing in Redux)
  sanitizedEnv: Record<string, string>;
  workDir: string;
  user?: string;
}

// Cron job definition
interface CronJob {
  id: string;
  name: string;
  schedule: string;
  command: string;
  lastRun?: {
    timestamp: string;
    exitCode: number;
    duration: number;
  };
  nextRun: string;
  status: 'active' | 'disabled' | 'running';
  failureCount: number;
}

// Log entry structure
interface LogLine {
  timestamp: string;
  level: 'debug' | 'info' | 'warn' | 'error';
  service: string;
  message: string;
  stream: 'stdout' | 'stderr' | 'supervisor';
}

// Metrics data point
interface MetricsData {
  timestamp: number;
  services: {
    [serviceName: string]: {
      cpu: number[];  // Time series data
      memory: number[];  // Time series data
      restarts: number;
      uptime: number;
    };
  };
  system: {
    totalCpu: number;
    totalMemory: number;
    loadAverage: [number, number, number];
  };
}

// Supervisor state
interface SupervisorInfo {
  pid: number;
  uptime: number;
  version: string;
  configPath: string;
  stateDir: string;
  logDir: string;
  startedAt: string;
}

// Service state from disk
interface ServiceState {
  name: string;
  pid?: number;
  status: string;
  exitCode?: number;
  startedAt?: string;
  stoppedAt?: string;
  restartCount: number;
  errorMessage?: string;
}

// Complete Redux state shape
interface SystemGState {
  // Core data
  services: Process[];
  supervisor: SupervisorInfo | null;
  cron: CronJob[];
  logs: LogLine[];
  metrics: MetricsData | null;

  // UI state
  selectedService: string | null;
  searchTerm: string;
  logFilter: 'all' | 'stdout' | 'stderr' | 'supervisor';
  timeWindow: '1h' | '6h' | '24h' | '7d';

  // System state
  lastPoll: number;
  pollingError: string | null;
  isPolling: boolean;
  directoryHandle: FileSystemDirectoryHandle | null;

  // User preferences
  theme: 'dark' | 'light';
  autoScroll: boolean;
  showMetrics: boolean;
  refreshInterval: number;
}

// Error types
interface SystemGError {
  type: 'FILE_ACCESS' | 'PARSE_ERROR' | 'PERMISSION_DENIED' | 'NOT_FOUND';
  message: string;
  timestamp: number;
  recoverable: boolean;
}
```

---

## Implementation

### Quick Start

```bash
# Build it
npm run build

# Open in browser
open dist/index.html

# Select your ~/.systemg directory when prompted
# Watch your processes!
```

### Browser Compatibility Check

```typescript
// browserCompat.ts
export interface FileApiSupport {
  supported: boolean;
  reason?: string;
}

export function checkFileAPISupport(): FileApiSupport {
  if (!('showDirectoryPicker' in window)) {
    return {
      supported: false,
      reason: 'File System Access API missing (Safari, Firefox ESR, hardened Chromium).',
    };
  }

  // Check for secure context (HTTPS or localhost)
  if (!window.isSecureContext) {
    return {
      supported: false,
      reason: 'Secure context required—serve over https:// or run on localhost.',
    };
  }

  return { supported: true };
}

export function getBrowserInfo() {
  const ua = navigator.userAgent;
  const fileApi = checkFileAPISupport();

  return {
    isChrome: /Chrome/.test(ua) && !/Edge/.test(ua),
    isFirefox: /Firefox/.test(ua),
    isSafari: /Safari/.test(ua) && !/Chrome/.test(ua),
    fileApi,
  };
}
```

- Support matrix: Chrome/Edge/Opera ≥ 86 fully support the File System Access API. Firefox, Brave in Tor mode, and Safari require a fallback flow (prompt users to upload a tarball generated by `systemg export`).
- Block the UI when `fileApi.supported` is `false` and surface `fileApi.reason`; otherwise users will interact with a broken dashboard without feedback.
- Offer a "manual snapshot" mode that accepts zipped state bundles so unsupported browsers still have read-only diagnostics.

### Redux Store Setup

```typescript
// store.ts
import { configureStore, createSlice, PayloadAction } from '@reduxjs/toolkit';
import type { SystemGState, Process, CronJob, LogLine, MetricsData, SupervisorInfo } from './types';

// Services slice
const servicesSlice = createSlice({
  name: 'services',
  initialState: [] as Process[],
  reducers: {
    updateServices: (state, action: PayloadAction<Process[]>) => action.payload,
    updateServiceStatus: (state, action: PayloadAction<{name: string; status: Process['status']}>) => {
      const service = state.find(s => s.name === action.payload.name);
      if (service) service.status = action.payload.status;
    },
  },
});

// Cron slice
const cronSlice = createSlice({
  name: 'cron',
  initialState: [] as CronJob[],
  reducers: {
    updateCron: (state, action: PayloadAction<CronJob[]>) => action.payload,
  },
});

// Logs slice
const logsSlice = createSlice({
  name: 'logs',
  initialState: [] as LogLine[],
  reducers: {
    appendLogs: (state, action: PayloadAction<LogLine[]>) => {
      // Keep only last 10000 lines for performance
      return [...state, ...action.payload].slice(-10000);
    },
    clearLogs: () => [],
  },
});

// Metrics slice
const metricsSlice = createSlice({
  name: 'metrics',
  initialState: null as MetricsData | null,
  reducers: {
    updateMetrics: (state, action: PayloadAction<MetricsData>) => action.payload,
  },
});

// System slice for UI and polling state
const systemSlice = createSlice({
  name: 'system',
  initialState: {
    supervisor: null as SupervisorInfo | null,
    lastPoll: 0,
    pollingError: null as string | null,
    isPolling: false,
    directoryHandle: null as FileSystemDirectoryHandle | null,
    selectedService: null as string | null,
    searchTerm: '',
    logFilter: 'all' as SystemGState['logFilter'],
    timeWindow: '1h' as SystemGState['timeWindow'],
    theme: 'dark' as SystemGState['theme'],
    autoScroll: true,
    showMetrics: true,
    refreshInterval: 1000,
  },
  reducers: {
    updateSupervisor: (state, action: PayloadAction<SupervisorInfo>) => {
      state.supervisor = action.payload;
    },
    setPollingError: (state, action: PayloadAction<string | null>) => {
      state.pollingError = action.payload;
    },
    setIsPolling: (state, action: PayloadAction<boolean>) => {
      state.isPolling = action.payload;
    },
    setDirectoryHandle: (state, action: PayloadAction<FileSystemDirectoryHandle | null>) => {
      state.directoryHandle = action.payload;
    },
    selectService: (state, action: PayloadAction<string | null>) => {
      state.selectedService = action.payload;
    },
    setSearchTerm: (state, action: PayloadAction<string>) => {
      state.searchTerm = action.payload;
    },
    setLogFilter: (state, action: PayloadAction<SystemGState['logFilter']>) => {
      state.logFilter = action.payload;
    },
    updateLastPoll: (state) => {
      state.lastPoll = Date.now();
    },
  },
});

// Configure store with all slices
export const store = configureStore({
  reducer: {
    services: servicesSlice.reducer,
    cron: cronSlice.reducer,
    logs: logsSlice.reducer,
    metrics: metricsSlice.reducer,
    system: systemSlice.reducer,
  },
  // Handle non-serializable FileSystemDirectoryHandle
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: ['system/setDirectoryHandle'],
        ignoredPaths: ['system.directoryHandle'],
      },
    }),
});

// Export actions
export const { updateServices, updateServiceStatus } = servicesSlice.actions;
export const { updateCron } = cronSlice.actions;
export const { appendLogs, clearLogs } = logsSlice.actions;
export const { updateMetrics } = metricsSlice.actions;
export const {
  updateSupervisor,
  setPollingError,
  setIsPolling,
  setDirectoryHandle,
  selectService,
  setSearchTerm,
  setLogFilter,
  updateLastPoll,
} = systemSlice.actions;

// Export types
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
```

### File Polling Hook

```typescript
// useSystemGPoller.ts
import { useEffect, useRef } from 'react';
import { useDispatch } from 'react-redux';
import { updateServices, updateCron, updateMetrics, appendLogs, setPollingError } from './store';
import { sanitizeServices, readJsonSnapshot, readLogDelta, toPollingMessage } from './files';

const POLL_INTERVAL_MS = 1000;
const MAX_RETRY_DELAY_MS = 10_000;

export function useSystemGPoller(dirHandle: FileSystemDirectoryHandle | null) {
  const dispatch = useDispatch();
  const logOffsets = useRef(new Map<string, number>());

  useEffect(() => {
    if (!dirHandle) return undefined;

    let destroyed = false;
    let pollInFlight = false;
    let retryDelay = POLL_INTERVAL_MS;
    let timer: number | undefined;

    const scheduleNext = () => {
      if (destroyed) return;
      timer = window.setTimeout(pollState, retryDelay);
    };

    const pollState = async () => {
      if (pollInFlight || destroyed) return;
      pollInFlight = true;

      try {
        const services = await readJsonSnapshot(dirHandle, 'state/services.state');
        if (services) {
          dispatch(updateServices(sanitizeServices(services)));
        }

        const cron = await readJsonSnapshot(dirHandle, 'state/cron.state');
        if (cron) {
          dispatch(updateCron(cron));
        }

        const metrics = await readJsonSnapshot(dirHandle, 'metrics/latest.json');
        if (metrics) {
          dispatch(updateMetrics(metrics));
        }

        const newLogs = await readLogDelta(dirHandle, 'logs/supervisor.log', logOffsets.current, {
          maxBytes: 1_048_576, // 1 MiB safety cap
        });
        if (newLogs.length) {
          dispatch(appendLogs(newLogs));
        }

        retryDelay = POLL_INTERVAL_MS;
        dispatch(setPollingError(null));
      } catch (error) {
        console.error('Polling error', error);
        dispatch(setPollingError(toPollingMessage(error)));

        retryDelay = Math.min(retryDelay * 2, MAX_RETRY_DELAY_MS);
      } finally {
        pollInFlight = false;
        scheduleNext();
      }
    };

    pollState();

    return () => {
      destroyed = true;
      if (timer) {
        window.clearTimeout(timer);
      }
    };
  }, [dirHandle, dispatch]);
}
```

**Helper expectations**
- `readJsonSnapshot` memoizes each file's `lastModified` value so unchanged files short-circuit parsing. It must swallow partial writes and retry on the next tick instead of surfacing broken JSON to the UI.
- `readLogDelta` keeps a byte-offset map (`Map<string, number>`) and only returns the freshly appended log lines. Respect `maxBytes` to avoid loading multi-megabyte spikes into memory.
- `toPollingMessage` normalises DOMException names (e.g., `NotFoundError`, `NoModificationAllowedError`) into copy safe for user-facing alerts.
- Increase `retryDelay` only when errors occur; healthy steady-state polling should stay at `POLL_INTERVAL_MS`.

---

## Key Components

```tsx
// Simple status dot
<StatusDot status={proc.status} />

// ASCII sparkline
<SparkLine data={metrics} width={50} />

// Process tree node
<ProcNode proc={proc} depth={0} />

// Log viewer with search
<LogTail logs={logs} searchTerm={query} />
```

---

## Security Considerations

### Handling Sensitive Data

```typescript
// security.ts
const SENSITIVE_ENV_PATTERNS = [
  /api[_-]?key/i,
  /api[_-]?secret/i,
  /password/i,
  /passwd/i,
  /token/i,
  /auth/i,
  /credential/i,
  /private[_-]?key/i,
  /access[_-]?key/i,
  /secret[_-]?key/i,
  /aws[_-]?access/i,
  /aws[_-]?secret/i,
];

export function maskSensitiveValue(key: string, value: string): string {
  const isSensitive = SENSITIVE_ENV_PATTERNS.some(pattern => pattern.test(key));

  if (isSensitive) {
    // Show first 4 chars and mask the rest
    if (value.length <= 8) {
      return '********';
    }
    return value.substring(0, 4) + '*'.repeat(value.length - 4);
  }

  return value;
}

export function sanitizeEnvironment(env: Record<string, string>): Record<string, string> {
  const sanitized: Record<string, string> = {};

  for (const [key, value] of Object.entries(env)) {
    sanitized[key] = maskSensitiveValue(key, value);
  }

  return sanitized;
}

export function sanitizeLogs(logContent: string): string {
  // Remove potential secrets from logs
  let sanitized = logContent;

  // Replace JWT tokens
  sanitized = sanitized.replace(/Bearer\s+[A-Za-z0-9\-_=]+\.[A-Za-z0-9\-_=]+\.?[A-Za-z0-9\-_.+/=]*/g, 'Bearer [REDACTED]');

  // Replace API keys in URLs
  sanitized = sanitized.replace(/([?&])(api_key|apikey|token|auth)=([^&\s]+)/gi, '$1$2=[REDACTED]');

  // Replace basic auth in URLs
  sanitized = sanitized.replace(/:\/\/([^:]+):([^@]+)@/g, '://[REDACTED]:[REDACTED]@');

  return sanitized;
}
```

### Security Best Practices

1. **File Access Permissions**
   - Only request read permissions for systemg directory
   - Never write to system files from the UI
   - Validate all file paths before access

2. **Data Sanitization**
   - Mask sensitive environment variables before dispatch and persist them only in `sanitizedEnv`
   - Redact tokens and credentials from logs before appending to Redux
   - Never store raw secrets in Redux state or anywhere in IndexedDB/localStorage

3. **Browser Security**
   - Require HTTPS or localhost for File API
   - Use Content Security Policy headers
   - Sanitize all displayed data to prevent XSS

4. **Error Handling**
   ```typescript
   // errorBoundary.tsx
   export class SecurityErrorBoundary extends Component {
     componentDidCatch(error: Error) {
       // Never log full error with potentially sensitive data
       console.error('UI Error:', {
         message: error.message,
         type: error.name,
         // Don't log stack trace in production
         stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
       });
     }
   }
   ```

---

## Build Setup & Project Structure

### Project Initialization

```bash
# Create project with Vite
npm create vite@latest orchestrator-ui -- --template react-ts
cd orchestrator-ui

# Install dependencies
npm install \
  @reduxjs/toolkit react-redux \
  @chakra-ui/react @emotion/react @emotion/styled framer-motion \
  lucide-react \
  @types/node

# Dev dependencies
npm install -D \
  @testing-library/react @testing-library/jest-dom \
  vitest jsdom \
  @typescript-eslint/eslint-plugin @typescript-eslint/parser \
  prettier eslint-config-prettier
```

### Project Structure

```
orchestrator-ui/
├── src/
│   ├── components/
│   │   ├── Dashboard/
│   │   │   ├── QuickStats.tsx
│   │   │   ├── ProcList.tsx
│   │   │   └── CronNext.tsx
│   │   ├── ProcessTree/
│   │   │   ├── ProcessNode.tsx
│   │   │   └── ProcessTree.tsx
│   │   ├── LogViewer/
│   │   │   ├── LogTail.tsx
│   │   │   └── LogSearch.tsx
│   │   ├── Metrics/
│   │   │   ├── SparkLine.tsx
│   │   │   └── MetricsChart.tsx
│   │   └── Common/
│   │       ├── StatusDot.tsx
│   │       ├── ErrorBoundary.tsx
│   │       └── FilePicker.tsx
│   ├── hooks/
│   │   ├── useSystemGPoller.ts
│   │   ├── useKeyboardNav.ts
│   │   └── useFileAPI.ts
│   ├── store/
│   │   ├── index.ts
│   │   ├── slices/
│   │   │   ├── services.ts
│   │   │   ├── cron.ts
│   │   │   ├── logs.ts
│   │   │   └── metrics.ts
│   │   └── types.ts
│   ├── utils/
│   │   ├── security.ts
│   │   ├── browserCompat.ts
│   │   ├── dataTransform.ts
│   │   └── formatters.ts
│   ├── App.tsx
│   ├── main.tsx
│   └── types.d.ts
├── public/
│   └── favicon.ico
├── tests/
│   ├── unit/
│   └── integration/
├── .env.example
├── vite.config.ts
├── tsconfig.json
├── package.json
└── README.md
```

### Vite Configuration

```typescript
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { resolve } from 'path';

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': resolve(__dirname, './src'),
      '@components': resolve(__dirname, './src/components'),
      '@hooks': resolve(__dirname, './src/hooks'),
      '@store': resolve(__dirname, './src/store'),
      '@utils': resolve(__dirname, './src/utils'),
    },
  },
  build: {
    outDir: 'dist',
    assetsDir: 'assets',
    sourcemap: false,
    minify: 'esbuild',
    rollupOptions: {
      output: {
        manualChunks: {
          'vendor': ['react', 'react-dom', 'react-redux'],
          'ui': ['@chakra-ui/react', '@emotion/react'],
        },
      },
    },
  },
  server: {
    port: 3000,
    open: true,
  },
});
```

### TypeScript Configuration

```json
// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "useDefineForClassFields": true,
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,

    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",

    "paths": {
      "@/*": ["./src/*"],
      "@components/*": ["./src/components/*"],
      "@hooks/*": ["./src/hooks/*"],
      "@store/*": ["./src/store/*"],
      "@utils/*": ["./src/utils/*"]
    }
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}
```

### Package.json Scripts

```json
{
  "name": "orchestrator-ui",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview",
    "test": "vitest",
    "test:ui": "vitest --ui",
    "test:coverage": "vitest --coverage",
    "lint": "eslint src --ext ts,tsx",
    "format": "prettier --write 'src/**/*.{ts,tsx,css}'",
    "type-check": "tsc --noEmit"
  }
}
```

### Development Commands

```bash
# Start development server
npm run dev

# Run tests
npm run test

# Build for production
npm run build

# Preview production build
npm run preview

# Type checking
npm run type-check

# Linting & formatting
npm run lint
npm run format
```

### Deployment

```bash
# Build production bundle
npm run build

# The dist/ folder contains static files ready for deployment
# Can be served from any static file host (Netlify, Vercel, GitHub Pages, etc.)

# For local testing
npx serve dist

# Or simply open the index.html
open dist/index.html
```

### Minimum Viable Dashboard Timeline

1. **Day 1**: Project setup + File API integration
   - Initialize project structure
   - Set up Redux store
   - Implement file picker and browser compatibility

2. **Day 2**: Core UI Components
   - Build dashboard layout
   - Implement process list and tree view
   - Add status indicators

3. **Day 3**: Data Visualization
   - Log viewer with virtual scrolling
   - Metrics sparklines and charts
   - Real-time updates

4. **Day 4**: Polish & Features
   - Keyboard navigation
   - Search and filtering
   - Theme switching
   - Error boundaries

5. **Day 5**: Testing & Deployment
   - Unit tests for critical paths
   - Performance optimization
   - Production build
   - Deploy to static host

---

## Why This Is Cool

- **Zero backend complexity** — Just a static HTML file
- **File API magic** — Direct filesystem access from browser
- **Redux for state** — Clean, predictable state management
- **Real-time updates** — Poll every second, always fresh
- **Keyboard navigation** — vim bindings because we're not savages
- **ASCII art graphs** — Terminal aesthetic in the browser
- **Read-only safety** — Can't break anything, just observe

## Summary

A lightweight, clever dashboard that reads SystemG's state files directly from disk. No backend, no server processes, no complexity—just open an HTML file and watch your processes.

Built with React, Redux, and the File API. Polls state files every second for real-time updates.

**Total complexity**: One static HTML file + some JavaScript.
**Setup time**: 0 seconds.
**Maintenance burden**: None.