umer-wasim commited on
Commit
8b38665
·
verified ·
1 Parent(s): b1768eb

Desktop app (Electron + WebLLM), collector progress output, offline LoRA training script

Browse files
.gitignore CHANGED
@@ -7,3 +7,7 @@ __pycache__/
7
  .DS_Store
8
  # Generated training data (published separately as the Devseis/endpoint-auditor-synthetic dataset)
9
  training/out/
 
 
 
 
 
7
  .DS_Store
8
  # Generated training data (published separately as the Devseis/endpoint-auditor-synthetic dataset)
9
  training/out/
10
+ # Local training environment and model files
11
+ training/.venv/
12
+ training/models/
13
+ app/node_modules/
README.md CHANGED
@@ -132,6 +132,24 @@ made per audit (80/10/10), so no device appears in two splits. With 1,000 synthe
132
  Template labels teach the format and grounding. Before customer use, add reviewed real audits and have an
133
  ISO 27001 / GDPR professional review the library and a sample of the targets.
134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  ## Test status (collector version 0.1.0)
136
 
137
  | Collector | How it was tested |
 
132
  Template labels teach the format and grounding. Before customer use, add reviewed real audits and have an
133
  ISO 27001 / GDPR professional review the library and a sample of the targets.
134
 
135
+ ## Desktop app (Electron + WebLLM)
136
+
137
+ `app/` is the client application. It runs everything on the client's computer:
138
+
139
+ 1. **Prepare** — downloads the auditor model once through WebLLM (WebGPU) and caches it for offline use. Without WebGPU, the built-in report writer is used instead.
140
+ 2. **Approve** — lists every check that will run for this OS; the client clicks *Run audit* and the OS asks for administrator rights (macOS admin prompt, Windows UAC, Linux pkexec).
141
+ 3. **Progress** — each check is shown as it finishes (collectors write `--progress` lines), then the findings are written.
142
+ 4. **Save** — a popup asks where to save the PDF report; with no answer in 60 seconds it is saved to `Documents/Devseis Endpoint Audit/<computer>-<date>/` together with the evidence JSON.
143
+
144
+ Model answers are only used if they pass the same grounding check as the training data; otherwise the template answer is used, so a report is always produced. Scores and counts always come from the evidence.
145
+
146
+ ```bash
147
+ cd app && npm install && npm test # prompt parity with training/build_dataset.py
148
+ npm start # run the app
149
+ ```
150
+
151
+ Offline fine-tuning on CPU: `training/train_lora.py` (LoRA on Qwen2.5-0.5B-Instruct; see `--benchmark` and `--resume`).
152
+
153
  ## Test status (collector version 0.1.0)
154
 
155
  | Collector | How it was tested |
app/main.cjs ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Devseis Endpoint Auditor - Electron main process.
2
+ // Runs the read-only collector for this OS (with the OS's own administrator prompt), streams progress
3
+ // to the window, turns the report into a PDF and saves it where the user chooses or, after 60 seconds
4
+ // without an answer, in Documents/Devseis Endpoint Audit/<computer>-<date>/.
5
+ const { app, BrowserWindow, ipcMain, dialog, shell } = require('electron');
6
+ const { spawn } = require('node:child_process');
7
+ const crypto = require('node:crypto');
8
+ const fs = require('node:fs');
9
+ const os = require('node:os');
10
+ const path = require('node:path');
11
+
12
+ // WebGPU (used by WebLLM) is still behind a flag on Linux.
13
+ if (process.platform === 'linux') {
14
+ app.commandLine.appendSwitch('enable-unsafe-webgpu');
15
+ app.commandLine.appendSwitch('enable-features', 'Vulkan');
16
+ }
17
+
18
+ // Audit files: next to the app when packaged, the repository root during development.
19
+ const AUDIT_ROOT = app.isPackaged ? path.join(process.resourcesPath, 'audit') : path.join(__dirname, '..');
20
+ const OS_FAMILY = { win32: 'windows', darwin: 'macos', linux: 'linux' }[process.platform];
21
+ const readJson = (...parts) => JSON.parse(fs.readFileSync(path.join(AUDIT_ROOT, ...parts), 'utf8'));
22
+ let mainWindow = null;
23
+
24
+ function createWindow() {
25
+ mainWindow = new BrowserWindow({
26
+ width: 1100, height: 780, minWidth: 760, minHeight: 560, title: 'Devseis Endpoint Auditor',
27
+ webPreferences: { preload: path.join(__dirname, 'preload.cjs'), contextIsolation: true, nodeIntegration: false, sandbox: true },
28
+ });
29
+ mainWindow.loadFile(path.join(__dirname, 'renderer', 'index.html'));
30
+ }
31
+
32
+ app.whenReady().then(() => {
33
+ createWindow();
34
+ app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); });
35
+ });
36
+ app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); });
37
+
38
+ // --- What will be audited -------------------------------------------------------
39
+ ipcMain.handle('audit:plan', () => {
40
+ const catalog = readJson('catalog', 'checks.json');
41
+ const sections = catalog.sections.map(section => ({
42
+ id: section.id,
43
+ title: section.title,
44
+ checks: catalog.checks.filter(c => c.section === section.id && c.os.includes(OS_FAMILY))
45
+ .map(c => ({ id: c.id, name: (c.names && c.names[OS_FAMILY]) || c.name })),
46
+ }));
47
+ return { os: OS_FAMILY, hostname: os.hostname(), platform: `${os.type()} ${os.release()}`, sections };
48
+ });
49
+
50
+ ipcMain.handle('audit:library', () => ({
51
+ catalog: readJson('catalog', 'checks.json'),
52
+ controls: readJson('library', 'controls.json'),
53
+ guidance: readJson('library', 'check_guidance.json'),
54
+ aiTools: readJson('library', 'ai_tools.json'),
55
+ }));
56
+
57
+ // --- Running the collector ----------------------------------------------------------
58
+ function collectorCommand(workDir, progressFile, elevated) {
59
+ const base = path.join(AUDIT_ROOT, 'baseline.conf');
60
+ const org = path.join(AUDIT_ROOT, 'organisational.conf');
61
+ if (OS_FAMILY === 'windows') {
62
+ const q = s => `'${s.replace(/'/g, "''")}'`;
63
+ const runner = path.join(workDir, 'run.ps1');
64
+ fs.writeFileSync(runner, `& ${q(path.join(AUDIT_ROOT, 'collectors', 'windows', 'audit.ps1'))} -Baseline ${q(base)} -Organisational ${q(org)} -Output ${q(workDir)} -Progress ${q(progressFile)} *> ${q(path.join(workDir, 'collector.log'))}\n`);
65
+ const inner = `-NoProfile -ExecutionPolicy Bypass -File "${runner}"`;
66
+ if (!elevated) return ['powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', runner]];
67
+ // UAC prompt; -Wait keeps this process alive until the elevated audit finishes.
68
+ return ['powershell.exe', ['-NoProfile', '-Command', `Start-Process powershell.exe -Verb RunAs -Wait -WindowStyle Hidden -ArgumentList '${inner.replace(/'/g, "''")}'`]];
69
+ }
70
+ const q = s => `'${s.replace(/'/g, `'\\''`)}'`;
71
+ const runner = path.join(workDir, 'run.sh');
72
+ const collector = path.join(AUDIT_ROOT, 'collectors', OS_FAMILY, 'audit.sh');
73
+ fs.writeFileSync(runner, `#!/bin/bash\n/bin/bash ${q(collector)} --baseline ${q(base)} --org ${q(org)} --output ${q(workDir)} --progress ${q(progressFile)} > ${q(path.join(workDir, 'collector.log'))} 2>&1\nchmod -R a+rX ${q(workDir)}\n`, { mode: 0o755 });
74
+ if (!elevated) return ['/bin/bash', [runner]];
75
+ if (OS_FAMILY === 'macos') {
76
+ // macOS administrator prompt; the runner path has no quotes or backslashes.
77
+ return ['/usr/bin/osascript', ['-e', `do shell script "/bin/bash '${runner}'" with prompt "Devseis Endpoint Auditor needs administrator rights to read security settings. It only reads settings and changes nothing." with administrator privileges`]];
78
+ }
79
+ return ['pkexec', ['/bin/bash', runner]];
80
+ }
81
+
82
+ ipcMain.handle('audit:run', async (event, { elevated }) => {
83
+ const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'devseis-audit-'));
84
+ fs.chmodSync(workDir, 0o755);
85
+ const progressFile = path.join(workDir, 'progress.tsv');
86
+ fs.writeFileSync(progressFile, '');
87
+ fs.chmodSync(progressFile, 0o666);
88
+ const [command, args] = collectorCommand(workDir, progressFile, elevated);
89
+
90
+ return new Promise((resolve, reject) => {
91
+ let offset = 0;
92
+ let done = null;
93
+ const poll = () => {
94
+ const text = fs.readFileSync(progressFile, 'utf8');
95
+ const fresh = text.slice(offset);
96
+ const complete = fresh.lastIndexOf('\n') + 1;
97
+ offset += complete;
98
+ for (const line of fresh.slice(0, complete).split('\n').filter(Boolean)) {
99
+ const [first, second, third] = line.split('\t');
100
+ if (first === 'DONE') done = { evidencePath: second, reportPath: third };
101
+ else event.sender.send('audit:progress', { id: first, status: second, name: third });
102
+ }
103
+ };
104
+ const timer = setInterval(poll, 250);
105
+ const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });
106
+ let stderr = '';
107
+ child.stderr.on('data', chunk => { stderr += chunk; });
108
+ child.on('error', error => { clearInterval(timer); reject(new Error(`Could not start the audit: ${error.message}`)); });
109
+ child.on('close', code => {
110
+ clearInterval(timer);
111
+ poll();
112
+ if (!done) {
113
+ const log = fs.existsSync(path.join(workDir, 'collector.log')) ? fs.readFileSync(path.join(workDir, 'collector.log'), 'utf8').slice(-600) : '';
114
+ const cancelled = /User canceled|cancelled|-128|Request dismissed|126/.test(stderr) || code === 126;
115
+ reject(new Error(cancelled ? 'The administrator prompt was cancelled.' : `The audit did not finish (exit ${code}). ${stderr.slice(-300)} ${log}`.trim()));
116
+ return;
117
+ }
118
+ const evidenceText = fs.readFileSync(done.evidencePath, 'utf8');
119
+ resolve({ evidence: JSON.parse(evidenceText.replace(/^/, '')), evidenceText,
120
+ sha256: crypto.createHash('sha256').update(evidenceText).digest('hex'), workDir });
121
+ });
122
+ });
123
+ });
124
+
125
+ // --- Saving the report ------------------------------------------------------------------
126
+ function defaultFolder(hostname) {
127
+ const d = new Date();
128
+ const stamp = `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}-` +
129
+ `${String(d.getHours()).padStart(2, '0')}${String(d.getMinutes()).padStart(2, '0')}${String(d.getSeconds()).padStart(2, '0')}`;
130
+ return path.join(app.getPath('documents'), 'Devseis Endpoint Audit', `${hostname.replace(/[^\w.-]/g, '_')}-${stamp}`);
131
+ }
132
+
133
+ async function renderPdf(html) {
134
+ const win = new BrowserWindow({ show: false, webPreferences: { sandbox: true, javascript: false } });
135
+ await win.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(html)}`);
136
+ const pdf = await win.webContents.printToPDF({ printBackground: true, pageSize: 'A4',
137
+ margins: { top: 0.5, bottom: 0.5, left: 0.5, right: 0.5 } });
138
+ win.destroy();
139
+ return pdf;
140
+ }
141
+
142
+ // mode: 'choose' opens a Save dialog; 'auto' saves straight to the Documents folder.
143
+ ipcMain.handle('report:save', async (event, { html, evidenceText, hostname, mode }) => {
144
+ const pdf = await renderPdf(html);
145
+ let pdfPath;
146
+ if (mode === 'choose') {
147
+ const folder = defaultFolder(hostname);
148
+ const result = await dialog.showSaveDialog(mainWindow, {
149
+ title: 'Save the audit report', defaultPath: path.join(folder, 'audit-report.pdf'),
150
+ filters: [{ name: 'PDF', extensions: ['pdf'] }],
151
+ });
152
+ if (result.canceled || !result.filePath) return { saved: false };
153
+ pdfPath = result.filePath;
154
+ } else {
155
+ pdfPath = path.join(defaultFolder(hostname), 'audit-report.pdf');
156
+ }
157
+ fs.mkdirSync(path.dirname(pdfPath), { recursive: true });
158
+ fs.writeFileSync(pdfPath, pdf);
159
+ // Keep the machine-readable evidence next to the PDF (it is personal data: it stays on this computer).
160
+ fs.writeFileSync(pdfPath.replace(/\.pdf$/i, '') + '-evidence.json', evidenceText);
161
+ return { saved: true, pdfPath };
162
+ });
163
+
164
+ ipcMain.handle('report:show', (event, filePath) => shell.showItemInFolder(filePath));
app/package-lock.json ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "devseis-endpoint-auditor",
3
+ "version": "0.1.0",
4
+ "lockfileVersion": 3,
5
+ "requires": true,
6
+ "packages": {
7
+ "": {
8
+ "name": "devseis-endpoint-auditor",
9
+ "version": "0.1.0",
10
+ "dependencies": {
11
+ "@mlc-ai/web-llm": "^0.2.85"
12
+ },
13
+ "devDependencies": {
14
+ "electron": "^44.6.0"
15
+ }
16
+ },
17
+ "node_modules/@electron-internal/extract-zip": {
18
+ "version": "1.0.5",
19
+ "resolved": "https://registry.npmjs.org/@electron-internal/extract-zip/-/extract-zip-1.0.5.tgz",
20
+ "integrity": "sha512-+bqFCP98pLI0Tt0XQo1TmlXtwjWchISndDOxCkEcIuUgXWpBnLyRI+2DU+mesvnMMX6L1XDqYNA0lXNDHd/yiA==",
21
+ "dev": true,
22
+ "license": "BSD-2-Clause",
23
+ "engines": {
24
+ "node": ">=22.12.0"
25
+ }
26
+ },
27
+ "node_modules/@electron/get": {
28
+ "version": "5.1.0",
29
+ "resolved": "https://registry.npmjs.org/@electron/get/-/get-5.1.0.tgz",
30
+ "integrity": "sha512-3kSBtG8ObcTVfXanm5vVJ6UnBLEVmVsRk1M+vGqCuMBV+XLCbJYuWQful+yIy0GQDsSlK0kHEriEHn7SPk4EnA==",
31
+ "dev": true,
32
+ "license": "MIT",
33
+ "dependencies": {
34
+ "debug": "^4.1.1",
35
+ "env-paths": "^3.0.0",
36
+ "graceful-fs": "^4.2.11",
37
+ "progress": "^2.0.3",
38
+ "semver": "^7.6.3",
39
+ "sumchecker": "^3.0.1"
40
+ },
41
+ "engines": {
42
+ "node": ">=22.12.0"
43
+ },
44
+ "optionalDependencies": {
45
+ "undici": "^7.24.4"
46
+ }
47
+ },
48
+ "node_modules/@mlc-ai/web-llm": {
49
+ "version": "0.2.85",
50
+ "resolved": "https://registry.npmjs.org/@mlc-ai/web-llm/-/web-llm-0.2.85.tgz",
51
+ "integrity": "sha512-CwUiSAvDCYnmAZlpPMkurPHDfBLq6fvdRB3vRgoA894hRG/V/BSeY9bmMm6iIIU5VpjJxfb/dLPpJX2at0L9rw==",
52
+ "license": "Apache-2.0",
53
+ "dependencies": {
54
+ "loglevel": "^1.9.1"
55
+ }
56
+ },
57
+ "node_modules/@types/node": {
58
+ "version": "24.19.1",
59
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.1.tgz",
60
+ "integrity": "sha512-aS3/DG0oM05K0RIXXP+hKjinGG5IgSSVGzswZxW3O0sS3pH4/fycXundUC9XsszgKCk4gHXylTEK6hyFxVxnoQ==",
61
+ "dev": true,
62
+ "license": "MIT",
63
+ "dependencies": {
64
+ "undici-types": ">=7.24.0 <7.24.7"
65
+ }
66
+ },
67
+ "node_modules/debug": {
68
+ "version": "4.4.3",
69
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
70
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
71
+ "dev": true,
72
+ "license": "MIT",
73
+ "dependencies": {
74
+ "ms": "^2.1.3"
75
+ },
76
+ "engines": {
77
+ "node": ">=6.0"
78
+ },
79
+ "peerDependenciesMeta": {
80
+ "supports-color": {
81
+ "optional": true
82
+ }
83
+ }
84
+ },
85
+ "node_modules/electron": {
86
+ "version": "44.6.0",
87
+ "resolved": "https://registry.npmjs.org/electron/-/electron-44.6.0.tgz",
88
+ "integrity": "sha512-qjzKZ82yTsAoo0Q/gqdy4PEMQkzYpukZqIduaHWZYHapFhK9wgWwU4YId60xHmwTCraqF4AfVCm05o90dZJKMQ==",
89
+ "dev": true,
90
+ "license": "MIT",
91
+ "dependencies": {
92
+ "@electron-internal/extract-zip": "^1.0.1",
93
+ "@electron/get": "^5.0.0",
94
+ "@types/node": "^24.9.0"
95
+ },
96
+ "bin": {
97
+ "electron": "cli.js",
98
+ "install-electron": "install.js"
99
+ },
100
+ "engines": {
101
+ "node": ">= 22.12.0"
102
+ }
103
+ },
104
+ "node_modules/env-paths": {
105
+ "version": "3.0.0",
106
+ "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz",
107
+ "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==",
108
+ "dev": true,
109
+ "license": "MIT",
110
+ "engines": {
111
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
112
+ },
113
+ "funding": {
114
+ "url": "https://github.com/sponsors/sindresorhus"
115
+ }
116
+ },
117
+ "node_modules/graceful-fs": {
118
+ "version": "4.2.11",
119
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
120
+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
121
+ "dev": true,
122
+ "license": "ISC"
123
+ },
124
+ "node_modules/loglevel": {
125
+ "version": "1.9.2",
126
+ "resolved": "https://registry.npmjs.org/loglevel/-/loglevel-1.9.2.tgz",
127
+ "integrity": "sha512-HgMmCqIJSAKqo68l0rS2AanEWfkxaZ5wNiEFb5ggm08lDs9Xl2KxBlX3PTcaD2chBM1gXAYf491/M2Rv8Jwayg==",
128
+ "license": "MIT",
129
+ "engines": {
130
+ "node": ">= 0.6.0"
131
+ },
132
+ "funding": {
133
+ "type": "tidelift",
134
+ "url": "https://tidelift.com/funding/github/npm/loglevel"
135
+ }
136
+ },
137
+ "node_modules/ms": {
138
+ "version": "2.1.3",
139
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
140
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
141
+ "dev": true,
142
+ "license": "MIT"
143
+ },
144
+ "node_modules/progress": {
145
+ "version": "2.0.3",
146
+ "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",
147
+ "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",
148
+ "dev": true,
149
+ "license": "MIT",
150
+ "engines": {
151
+ "node": ">=0.4.0"
152
+ }
153
+ },
154
+ "node_modules/semver": {
155
+ "version": "7.8.5",
156
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
157
+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
158
+ "dev": true,
159
+ "license": "ISC",
160
+ "bin": {
161
+ "semver": "bin/semver.js"
162
+ },
163
+ "engines": {
164
+ "node": ">=10"
165
+ }
166
+ },
167
+ "node_modules/sumchecker": {
168
+ "version": "3.0.1",
169
+ "resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",
170
+ "integrity": "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==",
171
+ "dev": true,
172
+ "license": "Apache-2.0",
173
+ "dependencies": {
174
+ "debug": "^4.1.0"
175
+ },
176
+ "engines": {
177
+ "node": ">= 8.0"
178
+ }
179
+ },
180
+ "node_modules/undici": {
181
+ "version": "7.30.0",
182
+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.0.tgz",
183
+ "integrity": "sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==",
184
+ "dev": true,
185
+ "license": "MIT",
186
+ "optional": true,
187
+ "engines": {
188
+ "node": ">=20.18.1"
189
+ }
190
+ },
191
+ "node_modules/undici-types": {
192
+ "version": "7.24.6",
193
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
194
+ "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
195
+ "dev": true,
196
+ "license": "MIT"
197
+ }
198
+ }
199
+ }
app/package.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "devseis-endpoint-auditor",
3
+ "productName": "Devseis Endpoint Auditor",
4
+ "version": "0.1.0",
5
+ "description": "Read-only endpoint audit for ISO 27001, GDPR and the EU AI Act, with a local AI auditor.",
6
+ "author": "Devseis",
7
+ "private": true,
8
+ "type": "module",
9
+ "main": "main.cjs",
10
+ "scripts": {
11
+ "start": "electron .",
12
+ "test": "node test/prompt-parity.mjs"
13
+ },
14
+ "devDependencies": {
15
+ "electron": "^44.6.0"
16
+ },
17
+ "dependencies": {
18
+ "@mlc-ai/web-llm": "^0.2.85"
19
+ }
20
+ }
app/preload.cjs ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Exposes a small, fixed API to the window. The window never gets direct access to Node or the file system.
2
+ const { contextBridge, ipcRenderer } = require('electron');
3
+
4
+ contextBridge.exposeInMainWorld('devseis', {
5
+ plan: () => ipcRenderer.invoke('audit:plan'),
6
+ library: () => ipcRenderer.invoke('audit:library'),
7
+ runAudit: elevated => ipcRenderer.invoke('audit:run', { elevated }),
8
+ onProgress: callback => {
9
+ const listener = (event, item) => callback(item);
10
+ ipcRenderer.on('audit:progress', listener);
11
+ return () => ipcRenderer.removeListener('audit:progress', listener);
12
+ },
13
+ saveReport: options => ipcRenderer.invoke('report:save', options),
14
+ showInFolder: filePath => ipcRenderer.invoke('report:show', filePath),
15
+ });
app/renderer/app.js ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Screen flow: prepare model -> approval -> live progress -> findings -> results + save popup (60 s auto-save).
2
+ import { Library, findingPrompt, findingTemplate, summaryPrompt, summaryTemplate, aiPrompt, aiTemplate, writeAnswer } from './auditor-core.js';
3
+ import { buildReportHtml } from './report.js';
4
+
5
+ const $ = id => document.getElementById(id);
6
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
7
+ const SAVE_TIMEOUT_SECONDS = 60;
8
+ let plan = null, lib = null, model = null, lastReport = null, countdownTimer = null;
9
+
10
+ function show(name) {
11
+ for (const screen of document.querySelectorAll('.screen')) screen.classList.toggle('hidden', screen.id !== `screen-${name}`);
12
+ }
13
+ function setBar(id, fraction) { $(id).style.width = `${Math.round(Math.max(0, Math.min(1, fraction)) * 100)}%`; }
14
+ function stopped(title, text) { $('stopped-title').textContent = title; $('stopped-text').textContent = text; show('stopped'); }
15
+
16
+ // 1. Prepare the auditor model (downloaded once, then cached by WebLLM)
17
+ async function prepare() {
18
+ show('model');
19
+ plan = await window.devseis.plan();
20
+ lib = new Library(await window.devseis.library());
21
+ $('device').textContent = `${plan.hostname} · ${plan.platform}`;
22
+ if (!model) {
23
+ try {
24
+ const { loadModel } = await import('./model.js');
25
+ $('model-name').textContent = 'Devseis auditor model';
26
+ $('model-status').textContent = 'Downloading the auditor model (first run only)…';
27
+ model = await loadModel(({ progress, text }) => {
28
+ setBar('model-bar', progress);
29
+ $('model-percent').textContent = `${Math.round(progress * 100)}%`;
30
+ $('model-status').textContent = text;
31
+ });
32
+ $('model-name').textContent = model.name + (model.fineTuned ? '' : ' (base model)');
33
+ $('model-status').textContent = 'The auditor is ready and runs offline on this computer.';
34
+ setBar('model-bar', 1);
35
+ $('model-percent').textContent = '100%';
36
+ await sleep(800);
37
+ } catch (error) {
38
+ model = null;
39
+ $('model-name').textContent = 'Built-in report writer';
40
+ $('model-percent').textContent = '';
41
+ $('model-status').textContent = `${error.message} The audit will use the built-in report writer instead.`;
42
+ await sleep(2500);
43
+ }
44
+ }
45
+ showApproval();
46
+ }
47
+
48
+ // 2. Approval: show everything that will be checked
49
+ function showApproval() {
50
+ $('plan').innerHTML = '';
51
+ for (const section of plan.sections) {
52
+ const box = document.createElement('div');
53
+ box.className = 'section';
54
+ const title = document.createElement('h3');
55
+ title.textContent = section.title;
56
+ const count = document.createElement('span');
57
+ count.textContent = `${section.checks.length} checks`;
58
+ title.appendChild(count);
59
+ const list = document.createElement('ul');
60
+ for (const check of section.checks) {
61
+ const item = document.createElement('li');
62
+ item.textContent = check.name;
63
+ list.appendChild(item);
64
+ }
65
+ box.append(title, list);
66
+ $('plan').appendChild(box);
67
+ }
68
+ show('approve');
69
+ }
70
+
71
+ // 3. Run the audit and show live progress
72
+ async function runAudit() {
73
+ show('progress');
74
+ $('progress-title').textContent = 'Auditing this computer';
75
+ $('progress-step').textContent = 'Collecting evidence';
76
+ $('progress-current').textContent = $('elevated').checked ? 'Waiting for administrator approval…' : 'Starting…';
77
+ setBar('progress-bar', 0);
78
+ const rows = new Map();
79
+ const order = [];
80
+ $('checklist').innerHTML = '';
81
+ for (const section of plan.sections) {
82
+ for (const check of section.checks) {
83
+ const row = document.createElement('div');
84
+ row.className = 'check';
85
+ row.innerHTML = '<span class="icon"></span><span class="name"></span><span class="group"></span>';
86
+ row.querySelector('.name').textContent = check.name;
87
+ row.querySelector('.group').textContent = section.title.replace(' CONTROLS', '').replace('COMPLIANCE RESULTS', 'BASELINE');
88
+ $('checklist').appendChild(row);
89
+ rows.set(check.id, row);
90
+ order.push(check.id);
91
+ }
92
+ }
93
+ const total = order.length;
94
+ let finished = 0;
95
+ $('progress-count').textContent = `0 / ${total}`;
96
+ const markRunning = () => { const next = order.find(id => !rows.get(id).classList.contains('done')); if (next) rows.get(next).classList.add('running'); };
97
+ const markDone = (id, status) => {
98
+ const row = rows.get(id);
99
+ if (!row || row.classList.contains('done')) return;
100
+ row.classList.remove('running');
101
+ row.classList.add('done', `s-${status}`);
102
+ row.querySelector('.group').textContent = status;
103
+ finished += 1;
104
+ $('progress-count').textContent = `${finished} / ${total}`;
105
+ setBar('progress-bar', finished / total);
106
+ };
107
+ const unsubscribe = window.devseis.onProgress(item => {
108
+ markDone(item.id, item.status);
109
+ $('progress-current').textContent = `Checked: ${item.name}`;
110
+ markRunning();
111
+ });
112
+
113
+ let result;
114
+ try {
115
+ result = await window.devseis.runAudit($('elevated').checked);
116
+ } catch (error) {
117
+ unsubscribe();
118
+ const cancelled = /cancelled/i.test(error.message);
119
+ stopped(cancelled ? 'Audit cancelled' : 'The audit stopped', cancelled ? 'Administrator approval was not given. Nothing was checked and nothing was changed.' : error.message);
120
+ return;
121
+ }
122
+ unsubscribe();
123
+ const evidence = result.evidence;
124
+ for (const r of evidence.results) markDone(r.id, r.status);
125
+
126
+ // 4. Write the findings (AI model when available, otherwise the built-in writer)
127
+ const targets = evidence.results.filter(r => ['Non-Compliant', 'Error', 'Pending'].includes(r.status));
128
+ const ai = aiPrompt(evidence, lib);
129
+ const steps = targets.length + 1 + (ai ? 1 : 0);
130
+ let written = 0;
131
+ const sources = { model: 0, template: 0 };
132
+ const generate = model ? model.generate : null;
133
+ const tick = label => {
134
+ written += 1;
135
+ $('progress-count').textContent = `${written} / ${steps}`;
136
+ setBar('progress-bar', written / steps);
137
+ $('progress-current').textContent = label;
138
+ };
139
+ $('progress-title').textContent = 'Writing the audit report';
140
+ $('progress-step').textContent = model ? 'AI auditor is writing findings' : 'Writing findings';
141
+ $('progress-count').textContent = `0 / ${steps}`;
142
+ setBar('progress-bar', 0);
143
+
144
+ const findings = {};
145
+ for (const r of targets) {
146
+ $('progress-current').textContent = `Writing: ${r.name}`;
147
+ const { answer, source } = await writeAnswer('finding', findingPrompt(evidence, r, lib), findingTemplate(evidence, r, lib), generate);
148
+ findings[r.id] = answer;
149
+ sources[source] += 1;
150
+ tick(`Written: ${r.name}`);
151
+ }
152
+ // Score, counts and top gaps always come from the evidence; the model may only phrase the text.
153
+ const summaryBase = summaryTemplate(evidence, lib);
154
+ const summaryOut = await writeAnswer('summary', summaryPrompt(evidence, lib), summaryBase, generate);
155
+ const summary = summaryOut.source === 'model'
156
+ ? { ...summaryBase, summary: summaryOut.answer.summary, next_steps: summaryOut.answer.next_steps }
157
+ : summaryBase;
158
+ sources[summaryOut.source] += 1;
159
+ tick('Written: summary');
160
+ let aiResult = null;
161
+ if (ai) {
162
+ const out = await writeAnswer('ai_classification', ai, aiTemplate(evidence, lib), generate);
163
+ aiResult = out.answer;
164
+ sources[out.source] += 1;
165
+ tick('Written: AI tool classification');
166
+ }
167
+
168
+ const html = buildReportHtml({ evidence, findings, summary, ai: aiResult, sha256: result.sha256, model: model ? model.name : null, sources });
169
+ lastReport = { html, evidenceText: result.evidenceText, hostname: evidence.host.hostname };
170
+ showResults(evidence, summary, sources);
171
+ openSaveModal();
172
+ }
173
+
174
+ // 5. Results and saving
175
+ function showResults(evidence, summary, sources) {
176
+ const pills = Object.entries(evidence.summary).map(([k, v]) => `<span class="pill s-${k}">${v} ${k}</span>`).join('');
177
+ const gaps = summary.top_gaps.map(g => `<li><b class="s-Non-Compliant">${g.risk}</b> — ${escapeHtml(g.name)}: ${escapeHtml(g.found)}</li>`).join('');
178
+ $('result-summary').innerHTML = `
179
+ <div class="row"><div><div class="score">${summary.score.percent}%</div>
180
+ <div class="muted">${summary.score.compliant} of ${summary.score.assessed} assessed checks compliant</div></div></div>
181
+ <div class="pills">${pills}</div>
182
+ <p>${escapeHtml(summary.summary)}</p>
183
+ ${gaps ? `<b>Top gaps</b><ul class="gaps">${gaps}</ul>` : ''}
184
+ <p class="muted">Findings: ${sources.model} written by the AI auditor, ${sources.template} by the built-in writer.</p>`;
185
+ $('saved-note').textContent = '';
186
+ show('done');
187
+ }
188
+
189
+ function escapeHtml(value) { const d = document.createElement('div'); d.textContent = String(value ?? ''); return d.innerHTML; }
190
+
191
+ function openSaveModal() {
192
+ let remaining = SAVE_TIMEOUT_SECONDS;
193
+ $('countdown').textContent = remaining;
194
+ setBar('countdown-bar', 1);
195
+ $('save-modal').classList.remove('hidden');
196
+ clearInterval(countdownTimer);
197
+ countdownTimer = setInterval(() => {
198
+ remaining -= 1;
199
+ $('countdown').textContent = remaining;
200
+ setBar('countdown-bar', remaining / SAVE_TIMEOUT_SECONDS);
201
+ if (remaining <= 0) save('auto', true);
202
+ }, 1000);
203
+ }
204
+
205
+ async function save(mode, automatic = false) {
206
+ clearInterval(countdownTimer);
207
+ $('save-modal').classList.add('hidden');
208
+ if (!lastReport) return;
209
+ $('saved-note').textContent = 'Saving…';
210
+ try {
211
+ const result = await window.devseis.saveReport({ ...lastReport, mode });
212
+ if (!result.saved) {
213
+ $('saved-note').textContent = 'The report was not saved. Use "Save report as PDF" to save it.';
214
+ return;
215
+ }
216
+ $('saved-note').innerHTML = '';
217
+ const prefix = document.createTextNode(automatic ? 'No answer after 60 seconds — saved automatically to ' : 'Saved to ');
218
+ const link = document.createElement('a');
219
+ link.href = '#';
220
+ link.textContent = result.pdfPath;
221
+ link.addEventListener('click', event => { event.preventDefault(); window.devseis.showInFolder(result.pdfPath); });
222
+ $('saved-note').append(prefix, link);
223
+ } catch (error) {
224
+ $('saved-note').textContent = `Saving failed: ${error.message}`;
225
+ }
226
+ }
227
+
228
+ $('run').addEventListener('click', runAudit);
229
+ $('cancel').addEventListener('click', () => stopped('Audit cancelled', 'Nothing was checked and nothing was changed.'));
230
+ $('restart').addEventListener('click', showApproval);
231
+ $('again').addEventListener('click', showApproval);
232
+ $('save-again').addEventListener('click', () => save('choose'));
233
+ $('save-docs').addEventListener('click', () => save('auto'));
234
+ $('save-choose').addEventListener('click', () => save('choose'));
235
+ prepare();
app/renderer/auditor-core.js ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Devseis auditor core: builds the same prompts the model was trained on (training/build_dataset.py),
2
+ // produces template answers as a fallback, and checks model answers for grounding.
3
+ // Used by the app (browser) and by tests (Node). No dependencies.
4
+
5
+ export const SYSTEM_PROMPT = 'You are the Devseis endpoint auditor. You write audit findings from collected evidence for ' +
6
+ 'ISO 27001, GDPR and the EU AI Act. Use only the evidence and reference material in the request. ' +
7
+ 'Never invent values, dates, versions, account names or tools. Reply with JSON only.';
8
+
9
+ export const SECTION_TITLES = { baseline: 'COMPLIANCE RESULTS', gdpr: 'GDPR TECHNICAL CONTROLS', aiact: 'EU AI ACT CONTROLS', org: 'ORGANISATIONAL CONTROLS' };
10
+ const RISK_ORDER = { High: 0, Medium: 1, Low: 2 };
11
+
12
+ export class Library {
13
+ // data: { catalog, controls, guidance, aiTools } as loaded from catalog/ and library/
14
+ constructor(data) {
15
+ this.checks = Object.fromEntries(data.catalog.checks.map(c => [c.id, c]));
16
+ this.titles = data.catalog.references;
17
+ this.controls = Object.fromEntries(data.controls.controls.map(c => [`${c.id}|${c.framework}`, c]));
18
+ this.guidance = data.guidance.checks;
19
+ this.aliases = data.guidance.aliases;
20
+ this.statusNotes = data.guidance.status_notes;
21
+ this.tools = data.aiTools.tools;
22
+ this.purposeRules = data.aiTools.purpose_rules;
23
+ }
24
+
25
+ guide(checkId) { return this.guidance[this.aliases[checkId] || checkId]; }
26
+
27
+ references(checkId) {
28
+ const out = [];
29
+ const controls = this.checks[checkId].controls;
30
+ for (const [key, framework] of [['iso27001', 'ISO 27001:2022'], ['gdpr', 'GDPR'], ['ai_act', 'EU AI Act']]) {
31
+ for (const ref of controls[key]) {
32
+ const entry = this.controls[`${ref}|${framework}`];
33
+ const title = entry ? entry.title : (this.titles[key][ref] || '');
34
+ out.push([`${framework} ${ref}`, title, entry ? entry.summary : '']);
35
+ }
36
+ }
37
+ return out;
38
+ }
39
+ }
40
+
41
+ export function fill(text, baseline) {
42
+ const values = { ...baseline };
43
+ values.LOCKOUT_DURATION_SECONDS = String(parseInt(baseline.LOCKOUT_DURATION_MIN_MINUTES, 10) * 60);
44
+ values.LOCKOUT_OBSERVATION_SECONDS = String(parseInt(baseline.LOCKOUT_OBSERVATION_MIN_MINUTES, 10) * 60);
45
+ values.SCREEN_LOCK_MAX_MINUTES = String(Math.floor(parseInt(baseline.SCREEN_LOCK_MAX_SECONDS, 10) / 60));
46
+ const out = baseline.FIREWALL_OUTBOUND;
47
+ values.FIREWALL_OUTBOUND_TITLE = out.charAt(0).toUpperCase() + out.slice(1).toLowerCase();
48
+ values.USB_READ_POLICY = baseline.USB_READ.toLowerCase() === 'deny' ? 'Enabled' : 'Disabled';
49
+ values.APPROVED_REMOTE_SERVICES_TEXT = baseline.APPROVED_REMOTE_SERVICES || 'none';
50
+ return text.replace(/\{([A-Z_]+)\}/g, (match, key) => (key in values ? values[key] : match));
51
+ }
52
+
53
+ export function fixSteps(guide, osFamily, baseline) {
54
+ return [...(guide.fix.all || []), ...(guide.fix[osFamily] || [])].map(step => fill(step, baseline));
55
+ }
56
+
57
+ const deviceLine = record => `${record.host.os_name} ${record.host.os_version} (${record.host.os_family})`;
58
+ const sentence = text => { const t = text.trim(); return !t || /[.!?]$/.test(t) ? t : `${t}.`; };
59
+
60
+ // --- Task A: finding ----------------------------------------------------------
61
+ export function findingPrompt(record, result, lib) {
62
+ const osFamily = record.host.os_family;
63
+ const baseline = record.baseline;
64
+ const guide = lib.guide(result.id);
65
+ const lines = [
66
+ 'TASK: finding',
67
+ `DEVICE: ${deviceLine(record)}`,
68
+ `AUDIT RUN AS ADMIN: ${record.audit.is_admin ? 'yes' : 'no'}`,
69
+ `CHECK: ${result.name} [${result.id}] in ${SECTION_TITLES[result.section]}`,
70
+ `STATUS: ${result.status}`,
71
+ `FOUND: ${result.actual}`,
72
+ `REQUIRED: ${result.expected}`,
73
+ ];
74
+ if (result.detail) lines.push(`DETAIL: ${result.detail}`);
75
+ lines.push('REFERENCES:');
76
+ for (const [label, title, summary] of lib.references(result.id)) lines.push(`- ${label} ${title}: ${summary}`);
77
+ lines.push('GUIDANCE:');
78
+ lines.push(`why: ${guide.why}`);
79
+ lines.push(`risk: ${guide.risk.level} - ${guide.risk.reason}`);
80
+ const steps = fixSteps(guide, osFamily, baseline);
81
+ if (steps.length) {
82
+ lines.push(`fix (${osFamily}):`);
83
+ for (const step of steps) lines.push(`- ${step}`);
84
+ }
85
+ lines.push(`verify: ${fill(guide.verify, baseline)}`);
86
+ if (guide.note) lines.push(`note: ${fill(guide.note, baseline)}`);
87
+ if (lib.statusNotes[result.status]) lines.push(`status note: ${lib.statusNotes[result.status]}`);
88
+ return lines.join('\n');
89
+ }
90
+
91
+ export function findingTemplate(record, result, lib) {
92
+ const guide = lib.guide(result.id);
93
+ const baseline = record.baseline;
94
+ const steps = fixSteps(guide, record.host.os_family, baseline);
95
+ const detail = result.detail || '';
96
+ const references = lib.references(result.id).map(([label]) => label);
97
+ const status = result.status;
98
+ const name = result.name;
99
+ let title, finding, risk, recommendation, verification = null;
100
+ if (status === 'Compliant') {
101
+ title = `${name}: meets the baseline`;
102
+ finding = `The device reports ${result.actual}, which meets the requirement (${result.expected}).`;
103
+ risk = { level: 'None', reason: 'The setting meets the baseline.' };
104
+ recommendation = ['Keep the current setting and confirm it at the next audit.'];
105
+ } else if (status === 'Non-Compliant') {
106
+ title = `${name}: does not meet the baseline`;
107
+ finding = `The device reports ${result.actual}, but the baseline requires ${result.expected}. ${guide.why}`;
108
+ risk = { ...guide.risk };
109
+ recommendation = steps;
110
+ verification = fill(guide.verify, baseline);
111
+ } else if (status === 'Error') {
112
+ title = `${name}: could not be checked`;
113
+ finding = `The collector could not read this setting (${detail ? sentence(detail) : 'no detail'}), so compliance is unknown.`;
114
+ risk = { level: 'Unknown', reason: 'The setting could not be read.' };
115
+ recommendation = [lib.statusNotes.Error];
116
+ verification = fill(guide.verify, baseline);
117
+ } else if (status === 'Pending') {
118
+ title = `${name}: decision pending`;
119
+ finding = `Current state: ${result.actual}. ${detail ? sentence(detail) : lib.statusNotes.Pending}`;
120
+ risk = { level: guide.risk.level, reason: `Until resolved: ${guide.risk.reason}` };
121
+ recommendation = steps;
122
+ verification = fill(guide.verify, baseline);
123
+ } else {
124
+ title = `${name}: not applicable`;
125
+ finding = `This check does not apply: ${sentence(detail || result.actual)}`;
126
+ risk = { level: 'None', reason: 'Not applicable to this device.' };
127
+ recommendation = [];
128
+ }
129
+ const answer = { check_id: result.id, status, title, finding: finding.trim(), risk, recommendation, references };
130
+ if (verification) answer.verification = verification;
131
+ return answer;
132
+ }
133
+
134
+ // --- Task B: summary ------------------------------------------------------------
135
+ function rankedGaps(record, lib) {
136
+ const order = new Map(record.results.map((r, i) => [r.id, i]));
137
+ return record.results.filter(r => r.status === 'Non-Compliant')
138
+ .sort((a, b) => (RISK_ORDER[lib.guide(a.id).risk.level] - RISK_ORDER[lib.guide(b.id).risk.level]) || (order.get(a.id) - order.get(b.id)));
139
+ }
140
+
141
+ export function summaryPrompt(record, lib) {
142
+ const { results, summary, host } = record;
143
+ const lines = ['TASK: summary', `DEVICE: ${deviceLine(record)}`, `HOSTNAME: ${host.hostname}`,
144
+ `AUDIT RUN AS ADMIN: ${record.audit.is_admin ? 'yes' : 'no'}`,
145
+ 'COUNTS: ' + Object.entries(summary).map(([k, v]) => `${k}=${v}`).join(', '), 'RESULTS (id | name | status | found):'];
146
+ for (const r of results) lines.push(`- ${r.id} | ${r.name} | ${r.status} | ${r.actual}`);
147
+ lines.push('RISK LEVELS (from guidance):');
148
+ for (const r of results.filter(x => x.status === 'Non-Compliant')) lines.push(`- ${r.id}: ${lib.guide(r.id).risk.level}`);
149
+ lines.push('FIX GUIDANCE (highest-risk gaps):');
150
+ for (const r of rankedGaps(record, lib).slice(0, 3)) {
151
+ const steps = fixSteps(lib.guide(r.id), host.os_family, record.baseline);
152
+ if (steps.length) lines.push(`- ${r.id}: ${steps[0]}`);
153
+ }
154
+ return lines.join('\n');
155
+ }
156
+
157
+ export function summaryTemplate(record, lib) {
158
+ const { results, summary, host } = record;
159
+ const ranked = rankedGaps(record, lib);
160
+ const top = ranked.slice(0, 5).map(r => ({ check_id: r.id, name: r.name, risk: lib.guide(r.id).risk.level, found: r.actual }));
161
+ const assessed = summary.Compliant + summary['Non-Compliant'];
162
+ const percent = assessed ? Math.round(100 * summary.Compliant / assessed) : 0;
163
+ const high = ranked.filter(r => lib.guide(r.id).risk.level === 'High');
164
+ let text = `${host.hostname} meets ${summary.Compliant} of ${assessed} assessed checks (${percent}%).`;
165
+ if (high.length) {
166
+ const names = high.slice(0, 3).map(r => r.name);
167
+ text += ' The most serious gaps are ' + (names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}` : names[0]) + '.';
168
+ } else if (ranked.length) {
169
+ text += ` There are ${summary['Non-Compliant']} gaps, none of them rated high risk.`;
170
+ } else {
171
+ text += ' No gaps were found.';
172
+ }
173
+ if (summary.Error) text += ` ${summary.Error} checks could not be read` + (record.audit.is_admin ? '.' : ' because the audit was not run as administrator.');
174
+ if (summary.Pending) text += ` ${summary.Pending} items are pending.`;
175
+ const nextSteps = [];
176
+ if (summary.Error) nextSteps.push('Re-run the audit as administrator/root so that every check can be read.');
177
+ for (const r of ranked.slice(0, 3)) {
178
+ const steps = fixSteps(lib.guide(r.id), host.os_family, record.baseline);
179
+ if (steps.length) nextSteps.push(`${r.name}: ${steps[0]}`);
180
+ }
181
+ const unanswered = results.filter(r => r.section === 'org' && r.status === 'Pending');
182
+ if (unanswered.length) nextSteps.push(`Answer the ${unanswered.length} open organisational questions in organisational.conf.`);
183
+ if (results.some(r => r.id === 'aiact.risk_classification' && r.status === 'Pending')) nextSteps.push('Classify the AI tools found on this device and record them in the AI register.');
184
+ return { device: `${host.hostname} - ${host.os_name} ${host.os_version}`, score: { compliant: summary.Compliant, assessed, percent },
185
+ counts: summary, top_gaps: top, summary: text, next_steps: nextSteps };
186
+ }
187
+
188
+ // --- Task C: AI tool classification -----------------------------------------------
189
+ export function aiTools(record) {
190
+ const inventory = record.results.find(r => r.id === 'aiact.inventory');
191
+ if (!inventory || inventory.actual === 'no AI tools found') return [];
192
+ return inventory.actual.split(',').map(t => t.trim()).filter(Boolean);
193
+ }
194
+
195
+ export function aiPrompt(record, lib) {
196
+ const tools = aiTools(record);
197
+ if (!tools.length) return null;
198
+ const inventory = record.results.find(r => r.id === 'aiact.inventory');
199
+ const rules = lib.purposeRules;
200
+ const lines = ['TASK: ai_classification', `DEVICE: ${deviceLine(record)}`, `AI TOOLS FOUND: ${tools.join(', ')}`,
201
+ `APPROVED AI TOOLS: ${record.baseline.APPROVED_AI_TOOLS || 'none'}`];
202
+ if (inventory.detail) lines.push(`INVENTORY DETAIL: ${inventory.detail}`);
203
+ lines.push('PURPOSE OF USE: not stated');
204
+ lines.push('TOOL FACTS:');
205
+ for (const tool of tools) {
206
+ const f = lib.tools[tool];
207
+ if (f) lines.push(`- ${tool}: ${f.kind}; provider ${f.provider}; data: ${f.data_location}; default risk ${f.default_risk}; GDPR: ${f.gdpr_notes}`);
208
+ }
209
+ lines.push('RULES:');
210
+ lines.push('- prohibited: ' + rules.prohibited.join('; '));
211
+ lines.push('- high-risk examples: ' + rules.high_risk_examples.join('; '));
212
+ lines.push('- limited risk: ' + rules.limited_risk);
213
+ lines.push('- minimal risk: ' + rules.minimal_risk);
214
+ return lines.join('\n');
215
+ }
216
+
217
+ export function aiTemplate(record, lib) {
218
+ const tools = aiTools(record);
219
+ if (!tools.length) return null;
220
+ const approved = (record.baseline.APPROVED_AI_TOOLS || '').split(',').map(a => a.trim().toLowerCase()).filter(Boolean);
221
+ const rules = lib.purposeRules;
222
+ const entries = tools.map(tool => {
223
+ const f = lib.tools[tool] || {};
224
+ const ok = approved.includes(tool.toLowerCase());
225
+ return { tool, kind: f.kind || 'unknown', approved: ok, default_risk_class: f.default_risk || 'unknown',
226
+ becomes_high_risk_if: rules.high_risk_examples.slice(0, 2), prohibited_if: rules.prohibited.slice(0, 1), gdpr: f.gdpr_notes || '',
227
+ action: ok ? 'Keep: approved. Confirm its purpose is recorded in the AI register.'
228
+ : 'Review: not approved. Approve it after a data protection and AI Act review, or remove it.' };
229
+ });
230
+ const unapproved = entries.filter(e => !e.approved).map(e => e.tool);
231
+ return { tools: entries, purpose_needed: true,
232
+ log_retention: 'Required (at least six months) only if a tool is used for a high-risk purpose.',
233
+ summary: `${tools.length} AI tool(s) found; default risk class minimal for general office use. ` +
234
+ 'The class rises to high-risk if a tool is used for an Annex III purpose such as screening job applicants. ' +
235
+ (unapproved.length ? `Not approved: ${unapproved.join(', ')}.` : 'All tools are approved.') };
236
+ }
237
+
238
+ // --- Grounding check (same rules as training/check_faithfulness.py) -----------------------
239
+ const REQUIRED = {
240
+ finding: ['check_id', 'status', 'title', 'finding', 'risk', 'recommendation', 'references'],
241
+ summary: ['device', 'score', 'counts', 'top_gaps', 'summary', 'next_steps'],
242
+ ai_classification: ['tools', 'purpose_needed', 'log_retention', 'summary'],
243
+ };
244
+ const NUMBER = /(?<![\w.])\d+(?:\.\d+)?(?!\w)/g;
245
+ function* strings(value) {
246
+ if (typeof value === 'string') yield value;
247
+ else if (Array.isArray(value)) for (const v of value) yield* strings(v);
248
+ else if (value && typeof value === 'object') for (const v of Object.values(value)) yield* strings(v);
249
+ }
250
+
251
+ export function groundingProblems(task, prompt, answer) {
252
+ const problems = [];
253
+ for (const key of REQUIRED[task]) if (!(key in answer)) problems.push(`missing ${key}`);
254
+ const allowed = new Set(prompt.match(NUMBER) || []);
255
+ if (task === 'summary') Object.values(answer.score || {}).forEach(v => allowed.add(String(v)));
256
+ if (task !== 'finding') for (let n = 0; n <= 10; n++) allowed.add(String(n));
257
+ for (const text of strings(answer)) for (const n of text.match(NUMBER) || []) if (!allowed.has(n)) problems.push(`number ${n} not in evidence`);
258
+ if (task === 'finding') {
259
+ if (!prompt.includes(`[${answer.check_id}]`)) problems.push('wrong check id');
260
+ if (!prompt.includes(`STATUS: ${answer.status}`)) problems.push('wrong status');
261
+ for (const ref of answer.references || []) if (!prompt.includes(ref)) problems.push(`unknown reference ${ref}`);
262
+ }
263
+ if (task === 'ai_classification') for (const t of answer.tools || []) if (t.tool && !prompt.includes(t.tool)) problems.push(`unknown tool ${t.tool}`);
264
+ return problems;
265
+ }
266
+
267
+ // Ask the model when available; fall back to the template answer if it is missing or not grounded.
268
+ export async function writeAnswer(task, prompt, template, generate) {
269
+ if (generate) {
270
+ try {
271
+ const reply = await generate(SYSTEM_PROMPT, prompt);
272
+ const answer = JSON.parse(reply);
273
+ if (groundingProblems(task, prompt, answer).length === 0) return { answer, source: 'model' };
274
+ } catch (error) { /* invalid JSON or engine failure: use the template */ }
275
+ }
276
+ return { answer: template, source: 'template' };
277
+ }
app/renderer/index.html ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self'; connect-src 'self' https://huggingface.co https://*.huggingface.co https://*.hf.co https://raw.githubusercontent.com; img-src 'self' data:; worker-src 'self' blob:">
6
+ <meta name="viewport" content="width=device-width, initial-scale=1">
7
+ <title>Devseis Endpoint Auditor</title>
8
+ <link rel="stylesheet" href="styles.css">
9
+ </head>
10
+ <body>
11
+ <header class="bar">
12
+ <div class="brand"><span class="dot"></span> Devseis Endpoint Auditor</div>
13
+ <div class="device" id="device"></div>
14
+ </header>
15
+
16
+ <main>
17
+ <!-- 1. Preparing the auditor model -->
18
+ <section class="screen" id="screen-model">
19
+ <h1>Preparing the auditor</h1>
20
+ <p class="lead">The AI auditor runs on this computer. It is downloaded once and then works offline; nothing about your device is sent anywhere.</p>
21
+ <div class="card">
22
+ <div class="row"><b id="model-name">Loading…</b><span id="model-percent">0%</span></div>
23
+ <div class="progress"><div id="model-bar"></div></div>
24
+ <p class="muted" id="model-status">Checking this computer…</p>
25
+ </div>
26
+ </section>
27
+
28
+ <!-- 2. Approval -->
29
+ <section class="screen hidden" id="screen-approve">
30
+ <h1>Ready to audit this computer</h1>
31
+ <p class="lead">The audit only <b>reads</b> settings. It does not change anything on this computer. These checks will run:</p>
32
+ <div class="sections" id="plan"></div>
33
+ <label class="option"><input type="checkbox" id="elevated" checked> Run with administrator rights (recommended — without them some checks cannot be read)</label>
34
+ <div class="actions">
35
+ <button class="secondary" id="cancel">Cancel</button>
36
+ <button class="primary" id="run">Run audit</button>
37
+ </div>
38
+ </section>
39
+
40
+ <!-- 3. Progress -->
41
+ <section class="screen hidden" id="screen-progress">
42
+ <h1 id="progress-title">Auditing this computer</h1>
43
+ <div class="card">
44
+ <div class="row"><b id="progress-step">Collecting evidence</b><span id="progress-count">0 / 0</span></div>
45
+ <div class="progress"><div id="progress-bar"></div></div>
46
+ <p class="muted" id="progress-current">Waiting for administrator approval…</p>
47
+ </div>
48
+ <div class="checklist" id="checklist"></div>
49
+ </section>
50
+
51
+ <!-- 4. Results -->
52
+ <section class="screen hidden" id="screen-done">
53
+ <h1>Audit complete</h1>
54
+ <div class="card" id="result-summary"></div>
55
+ <div class="actions">
56
+ <button class="secondary" id="again">Run another audit</button>
57
+ <button class="primary" id="save-again">Save report as PDF</button>
58
+ </div>
59
+ <p class="muted" id="saved-note"></p>
60
+ </section>
61
+
62
+ <!-- Cancelled / error -->
63
+ <section class="screen hidden" id="screen-stopped">
64
+ <h1 id="stopped-title">Audit cancelled</h1>
65
+ <p class="lead" id="stopped-text">Nothing was checked and nothing was changed.</p>
66
+ <div class="actions"><button class="primary" id="restart">Start again</button></div>
67
+ </section>
68
+ </main>
69
+
70
+ <!-- Save popup with 60-second countdown -->
71
+ <div class="modal hidden" id="save-modal" role="dialog" aria-modal="true" aria-labelledby="save-title">
72
+ <div class="modal-box">
73
+ <h2 id="save-title">Save the audit report as PDF?</h2>
74
+ <p>Choose where to save it. If you do not answer, it is saved automatically in
75
+ <b>Documents › Devseis Endpoint Audit</b> in <b id="countdown">60</b> seconds.</p>
76
+ <div class="progress thin"><div id="countdown-bar"></div></div>
77
+ <div class="actions">
78
+ <button class="secondary" id="save-docs">Save to Documents now</button>
79
+ <button class="primary" id="save-choose">Choose location…</button>
80
+ </div>
81
+ </div>
82
+ </div>
83
+
84
+ <script type="module" src="app.js"></script>
85
+ </body>
86
+ </html>
app/renderer/model.js ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Loads the auditor model in WebLLM (runs on this computer's GPU through WebGPU).
2
+ // The model is downloaded once and cached by WebLLM, so later runs work offline.
3
+ import { CreateMLCEngine, prebuiltAppConfig } from '../node_modules/@mlc-ai/web-llm/lib/index.js';
4
+
5
+ // Until the fine-tuned Devseis model is converted to MLC format and published, the matching base model
6
+ // is used. To switch, set CUSTOM_MODEL to:
7
+ // { model: 'https://huggingface.co/Devseis/<repo>', model_id: 'devseis-auditor-0.5b-q4f16_1', model_lib: '<Qwen2.5-0.5B q4f16_1 WebGPU lib URL from prebuiltAppConfig>' }
8
+ const CUSTOM_MODEL = null;
9
+ // q4f16 needs 16-bit GPU maths (shader-f16); many older and integrated GPUs only support the q4f32 build.
10
+ const BASE_MODEL = { f16: 'Qwen2.5-0.5B-Instruct-q4f16_1-MLC', f32: 'Qwen2.5-0.5B-Instruct-q4f32_1-MLC' };
11
+
12
+ export async function loadModel(onProgress) {
13
+ if (!('gpu' in navigator)) throw new Error('WebGPU is not available on this computer.');
14
+ const adapter = await navigator.gpu.requestAdapter();
15
+ if (!adapter) throw new Error('No WebGPU-capable graphics adapter was found.');
16
+
17
+ let appConfig = prebuiltAppConfig;
18
+ let modelId;
19
+ if (CUSTOM_MODEL) {
20
+ appConfig = { ...prebuiltAppConfig, model_list: [...prebuiltAppConfig.model_list, CUSTOM_MODEL] };
21
+ modelId = CUSTOM_MODEL.model_id;
22
+ } else {
23
+ const wanted = adapter.features.has('shader-f16') ? BASE_MODEL.f16 : BASE_MODEL.f32;
24
+ const entry = prebuiltAppConfig.model_list.find(m => m.model_id === wanted);
25
+ if (!entry) throw new Error('The base model is not in this WebLLM version.');
26
+ modelId = entry.model_id;
27
+ }
28
+
29
+ const engine = await CreateMLCEngine(modelId, {
30
+ appConfig,
31
+ initProgressCallback: report => onProgress({ progress: report.progress, text: report.text }),
32
+ });
33
+ return {
34
+ name: modelId,
35
+ fineTuned: Boolean(CUSTOM_MODEL),
36
+ async generate(system, prompt) {
37
+ const reply = await engine.chat.completions.create({
38
+ messages: [{ role: 'system', content: system }, { role: 'user', content: prompt }],
39
+ temperature: 0,
40
+ max_tokens: 900,
41
+ response_format: { type: 'json_object' },
42
+ });
43
+ return reply.choices[0].message.content;
44
+ },
45
+ };
46
+ }
app/renderer/report.js ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Builds the self-contained HTML report that the main process prints to PDF.
2
+ import { SECTION_TITLES } from './auditor-core.js';
3
+
4
+ const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
5
+ const STATUS_COLOR = { Compliant: '#1a7f37', 'Non-Compliant': '#c4242f', NotApplicable: '#6e7781', Pending: '#9a6700', Error: '#8250df' };
6
+ const RISK_COLOR = { High: '#c4242f', Medium: '#bc4c00', Low: '#9a6700', Unknown: '#8250df', None: '#6e7781' };
7
+ const badge = (text, color) => `<span class="badge" style="color:${color};border-color:${color}">${esc(text)}</span>`;
8
+
9
+ export function buildReportHtml({ evidence, findings, summary, ai, sha256, model, sources }) {
10
+ const host = evidence.host;
11
+ const started = evidence.audit.started_at.replace('T', ' ').slice(0, 19);
12
+ const counts = evidence.summary;
13
+
14
+ const sectionHtml = ['baseline', 'gdpr', 'aiact', 'org'].map(sectionId => {
15
+ const rows = evidence.results.filter(r => r.section === sectionId).map(r => {
16
+ const f = findings[r.id];
17
+ let detail = '';
18
+ if (f && r.status !== 'Compliant' && r.status !== 'NotApplicable') {
19
+ detail = `<tr class="detail"><td colspan="4">
20
+ <p>${esc(f.finding)}</p>
21
+ <p><b>Risk:</b> ${badge(f.risk.level, RISK_COLOR[f.risk.level] || '#6e7781')} ${esc(f.risk.reason)}</p>
22
+ ${f.recommendation.length ? `<p><b>What to do:</b></p><ol>${f.recommendation.map(s => `<li>${esc(s)}</li>`).join('')}</ol>` : ''}
23
+ ${f.verification ? `<p><b>How to verify:</b> ${esc(f.verification)}</p>` : ''}
24
+ <p class="refs">${f.references.map(esc).join(' · ')}</p>
25
+ </td></tr>`;
26
+ }
27
+ return `<tr><td>${esc(r.name)}</td><td>${badge(r.status, STATUS_COLOR[r.status])}</td><td>${esc(r.actual)}</td><td>${esc(r.expected)}</td></tr>${detail}`;
28
+ }).join('');
29
+ return `<h2>${esc(SECTION_TITLES[sectionId])}</h2>
30
+ <table><thead><tr><th style="width:30%">Check</th><th style="width:14%">Status</th><th>Found</th><th style="width:20%">Required</th></tr></thead><tbody>${rows}</tbody></table>`;
31
+ }).join('');
32
+
33
+ const aiHtml = ai ? `<h2>AI TOOLS FOUND — EU AI ACT CLASSIFICATION</h2>
34
+ <p>${esc(ai.summary)}</p>
35
+ <table><thead><tr><th>Tool</th><th>Approved</th><th>Default risk class</th><th>GDPR</th><th>Action</th></tr></thead><tbody>
36
+ ${ai.tools.map(t => `<tr><td><b>${esc(t.tool)}</b><br><span class="muted">${esc(t.kind)}</span></td><td>${t.approved ? 'Yes' : 'No'}</td>
37
+ <td>${esc(t.default_risk_class)}<br><span class="muted">High-risk if: ${esc(t.becomes_high_risk_if.join('; '))}</span></td>
38
+ <td>${esc(t.gdpr)}</td><td>${esc(t.action)}</td></tr>`).join('')}
39
+ </tbody></table><p class="muted">${esc(ai.log_retention)} The purpose of use was not stated; the classification must be confirmed for each actual use.</p>` : '';
40
+
41
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Devseis Endpoint Audit — ${esc(host.hostname)}</title>
42
+ <style>
43
+ body { font: 10.5pt/1.45 -apple-system, "Segoe UI", Roboto, Arial, sans-serif; color: #16181d; margin: 0; }
44
+ .cover { border-top: 6px solid #ED2939; padding: 18px 0 10px; margin-bottom: 14px; }
45
+ h1 { font-size: 22pt; margin: 0 0 4px; } h2 { font-size: 12.5pt; margin: 22px 0 8px; color: #00A1DE; letter-spacing: .03em; page-break-after: avoid; }
46
+ .meta { display: grid; grid-template-columns: 150px 1fr; gap: 2px 12px; font-size: 10pt; margin: 10px 0; }
47
+ .meta b { color: #5b6270; font-weight: 600; }
48
+ .score { display: flex; gap: 18px; align-items: center; background: #f5f6f9; border-radius: 8px; padding: 12px 16px; margin: 12px 0; }
49
+ .score .big { font-size: 30pt; font-weight: 800; }
50
+ .badge { display: inline-block; border: 1px solid; border-radius: 10px; padding: 0 7px; font-size: 8.5pt; font-weight: 700; white-space: nowrap; }
51
+ table { width: 100%; border-collapse: collapse; font-size: 9pt; page-break-inside: auto; }
52
+ th { text-align: left; background: #f5f6f9; padding: 5px 6px; font-size: 8.5pt; text-transform: uppercase; color: #5b6270; }
53
+ td { padding: 5px 6px; border-bottom: 1px solid #e2e5eb; vertical-align: top; word-break: break-word; }
54
+ tr { page-break-inside: avoid; }
55
+ tr.detail td { background: #fbfbfd; border-left: 3px solid #ED2939; }
56
+ tr.detail p { margin: 3px 0; } tr.detail ol { margin: 2px 0 4px 18px; padding: 0; }
57
+ .refs, .muted { color: #5b6270; font-size: 8.5pt; }
58
+ .gaps li { margin: 3px 0; }
59
+ .note { border-left: 3px solid #00A1DE; background: #f5f6f9; padding: 8px 12px; font-size: 9pt; margin-top: 18px; }
60
+ .foot { font-size: 8pt; color: #5b6270; margin-top: 18px; word-break: break-all; }
61
+ </style></head><body>
62
+ <div class="cover">
63
+ <div class="muted">DEVSEIS ENDPOINT AUDIT · READ-ONLY</div>
64
+ <h1>${esc(host.hostname)}</h1>
65
+ <div class="meta">
66
+ <b>Operating system</b><span>${esc(host.os_name)} ${esc(host.os_version)}${host.build ? ` (build ${esc(host.build)})` : ''}</span>
67
+ <b>Serial number</b><span>${esc(host.serial_number || '')}</span>
68
+ <b>Audit date</b><span>${esc(started)}</span>
69
+ <b>Run as</b><span>${esc(evidence.audit.execution_user)}${evidence.audit.is_admin ? ' (administrator)' : ' (not administrator — some checks could not be read)'}</span>
70
+ </div>
71
+ <div class="score"><div class="big">${summary.score.percent}%</div>
72
+ <div>${summary.score.compliant} of ${summary.score.assessed} assessed checks compliant<br>
73
+ ${Object.entries(counts).map(([k, v]) => `${badge(`${v} ${k}`, STATUS_COLOR[k])}`).join(' ')}</div></div>
74
+ </div>
75
+
76
+ <h2>EXECUTIVE SUMMARY</h2>
77
+ <p>${esc(summary.summary)}</p>
78
+ ${summary.next_steps.length ? `<p><b>Next steps</b></p><ol>${summary.next_steps.map(s => `<li>${esc(s)}</li>`).join('')}</ol>` : ''}
79
+ ${summary.top_gaps.length ? `<h2>TOP GAPS</h2><ul class="gaps">${summary.top_gaps.map(g =>
80
+ `<li>${badge(g.risk, RISK_COLOR[g.risk])} <b>${esc(g.name)}</b> — ${esc(g.found)}</li>`).join('')}</ul>` : ''}
81
+
82
+ ${sectionHtml}
83
+ ${aiHtml}
84
+
85
+ <div class="note">This report records the settings found on this computer at the audit date and compares them with the
86
+ Devseis baseline. It supports ISO 27001 internal audits, GDPR Article 32 and EU AI Act deployer duties; it is not a
87
+ certification and not legal advice. Organisational controls reflect the answers given in organisational.conf.</div>
88
+ <div class="foot">Evidence SHA-256: ${esc(sha256)}<br>
89
+ Findings written by: ${esc(model || 'built-in report writer')} (${sources.model} by the AI model, ${sources.template} by the built-in writer)<br>
90
+ Collector ${esc(evidence.source.collector)} ${esc(evidence.source.collector_version)} · catalog ${esc(evidence.catalog_version)}</div>
91
+ </body></html>`;
92
+ }
app/renderer/styles.css ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ --bg: #f5f6f9; --card: #fff; --text: #16181d; --muted: #5b6270; --line: #e2e5eb;
3
+ --red: #ED2939; --blue: #00A1DE; --ok: #1a7f37; --bad: #c4242f; --na: #6e7781; --pending: #9a6700; --err: #8250df;
4
+ }
5
+ @media (prefers-color-scheme: dark) {
6
+ :root { --bg: #0d1117; --card: #161b22; --text: #e6edf3; --muted: #9da7b3; --line: #2b313a;
7
+ --ok: #3fb950; --bad: #ff6b6b; --na: #8b949e; --pending: #d29922; --err: #b392f0; }
8
+ }
9
+ * { box-sizing: border-box; }
10
+ body { margin: 0; background: var(--bg); color: var(--text); font: 15px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
11
+ .bar { display: flex; justify-content: space-between; align-items: center; padding: 12px 24px; background: var(--card); border-bottom: 1px solid var(--line); }
12
+ .brand { font-weight: 700; display: flex; align-items: center; gap: 8px; }
13
+ .dot { width: 12px; height: 12px; border-radius: 50%; background: linear-gradient(135deg, var(--red), var(--blue)); }
14
+ .device { color: var(--muted); font-size: 13px; }
15
+ main { max-width: 900px; margin: 0 auto; padding: 28px 24px 48px; }
16
+ h1 { font-size: 26px; margin: 0 0 6px; }
17
+ h2 { font-size: 19px; margin: 0 0 8px; }
18
+ .lead { color: var(--muted); margin: 0 0 18px; }
19
+ .muted { color: var(--muted); font-size: 13px; margin: 8px 0 0; }
20
+ .hidden { display: none !important; }
21
+ .card { background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 16px 18px; margin-bottom: 16px; }
22
+ .row { display: flex; justify-content: space-between; gap: 12px; align-items: baseline; }
23
+ .progress { height: 10px; background: var(--line); border-radius: 999px; overflow: hidden; margin-top: 10px; }
24
+ .progress.thin { height: 6px; margin: 12px 0 4px; }
25
+ .progress > div { height: 100%; width: 0; background: linear-gradient(90deg, var(--blue), var(--red)); transition: width .25s; }
26
+ .sections { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 12px; margin-bottom: 14px; }
27
+ .section { background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 12px 14px; }
28
+ .section h3 { font-size: 14px; margin: 0 0 6px; display: flex; justify-content: space-between; }
29
+ .section h3 span { color: var(--muted); font-weight: 500; }
30
+ .section ul { margin: 0; padding-left: 18px; font-size: 13px; color: var(--muted); max-height: 170px; overflow: auto; }
31
+ .option { display: flex; gap: 8px; align-items: flex-start; margin: 6px 0 18px; font-size: 14px; }
32
+ .actions { display: flex; gap: 10px; justify-content: flex-end; flex-wrap: wrap; }
33
+ button { font: inherit; font-weight: 600; border-radius: 10px; padding: 10px 18px; cursor: pointer; border: 1px solid transparent; }
34
+ button.primary { background: var(--red); color: #fff; }
35
+ button.primary:hover { filter: brightness(.95); }
36
+ button.secondary { background: var(--card); color: var(--text); border-color: var(--line); }
37
+ button:disabled { opacity: .5; cursor: default; }
38
+ .checklist { background: var(--card); border: 1px solid var(--line); border-radius: 12px; max-height: 380px; overflow: auto; }
39
+ .check { display: grid; grid-template-columns: 22px 1fr auto; gap: 10px; align-items: center; padding: 7px 14px; border-bottom: 1px solid var(--line); font-size: 13.5px; }
40
+ .check:last-child { border-bottom: 0; }
41
+ .check .icon { width: 16px; height: 16px; border-radius: 50%; border: 2px solid var(--line); }
42
+ .check.running .icon { border-color: var(--blue); border-top-color: transparent; animation: spin .8s linear infinite; }
43
+ .check.done .icon { border: 0; background: currentColor; }
44
+ .check .group { color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: .04em; }
45
+ .s-Compliant { color: var(--ok); } .s-Non-Compliant { color: var(--bad); } .s-NotApplicable { color: var(--na); }
46
+ .s-Pending { color: var(--pending); } .s-Error { color: var(--err); }
47
+ .pills { display: flex; flex-wrap: wrap; gap: 8px; margin: 10px 0; }
48
+ .pill { font-size: 13px; font-weight: 600; padding: 3px 10px; border-radius: 999px; border: 1px solid var(--line); }
49
+ .score { font-size: 40px; font-weight: 800; line-height: 1; }
50
+ .gaps { margin: 10px 0 0; padding-left: 18px; }
51
+ .modal { position: fixed; inset: 0; background: rgba(10, 12, 16, .55); display: flex; align-items: center; justify-content: center; padding: 16px; }
52
+ .modal-box { background: var(--card); border-radius: 14px; padding: 22px; max-width: 480px; width: 100%; box-shadow: 0 20px 60px rgba(0,0,0,.35); }
53
+ @keyframes spin { to { transform: rotate(360deg); } }
app/test/prompt-parity.mjs ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Checks that the app builds exactly the prompts the model was trained on (training/build_dataset.py).
2
+ import { readFileSync } from 'node:fs';
3
+ import { execFileSync } from 'node:child_process';
4
+ import { fileURLToPath } from 'node:url';
5
+ import path from 'node:path';
6
+ import { Library, findingPrompt, summaryPrompt, aiPrompt } from '../renderer/auditor-core.js';
7
+
8
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
9
+ const read = (...p) => JSON.parse(readFileSync(path.join(root, ...p), 'utf8'));
10
+ const lib = new Library({ catalog: read('catalog', 'checks.json'), controls: read('library', 'controls.json'),
11
+ guidance: read('library', 'check_guidance.json'), aiTools: read('library', 'ai_tools.json') });
12
+ const evidence = readFileSync(path.join(root, 'synthetic', 'out', 'evidence.jsonl'), 'utf8').trim().split('\n').slice(0, 30).map(JSON.parse);
13
+
14
+ const python = execFileSync('python3', ['-c', `
15
+ import json, sys
16
+ sys.path.insert(0, "training")
17
+ import build_dataset as b
18
+ lib = b.Library()
19
+ out = []
20
+ for line in list(open("synthetic/out/evidence.jsonl"))[:30]:
21
+ r = json.loads(line)
22
+ item = {"findings": [b.build_finding(r, x, lib, __import__("random").Random(0))[0] for x in r["results"]],
23
+ "summary": b.build_summary(r, lib)[0]}
24
+ ai = b.build_ai_classification(r, lib)
25
+ item["ai"] = ai[0] if ai else None
26
+ out.append(item)
27
+ print(json.dumps(out))
28
+ `], { cwd: root, maxBuffer: 256 * 1024 * 1024 }).toString();
29
+ const expected = JSON.parse(python);
30
+
31
+ let compared = 0, mismatches = 0;
32
+ evidence.forEach((record, i) => {
33
+ const pairs = [
34
+ ...record.results.map((r, j) => [`record ${i} finding ${r.id}`, findingPrompt(record, r, lib), expected[i].findings[j]]),
35
+ [`record ${i} summary`, summaryPrompt(record, lib), expected[i].summary],
36
+ [`record ${i} ai`, aiPrompt(record, lib), expected[i].ai],
37
+ ];
38
+ for (const [label, js, py] of pairs) {
39
+ compared++;
40
+ if (js !== py) { mismatches++; if (mismatches <= 3) console.log(`MISMATCH ${label}\n--- js\n${js}\n--- py\n${py}`); }
41
+ }
42
+ });
43
+ console.log(`${compared - mismatches}/${compared} prompts identical (${new Set(evidence.map(r => r.host.os_family)).size} OS families)`);
44
+ process.exit(mismatches ? 1 : 0);
collectors/linux/audit.sh CHANGED
@@ -5,7 +5,8 @@
5
  # The only files it writes are the report (.txt) and evidence (.json) in the output folder.
6
  #
7
  # Run as root for complete results: sudo ./audit.sh
8
- # Options: --baseline FILE --org FILE --output DIR --help
 
9
 
10
  set -u
11
 
@@ -16,6 +17,7 @@ SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
16
  ROOT_DIR=$(cd "$SCRIPT_DIR/../.." && pwd)
17
  BASELINE_FILE="$ROOT_DIR/baseline.conf"
18
  ORG_FILE="$ROOT_DIR/organisational.conf"
 
19
  OUTPUT_DIR="/var/log/devseis-endpoint-audit"
20
 
21
  while [ $# -gt 0 ]; do
@@ -23,6 +25,7 @@ while [ $# -gt 0 ]; do
23
  --baseline) BASELINE_FILE="$2"; shift 2 ;;
24
  --org) ORG_FILE="$2"; shift 2 ;;
25
  --output) OUTPUT_DIR="$2"; shift 2 ;;
 
26
  -h|--help) sed -n '2,9p' "$0"; exit 0 ;;
27
  *) echo "Unknown option: $1" >&2; exit 2 ;;
28
  esac
@@ -90,6 +93,8 @@ R_ID=(); R_SECTION=(); R_NAME=(); R_STATUS=(); R_ACTUAL=(); R_EXPECTED=(); R_DET
90
  add() { # id section name status actual expected [detail]
91
  R_ID+=("$1"); R_SECTION+=("$2"); R_NAME+=("$3"); R_STATUS+=("$4")
92
  R_ACTUAL+=("$5"); R_EXPECTED+=("$6"); R_DETAIL+=("${7:-}")
 
 
93
  }
94
  needs_root() { add "$1" "$2" "$3" "Error" "not read" "$4" "Requires root: run the collector with sudo."; }
95
  pass_fail() { # condition-result(0/1) id section name actual expected [detail]
@@ -680,6 +685,7 @@ if mkdir -p "$OUTPUT_DIR" 2>/dev/null && [ -w "$OUTPUT_DIR" ]; then
680
  evidence_json > "$OUTPUT_DIR/$BASENAME.json"
681
  echo "Report: $OUTPUT_DIR/$BASENAME.txt" >&2
682
  echo "Evidence: $OUTPUT_DIR/$BASENAME.json" >&2
 
683
  else
684
  report
685
  echo "Could not write to $OUTPUT_DIR (use --output DIR). Evidence not saved." >&2
 
5
  # The only files it writes are the report (.txt) and evidence (.json) in the output folder.
6
  #
7
  # Run as root for complete results: sudo ./audit.sh
8
+ # Options: --baseline FILE --org FILE --output DIR --progress FILE --help
9
+ # --progress appends one line per finished check (id<TAB>status<TAB>name) for the Devseis app.
10
 
11
  set -u
12
 
 
17
  ROOT_DIR=$(cd "$SCRIPT_DIR/../.." && pwd)
18
  BASELINE_FILE="$ROOT_DIR/baseline.conf"
19
  ORG_FILE="$ROOT_DIR/organisational.conf"
20
+ PROGRESS_FILE=""
21
  OUTPUT_DIR="/var/log/devseis-endpoint-audit"
22
 
23
  while [ $# -gt 0 ]; do
 
25
  --baseline) BASELINE_FILE="$2"; shift 2 ;;
26
  --org) ORG_FILE="$2"; shift 2 ;;
27
  --output) OUTPUT_DIR="$2"; shift 2 ;;
28
+ --progress) PROGRESS_FILE="$2"; shift 2 ;;
29
  -h|--help) sed -n '2,9p' "$0"; exit 0 ;;
30
  *) echo "Unknown option: $1" >&2; exit 2 ;;
31
  esac
 
93
  add() { # id section name status actual expected [detail]
94
  R_ID+=("$1"); R_SECTION+=("$2"); R_NAME+=("$3"); R_STATUS+=("$4")
95
  R_ACTUAL+=("$5"); R_EXPECTED+=("$6"); R_DETAIL+=("${7:-}")
96
+ [ -n "$PROGRESS_FILE" ] && printf '%s\t%s\t%s\n' "$1" "$4" "$3" >> "$PROGRESS_FILE"
97
+ return 0
98
  }
99
  needs_root() { add "$1" "$2" "$3" "Error" "not read" "$4" "Requires root: run the collector with sudo."; }
100
  pass_fail() { # condition-result(0/1) id section name actual expected [detail]
 
685
  evidence_json > "$OUTPUT_DIR/$BASENAME.json"
686
  echo "Report: $OUTPUT_DIR/$BASENAME.txt" >&2
687
  echo "Evidence: $OUTPUT_DIR/$BASENAME.json" >&2
688
+ [ -n "$PROGRESS_FILE" ] && printf 'DONE\t%s\t%s\n' "$OUTPUT_DIR/$BASENAME.json" "$OUTPUT_DIR/$BASENAME.txt" >> "$PROGRESS_FILE"
689
  else
690
  report
691
  echo "Could not write to $OUTPUT_DIR (use --output DIR). Evidence not saved." >&2
collectors/macos/audit.sh CHANGED
@@ -5,7 +5,8 @@
5
  # The only files it writes are the report (.txt) and evidence (.json) in the output folder.
6
  #
7
  # Run as root for complete results: sudo ./audit.sh
8
- # Options: --baseline FILE --org FILE --output DIR --help
 
9
  #
10
  # Compatible with the bash 3.2 that ships with macOS.
11
 
@@ -18,6 +19,7 @@ SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
18
  ROOT_DIR=$(cd "$SCRIPT_DIR/../.." && pwd)
19
  BASELINE_FILE="$ROOT_DIR/baseline.conf"
20
  ORG_FILE="$ROOT_DIR/organisational.conf"
 
21
  OUTPUT_DIR="/Library/Logs/Devseis/EndpointAudit"
22
 
23
  while [ $# -gt 0 ]; do
@@ -25,6 +27,7 @@ while [ $# -gt 0 ]; do
25
  --baseline) BASELINE_FILE="$2"; shift 2 ;;
26
  --org) ORG_FILE="$2"; shift 2 ;;
27
  --output) OUTPUT_DIR="$2"; shift 2 ;;
 
28
  -h|--help) sed -n '2,12p' "$0"; exit 0 ;;
29
  *) echo "Unknown option: $1" >&2; exit 2 ;;
30
  esac
@@ -109,6 +112,8 @@ R_ID=(); R_SECTION=(); R_NAME=(); R_STATUS=(); R_ACTUAL=(); R_EXPECTED=(); R_DET
109
  add() { # id section name status actual expected [detail]
110
  R_ID+=("$1"); R_SECTION+=("$2"); R_NAME+=("$3"); R_STATUS+=("$4")
111
  R_ACTUAL+=("$5"); R_EXPECTED+=("$6"); R_DETAIL+=("${7:-}")
 
 
112
  }
113
  needs_root() { # id section name expected
114
  add "$1" "$2" "$3" "Error" "not read" "$4" "Requires root: run the collector with sudo."
@@ -703,6 +708,7 @@ if mkdir -p "$OUTPUT_DIR" 2>/dev/null && [ -w "$OUTPUT_DIR" ]; then
703
  evidence_json > "$OUTPUT_DIR/$BASENAME.json"
704
  echo "Report: $OUTPUT_DIR/$BASENAME.txt" >&2
705
  echo "Evidence: $OUTPUT_DIR/$BASENAME.json" >&2
 
706
  else
707
  report
708
  echo "Could not write to $OUTPUT_DIR (use --output DIR). Evidence not saved." >&2
 
5
  # The only files it writes are the report (.txt) and evidence (.json) in the output folder.
6
  #
7
  # Run as root for complete results: sudo ./audit.sh
8
+ # Options: --baseline FILE --org FILE --output DIR --progress FILE --help
9
+ # --progress appends one line per finished check (id<TAB>status<TAB>name) for the Devseis app.
10
  #
11
  # Compatible with the bash 3.2 that ships with macOS.
12
 
 
19
  ROOT_DIR=$(cd "$SCRIPT_DIR/../.." && pwd)
20
  BASELINE_FILE="$ROOT_DIR/baseline.conf"
21
  ORG_FILE="$ROOT_DIR/organisational.conf"
22
+ PROGRESS_FILE=""
23
  OUTPUT_DIR="/Library/Logs/Devseis/EndpointAudit"
24
 
25
  while [ $# -gt 0 ]; do
 
27
  --baseline) BASELINE_FILE="$2"; shift 2 ;;
28
  --org) ORG_FILE="$2"; shift 2 ;;
29
  --output) OUTPUT_DIR="$2"; shift 2 ;;
30
+ --progress) PROGRESS_FILE="$2"; shift 2 ;;
31
  -h|--help) sed -n '2,12p' "$0"; exit 0 ;;
32
  *) echo "Unknown option: $1" >&2; exit 2 ;;
33
  esac
 
112
  add() { # id section name status actual expected [detail]
113
  R_ID+=("$1"); R_SECTION+=("$2"); R_NAME+=("$3"); R_STATUS+=("$4")
114
  R_ACTUAL+=("$5"); R_EXPECTED+=("$6"); R_DETAIL+=("${7:-}")
115
+ [ -n "$PROGRESS_FILE" ] && printf '%s\t%s\t%s\n' "$1" "$4" "$3" >> "$PROGRESS_FILE"
116
+ return 0
117
  }
118
  needs_root() { # id section name expected
119
  add "$1" "$2" "$3" "Error" "not read" "$4" "Requires root: run the collector with sudo."
 
708
  evidence_json > "$OUTPUT_DIR/$BASENAME.json"
709
  echo "Report: $OUTPUT_DIR/$BASENAME.txt" >&2
710
  echo "Evidence: $OUTPUT_DIR/$BASENAME.json" >&2
711
+ [ -n "$PROGRESS_FILE" ] && printf 'DONE\t%s\t%s\n' "$OUTPUT_DIR/$BASENAME.json" "$OUTPUT_DIR/$BASENAME.txt" >> "$PROGRESS_FILE"
712
  else
713
  report
714
  echo "Could not write to $OUTPUT_DIR (use --output DIR). Evidence not saved." >&2
collectors/windows/audit.ps1 CHANGED
@@ -18,7 +18,9 @@
18
  param(
19
  [string]$Baseline = (Join-Path $PSScriptRoot '..\..\baseline.conf'),
20
  [string]$Organisational = (Join-Path $PSScriptRoot '..\..\organisational.conf'),
21
- [string]$Output = (Join-Path $env:ProgramData 'Devseis\EndpointAudit')
 
 
22
  )
23
 
24
  Set-StrictMode -Version 2.0
@@ -79,6 +81,7 @@ function Add-Result($Id, $Section, $Name, $Status, $Actual, $Expected, $Detail)
79
  $item = [ordered]@{ id = $Id; section = $Section; name = $Name; status = $Status; actual = "$Actual"; expected = "$Expected" }
80
  if ($Detail) { $item['detail'] = "$Detail" }
81
  $Results.Add($item)
 
82
  }
83
  function Pass([bool]$Ok, $Actual, $Detail) {
84
  $status = 'Non-Compliant'; if ($Ok) { $status = 'Compliant' }
@@ -566,6 +569,7 @@ try {
566
  [IO.File]::WriteAllText("$base.json", ($Evidence | ConvertTo-Json -Depth 6), $utf8)
567
  Write-Host "Report: $base.txt"
568
  Write-Host "Evidence: $base.json"
 
569
  } catch {
570
  Write-Error "Could not write to $Output (use -Output DIR): $($_.Exception.Message)" -ErrorAction Continue
571
  exit 2
 
18
  param(
19
  [string]$Baseline = (Join-Path $PSScriptRoot '..\..\baseline.conf'),
20
  [string]$Organisational = (Join-Path $PSScriptRoot '..\..\organisational.conf'),
21
+ [string]$Output = (Join-Path $env:ProgramData 'Devseis\EndpointAudit'),
22
+ # Appends one line per finished check (id<TAB>status<TAB>name) for the Devseis app.
23
+ [string]$Progress = ''
24
  )
25
 
26
  Set-StrictMode -Version 2.0
 
81
  $item = [ordered]@{ id = $Id; section = $Section; name = $Name; status = $Status; actual = "$Actual"; expected = "$Expected" }
82
  if ($Detail) { $item['detail'] = "$Detail" }
83
  $Results.Add($item)
84
+ if ($Progress) { [IO.File]::AppendAllText($Progress, "$Id`t$Status`t$Name`n") }
85
  }
86
  function Pass([bool]$Ok, $Actual, $Detail) {
87
  $status = 'Non-Compliant'; if ($Ok) { $status = 'Compliant' }
 
569
  [IO.File]::WriteAllText("$base.json", ($Evidence | ConvertTo-Json -Depth 6), $utf8)
570
  Write-Host "Report: $base.txt"
571
  Write-Host "Evidence: $base.json"
572
+ if ($Progress) { [IO.File]::AppendAllText($Progress, "DONE`t$base.json`t$base.txt`n") }
573
  } catch {
574
  Write-Error "Could not write to $Output (use -Output DIR): $($_.Exception.Message)" -ErrorAction Continue
575
  exit 2
training/train_lora.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Fine-tune the auditor model with LoRA, fully offline, on CPU (or GPU if present).
3
+
4
+ The base model must already be in a local folder (downloaded once, see training/README.md).
5
+ No network access is used during training (HF_HUB_OFFLINE is forced on).
6
+
7
+ Usage (from the endpoint-audit folder, with the training environment):
8
+ training/.venv/bin/python training/train_lora.py --benchmark # time 10 steps, estimate the full run
9
+ training/.venv/bin/python training/train_lora.py --max-train 3000 # train on a balanced subset
10
+ training/.venv/bin/python training/train_lora.py --max-train 3000 --resume # continue after a stop
11
+
12
+ Loss is computed on the assistant answer only. Examples longer than --max-len tokens are skipped
13
+ (never truncated), so the model always sees complete prompts and answers.
14
+ """
15
+ import argparse
16
+ import json
17
+ import math
18
+ import os
19
+ import random
20
+ import time
21
+
22
+ os.environ["HF_HUB_OFFLINE"] = "1"
23
+ os.environ["TRANSFORMERS_OFFLINE"] = "1"
24
+
25
+ import torch # noqa: E402
26
+ from peft import LoraConfig, PeftModel, get_peft_model # noqa: E402
27
+ from transformers import AutoModelForCausalLM, AutoTokenizer # noqa: E402
28
+
29
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
30
+ DEFAULT_BASE = os.path.join(ROOT, "training", "models", "Qwen2.5-0.5B-Instruct")
31
+ LORA_TARGETS = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
32
+
33
+
34
+ def load_examples(path):
35
+ with open(path, encoding="utf-8") as handle:
36
+ return [json.loads(line) for line in handle]
37
+
38
+
39
+ def balanced_subset(examples, limit, seed):
40
+ """Pick up to `limit` examples spread evenly over task, OS and status."""
41
+ if not limit or limit >= len(examples):
42
+ return examples
43
+ groups = {}
44
+ for item in examples:
45
+ meta = item["meta"]
46
+ groups.setdefault((meta["task"], meta["os"], meta.get("status", "")), []).append(item)
47
+ rng = random.Random(seed)
48
+ for items in groups.values():
49
+ rng.shuffle(items)
50
+ chosen, keys = [], sorted(groups)
51
+ while len(chosen) < limit and keys:
52
+ for key in list(keys):
53
+ if groups[key]:
54
+ chosen.append(groups[key].pop())
55
+ if len(chosen) == limit:
56
+ break
57
+ else:
58
+ keys.remove(key)
59
+ rng.shuffle(chosen)
60
+ return chosen
61
+
62
+
63
+ def encode(tokenizer, example, max_len):
64
+ """Token ids with labels masked (-100) everywhere except the assistant answer."""
65
+ messages = example["messages"]
66
+ prompt_ids = tokenizer.apply_chat_template(messages[:-1], tokenize=True, add_generation_prompt=True)
67
+ full_ids = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=False)
68
+ if full_ids[:len(prompt_ids)] != prompt_ids or len(full_ids) > max_len:
69
+ return None
70
+ labels = [-100] * len(prompt_ids) + full_ids[len(prompt_ids):]
71
+ return {"input_ids": full_ids, "labels": labels}
72
+
73
+
74
+ def batches(encoded, batch_size, pad_id):
75
+ for start in range(0, len(encoded), batch_size):
76
+ chunk = encoded[start:start + batch_size]
77
+ width = max(len(e["input_ids"]) for e in chunk)
78
+ ids = torch.full((len(chunk), width), pad_id, dtype=torch.long)
79
+ labels = torch.full((len(chunk), width), -100, dtype=torch.long)
80
+ mask = torch.zeros((len(chunk), width), dtype=torch.long)
81
+ for row, item in enumerate(chunk):
82
+ n = len(item["input_ids"])
83
+ ids[row, :n] = torch.tensor(item["input_ids"])
84
+ labels[row, :n] = torch.tensor(item["labels"])
85
+ mask[row, :n] = 1
86
+ yield ids, labels, mask
87
+
88
+
89
+ @torch.no_grad()
90
+ def evaluate(model, encoded, pad_id, batch_size):
91
+ model.eval()
92
+ total, count = 0.0, 0
93
+ for ids, labels, mask in batches(encoded, batch_size, pad_id):
94
+ total += model(input_ids=ids, attention_mask=mask, labels=labels).loss.item()
95
+ count += 1
96
+ model.train()
97
+ return total / max(count, 1)
98
+
99
+
100
+ def main():
101
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
102
+ parser.add_argument("--base", default=DEFAULT_BASE, help="local folder with the base model")
103
+ parser.add_argument("--data", default=os.path.join(ROOT, "training", "out"))
104
+ parser.add_argument("--output", default=os.path.join(ROOT, "training", "models", "auditor-lora"))
105
+ parser.add_argument("--max-train", type=int, default=3000, help="balanced subset size (0 = all)")
106
+ parser.add_argument("--max-val", type=int, default=200)
107
+ parser.add_argument("--max-len", type=int, default=2048, help="skip examples longer than this many tokens")
108
+ parser.add_argument("--epochs", type=float, default=1.0)
109
+ parser.add_argument("--batch-size", type=int, default=1)
110
+ parser.add_argument("--grad-accum", type=int, default=8)
111
+ parser.add_argument("--lr", type=float, default=2e-4)
112
+ parser.add_argument("--lora-r", type=int, default=16)
113
+ parser.add_argument("--lora-alpha", type=int, default=32)
114
+ parser.add_argument("--save-every", type=int, default=50, help="optimizer steps between checkpoints")
115
+ parser.add_argument("--eval-every", type=int, default=100)
116
+ parser.add_argument("--threads", type=int, default=os.cpu_count())
117
+ parser.add_argument("--seed", type=int, default=13)
118
+ parser.add_argument("--benchmark", action="store_true", help="run 10 optimizer steps, report speed and estimated total time")
119
+ parser.add_argument("--resume", action="store_true", help="continue from the last checkpoint in --output")
120
+ args = parser.parse_args()
121
+
122
+ torch.manual_seed(args.seed)
123
+ torch.set_num_threads(args.threads)
124
+ device = "cuda" if torch.cuda.is_available() else "cpu"
125
+ print(f"Device: {device}, threads: {args.threads}, base: {args.base}")
126
+
127
+ tokenizer = AutoTokenizer.from_pretrained(args.base, local_files_only=True)
128
+ pad_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id
129
+
130
+ train_raw = balanced_subset(load_examples(os.path.join(args.data, "train.jsonl")), args.max_train, args.seed)
131
+ val_raw = balanced_subset(load_examples(os.path.join(args.data, "validation.jsonl")), args.max_val, args.seed)
132
+ train = [e for e in (encode(tokenizer, x, args.max_len) for x in train_raw) if e]
133
+ val = [e for e in (encode(tokenizer, x, args.max_len) for x in val_raw) if e]
134
+ # Group similar lengths to reduce padding, but keep task order mixed across groups.
135
+ train.sort(key=lambda e: len(e["input_ids"]))
136
+ groups = [train[i:i + args.batch_size] for i in range(0, len(train), args.batch_size)]
137
+ random.Random(args.seed).shuffle(groups)
138
+ train = [e for g in groups for e in g]
139
+ tokens = sum(len(e["input_ids"]) for e in train)
140
+ print(f"Train examples: {len(train)} ({len(train_raw) - len(train)} skipped as longer than {args.max_len} tokens), "
141
+ f"{tokens:,} tokens; validation: {len(val)}")
142
+
143
+ model = AutoModelForCausalLM.from_pretrained(args.base, local_files_only=True, torch_dtype=torch.float32)
144
+ model.config.use_cache = False
145
+ model.gradient_checkpointing_enable()
146
+ model.enable_input_require_grads()
147
+ last_checkpoint = os.path.join(args.output, "last")
148
+ state_path = os.path.join(last_checkpoint, "trainer_state.json")
149
+ if args.resume and os.path.exists(state_path):
150
+ model = PeftModel.from_pretrained(model, last_checkpoint, is_trainable=True)
151
+ with open(state_path) as handle:
152
+ state = json.load(handle)
153
+ print(f"Resuming from step {state['step']}")
154
+ else:
155
+ model = get_peft_model(model, LoraConfig(r=args.lora_r, lora_alpha=args.lora_alpha, lora_dropout=0.05,
156
+ target_modules=LORA_TARGETS, task_type="CAUSAL_LM"))
157
+ state = {"step": 0, "micro": 0, "history": []}
158
+ model.print_trainable_parameters()
159
+ model.to(device)
160
+ model.train()
161
+
162
+ optimizer = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=args.lr, weight_decay=0.0)
163
+ micro_per_epoch = math.ceil(len(train) / args.batch_size)
164
+ total_steps = math.ceil(micro_per_epoch * args.epochs / args.grad_accum)
165
+ if args.benchmark:
166
+ total_steps = min(total_steps, state["step"] + 10)
167
+ warmup = max(1, int(0.03 * total_steps))
168
+ scheduler = torch.optim.lr_scheduler.LambdaLR(
169
+ optimizer, lambda s: min(1.0, (s + 1) / warmup) * max(0.0, 1 - s / max(total_steps, 1)) if s >= warmup
170
+ else (s + 1) / warmup)
171
+ for _ in range(state["step"]):
172
+ scheduler.step()
173
+
174
+ def save(tag):
175
+ path = os.path.join(args.output, tag)
176
+ model.save_pretrained(path)
177
+ tokenizer.save_pretrained(path)
178
+ with open(os.path.join(path, "trainer_state.json"), "w") as handle:
179
+ json.dump(state, handle, indent=1)
180
+
181
+ batch_list = list(batches(train, args.batch_size, pad_id))
182
+ started = time.time()
183
+ step_start = time.time()
184
+ running = 0.0
185
+ micro = state["micro"]
186
+ while state["step"] < total_steps:
187
+ ids, labels, mask = batch_list[micro % len(batch_list)]
188
+ loss = model(input_ids=ids.to(device), attention_mask=mask.to(device), labels=labels.to(device)).loss
189
+ (loss / args.grad_accum).backward()
190
+ running += loss.item()
191
+ micro += 1
192
+ if micro % args.grad_accum:
193
+ continue
194
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
195
+ optimizer.step()
196
+ scheduler.step()
197
+ optimizer.zero_grad()
198
+ state["step"] += 1
199
+ state["micro"] = micro
200
+ seconds = time.time() - step_start
201
+ step_start = time.time()
202
+ avg = running / args.grad_accum
203
+ running = 0.0
204
+ state["history"].append({"step": state["step"], "loss": round(avg, 4), "seconds": round(seconds, 1)})
205
+ remaining = (total_steps - state["step"]) * (time.time() - started) / max(len(state["history"]) - 0, 1)
206
+ print(f"step {state['step']}/{total_steps} loss {avg:.4f} {seconds:.1f}s/step ~{remaining / 3600:.1f} h left", flush=True)
207
+ if not args.benchmark and state["step"] % args.save_every == 0:
208
+ save("last")
209
+ if not args.benchmark and val and state["step"] % args.eval_every == 0:
210
+ val_loss = evaluate(model, val, pad_id, args.batch_size)
211
+ state["history"][-1]["val_loss"] = round(val_loss, 4)
212
+ print(f" validation loss {val_loss:.4f}", flush=True)
213
+
214
+ if args.benchmark:
215
+ per_step = sum(h["seconds"] for h in state["history"][-10:]) / max(len(state["history"][-10:]), 1)
216
+ full = math.ceil(micro_per_epoch * args.epochs / args.grad_accum)
217
+ print(f"\nBENCHMARK: {per_step:.1f} s per optimizer step ({args.grad_accum} examples). "
218
+ f"Full run of {full} steps on {len(train)} examples: about {full * per_step / 3600:.1f} hours.")
219
+ return
220
+ save("last")
221
+ save("final")
222
+ if val:
223
+ print(f"Final validation loss: {evaluate(model, val, pad_id, args.batch_size):.4f}")
224
+ print(f"Adapter saved to {os.path.join(args.output, 'final')}")
225
+
226
+
227
+ if __name__ == "__main__":
228
+ main()