interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / src / visor / visor_evidence.c

690 lines · 27662 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* Omega Visor V1 - lane 4: evidence (receipt) inspection. See visor_evidence.h. */
18#include "visor_evidence.h"
19
20#include <ctype.h>
21#include <dirent.h>
22#include <stdarg.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <sys/stat.h>
27
28#include "omega_canonical.h"
29#include "sha256.h"
30
31/* ------------------------------------------------------------------ */
32/* Strict JSON scanner over one fixed buffer and one fixed token pool. */
33/* ------------------------------------------------------------------ */
34enum { JT_OBJ = 1, JT_ARR, JT_STR, JT_PRIM };
35#define J_MAX_TOKENS 32768
36#define J_MAX_DEPTH 64
37
38typedef struct {
39 uint8_t type;
40 uint8_t is_key;
41 int32_t start, end; /* STR: content [start,end); others: [start,end) raw */
42 int32_t next; /* index of the first token after this subtree */
43} JTok;
44
45static char g_buf[VISOR_EVIDENCE_MAX_FILE_BYTES + 1];
46static size_t g_len;
47static JTok g_tok[J_MAX_TOKENS];
48static int g_ntok;
49
50static void j_ws(size_t *p) {
51 while (*p < g_len && (g_buf[*p] == ' ' || g_buf[*p] == '\t' || g_buf[*p] == '\n' || g_buf[*p] == '\r')) (*p)++;
52}
53
54static int j_new(uint8_t type, size_t start) {
55 if (g_ntok >= J_MAX_TOKENS) return -1;
56 JTok *t = &g_tok[g_ntok];
57 memset(t, 0, sizeof(*t));
58 t->type = type;
59 t->start = (int32_t)start;
60 return g_ntok++;
61}
62
63static int j_string(size_t *p, bool is_key) {
64 if (*p >= g_len || g_buf[*p] != '"') return -1;
65 int t = j_new(JT_STR, *p + 1);
66 if (t < 0) return -1;
67 g_tok[t].is_key = is_key;
68 size_t i = *p + 1;
69 while (i < g_len) {
70 unsigned char c = (unsigned char)g_buf[i];
71 if (c == '"') break;
72 if (c < 0x20) return -1;
73 if (c == '\\') {
74 if (i + 1 >= g_len) return -1;
75 char e = g_buf[i + 1];
76 if (e == 'u') {
77 if (i + 5 >= g_len) return -1;
78 for (int k = 2; k < 6; ++k) if (!isxdigit((unsigned char)g_buf[i + k])) return -1;
79 i += 6;
80 continue;
81 }
82 if (!strchr("\"\\/bfnrt", e)) return -1;
83 i += 2;
84 continue;
85 }
86 i++;
87 }
88 if (i >= g_len) return -1;
89 g_tok[t].end = (int32_t)i;
90 g_tok[t].next = g_ntok;
91 *p = i + 1;
92 return t;
93}
94
95static int j_prim(size_t *p) {
96 size_t s = *p;
97 int t = j_new(JT_PRIM, s);
98 if (t < 0) return -1;
99 static const char *const lits[] = { "true", "false", "null" };
100 for (int k = 0; k < 3; ++k) {
101 size_t L = strlen(lits[k]);
102 if (s + L <= g_len && memcmp(g_buf + s, lits[k], L) == 0) { *p = s + L; goto done; }
103 }
104 {
105 size_t i = s;
106 if (i < g_len && g_buf[i] == '-') i++;
107 if (i >= g_len || !isdigit((unsigned char)g_buf[i])) return -1;
108 if (g_buf[i] == '0') i++; else while (i < g_len && isdigit((unsigned char)g_buf[i])) i++;
109 if (i < g_len && g_buf[i] == '.') {
110 i++;
111 if (i >= g_len || !isdigit((unsigned char)g_buf[i])) return -1;
112 while (i < g_len && isdigit((unsigned char)g_buf[i])) i++;
113 }
114 if (i < g_len && (g_buf[i] == 'e' || g_buf[i] == 'E')) {
115 i++;
116 if (i < g_len && (g_buf[i] == '+' || g_buf[i] == '-')) i++;
117 if (i >= g_len || !isdigit((unsigned char)g_buf[i])) return -1;
118 while (i < g_len && isdigit((unsigned char)g_buf[i])) i++;
119 }
120 *p = i;
121 }
122done:
123 g_tok[t].end = (int32_t)*p;
124 g_tok[t].next = g_ntok;
125 return t;
126}
127
128static int j_value(size_t *p, int depth) {
129 if (depth > J_MAX_DEPTH) return -1;
130 j_ws(p);
131 if (*p >= g_len) return -1;
132 char c = g_buf[*p];
133 if (c == '"') return j_string(p, false);
134 if (c != '{' && c != '[') return j_prim(p);
135 int t = j_new(c == '{' ? JT_OBJ : JT_ARR, *p);
136 if (t < 0) return -1;
137 char close = c == '{' ? '}' : ']';
138 (*p)++;
139 j_ws(p);
140 if (*p < g_len && g_buf[*p] == close) {
141 (*p)++;
142 } else {
143 for (;;) {
144 if (c == '{') {
145 j_ws(p);
146 if (j_string(p, true) < 0) return -1;
147 j_ws(p);
148 if (*p >= g_len || g_buf[*p] != ':') return -1;
149 (*p)++;
150 }
151 if (j_value(p, depth + 1) < 0) return -1;
152 j_ws(p);
153 if (*p >= g_len) return -1;
154 if (g_buf[*p] == ',') { (*p)++; continue; }
155 if (g_buf[*p] == close) { (*p)++; break; }
156 return -1;
157 }
158 }
159 g_tok[t].end = (int32_t)*p;
160 g_tok[t].next = g_ntok;
161 return t;
162}
163
164/* Parse g_buf[0..g_len). Top level must be an object. */
165static int j_parse(void) {
166 g_ntok = 0;
167 size_t p = 0;
168 int t = j_value(&p, 0);
169 if (t != 0 || g_tok[0].type != JT_OBJ) return -1;
170 j_ws(&p);
171 return p == g_len ? 0 : -1;
172}
173
174static bool j_key_eq(int i, const char *key) {
175 if (i < 0 || g_tok[i].type != JT_STR) return false;
176 size_t L = (size_t)(g_tok[i].end - g_tok[i].start);
177 return strlen(key) == L && memcmp(g_buf + g_tok[i].start, key, L) == 0;
178}
179
180/* Value token of `key` directly inside object `obj`, or -1. */
181static int j_get(int obj, const char *key) {
182 if (obj < 0 || g_tok[obj].type != JT_OBJ) return -1;
183 for (int k = obj + 1; k < g_tok[obj].next; k = g_tok[k + 1].next)
184 if (j_key_eq(k, key)) return k + 1;
185 return -1;
186}
187
188/* First value of `key` anywhere, in document order, or -1. */
189static int j_find_any(const char *key) {
190 for (int i = 0; i < g_ntok; ++i)
191 if (g_tok[i].is_key && j_key_eq(i, key)) return i + 1;
192 return -1;
193}
194
195static size_t j_copy(int i, char *out, size_t n) {
196 if (!out || n == 0) return 0;
197 out[0] = 0;
198 if (i < 0 || (g_tok[i].type != JT_STR && g_tok[i].type != JT_PRIM)) return 0;
199 size_t L = (size_t)(g_tok[i].end - g_tok[i].start);
200 if (L >= n) L = n - 1;
201 memcpy(out, g_buf + g_tok[i].start, L);
202 out[L] = 0;
203 return L;
204}
205
206static bool j_is_lit(int i, const char *lit) {
207 return i >= 0 && g_tok[i].type == JT_PRIM &&
208 (size_t)(g_tok[i].end - g_tok[i].start) == strlen(lit) &&
209 memcmp(g_buf + g_tok[i].start, lit, strlen(lit)) == 0;
210}
211
212static bool j_u32(int i, uint32_t *out) {
213 char tmp[24];
214 if (i < 0 || g_tok[i].type != JT_PRIM) return false;
215 j_copy(i, tmp, sizeof(tmp));
216 if (!isdigit((unsigned char)tmp[0])) return false;
217 char *end = NULL;
218 unsigned long v = strtoul(tmp, &end, 10);
219 if (!end || *end || v > UINT32_MAX) return false;
220 *out = (uint32_t)v;
221 return true;
222}
223
224static bool is_hex_n(const char *s, size_t n) {
225 if (strlen(s) != n) return false;
226 for (size_t i = 0; i < n; ++i) if (!isxdigit((unsigned char)s[i])) return false;
227 return true;
228}
229
230/* ------------------------------------------------------------------ */
231/* Record extraction */
232/* ------------------------------------------------------------------ */
233const char *visor_qual_scope_name(VisorQualScope s) {
234 switch (s) {
235 case VISOR_QUAL_UNKNOWN: return "UNKNOWN";
236 case VISOR_QUAL_SIMULATED: return "SIMULATED";
237 case VISOR_QUAL_HOST: return "HOST";
238 case VISOR_QUAL_QEMU: return "QEMU";
239 case VISOR_QUAL_SILICON: return "SILICON";
240 }
241 return "UNKNOWN";
242}
243
244static void first_hex_str(const char *const *keys, size_t nkeys, size_t hexlen, bool anywhere,
245 char *out, size_t n, bool prefix_sha) {
246 char tmp[80];
247 for (size_t k = 0; k < nkeys; ++k) {
248 int v = anywhere ? j_find_any(keys[k]) : j_get(0, keys[k]);
249 if (v < 0 || g_tok[v].type != JT_STR) continue;
250 j_copy(v, tmp, sizeof(tmp));
251 if (!is_hex_n(tmp, hexlen)) continue;
252 snprintf(out, n, "%s%s", prefix_sha ? "sha256:" : "", tmp);
253 return;
254 }
255}
256
257static void add_part(char *out, size_t n, const char *label, int v) {
258 char tmp[64];
259 if (v < 0 || g_tok[v].type != JT_STR || j_copy(v, tmp, sizeof(tmp)) == 0) return;
260 size_t len = strlen(out);
261 if (len >= n - 1) return;
262 snprintf(out + len, n - len, "%s%s=%s", len ? " " : "", label, tmp);
263}
264
265static void fill_machine(VisorEvidenceRecord *r) {
266 int mi = j_get(0, "machine_identity");
267 if (mi >= 0 && g_tok[mi].type == JT_OBJ) {
268 add_part(r->machine, sizeof(r->machine), "node", j_get(mi, "node"));
269 add_part(r->machine, sizeof(r->machine), "arch", j_get(mi, "architecture"));
270 add_part(r->machine, sizeof(r->machine), "kernel", j_get(mi, "release"));
271 return;
272 }
273 int h = j_get(0, "host");
274 if (h >= 0 && g_tok[h].type == JT_OBJ) {
275 add_part(r->machine, sizeof(r->machine), "os", j_get(h, "sysname"));
276 add_part(r->machine, sizeof(r->machine), "os", j_get(h, "os"));
277 add_part(r->machine, sizeof(r->machine), "arch", j_get(h, "machine"));
278 add_part(r->machine, sizeof(r->machine), "arch", j_get(h, "arch"));
279 add_part(r->machine, sizeof(r->machine), "kernel", j_get(h, "release"));
280 add_part(r->machine, sizeof(r->machine), "core", j_get(h, "core_class_midr_part"));
281 }
282}
283
284/* Count PASS/FAIL string verdicts in a gates object; remember a headline gate. */
285static void count_gates(int obj, VisorEvidenceRecord *r, char *headline, size_t hn) {
286 if (obj < 0 || g_tok[obj].type != JT_OBJ) return;
287 char key[96], val[16];
288 for (int k = obj + 1; k < g_tok[obj].next; k = g_tok[k + 1].next) {
289 int v = k + 1;
290 if (g_tok[v].type != JT_STR) continue;
291 j_copy(v, val, sizeof(val));
292 bool pass = strcmp(val, "PASS") == 0, fail = strcmp(val, "FAIL") == 0;
293 if (!pass && !fail) continue;
294 r->gates_run++;
295 if (pass) r->gates_passed++;
296 j_copy(k, key, sizeof(key));
297 size_t kl = strlen(key);
298 /* Prefer the last *_PASS gate (the rollup); else the first verdict seen. */
299 if ((kl > 5 && strcmp(key + kl - 5, "_PASS") == 0) || !headline[0])
300 snprintf(headline, hn, "%.90s=%s", key, val);
301 }
302}
303
304static void fill_gates_and_claim(VisorEvidenceRecord *r) {
305 char headline[112] = {0}, label[96] = {0}, status[64] = {0};
306 int qg = j_get(0, "qualification_gates");
307 uint32_t tot = 0, pas = 0;
308 if (qg >= 0 && j_u32(j_get(qg, "total"), &tot) && j_u32(j_get(qg, "passed"), &pas)) {
309 r->gates_run = tot;
310 r->gates_passed = pas;
311 } else {
312 count_gates(j_get(0, "gates"), r, headline, sizeof(headline));
313 count_gates(j_get(0, "gate"), r, headline, sizeof(headline));
314 if (qg >= 0) count_gates(j_get(qg, "gates"), r, headline, sizeof(headline));
315 }
316 static const char *const label_keys[] = { "schema", "milestone", "stage_title", "contract_id" };
317 for (size_t i = 0; i < 4 && !label[0]; ++i) j_copy(j_get(0, label_keys[i]), label, sizeof(label));
318 j_copy(j_get(0, "status"), status, sizeof(status));
319 const char *what = headline[0] ? headline : status;
320 if (label[0] && what[0]) snprintf(r->claim, sizeof(r->claim), "%.60s: %.64s", label, what);
321 else if (label[0]) snprintf(r->claim, sizeof(r->claim), "%.120s", label);
322 else snprintf(r->claim, sizeof(r->claim), "%.120s", what);
323}
324
325static void scope_signal(VisorQualScope s, const char *basis, VisorQualScope *cur, bool *have,
326 VisorEvidenceRecord *r) {
327 if (!*have || s < *cur) {
328 *cur = s;
329 snprintf(r->scope_basis, sizeof(r->scope_basis), "%s", basis);
330 }
331 *have = true;
332}
333
334static void fill_scope(VisorEvidenceRecord *r) {
335 VisorQualScope cur = VISOR_QUAL_UNKNOWN;
336 bool have = false;
337 int so = j_get(0, "silicon_observed");
338 if (j_is_lit(so, "true")) scope_signal(VISOR_QUAL_SILICON, "silicon_observed=true", &cur, &have, r);
339 if (j_is_lit(so, "false")) scope_signal(VISOR_QUAL_HOST, "silicon_observed=false", &cur, &have, r);
340 if (j_find_any("gpu_uuid") >= 0) scope_signal(VISOR_QUAL_SILICON, "gpu_uuid", &cur, &have, r);
341 if (j_find_any("compute_class") >= 0) scope_signal(VISOR_QUAL_SILICON, "compute_class", &cur, &have, r);
342 /* Only an explicit execution target counts; gate names or machine-model
343 * names that merely mention QEMU (e.g. *_QEMU_VIRT_PASS) do not. */
344 if (j_find_any("qemu_target") >= 0) scope_signal(VISOR_QUAL_QEMU, "qemu_target", &cur, &have, r);
345 static const char *const scope_keys[] = { "hardware_scope", "scope" };
346 for (size_t k = 0; k < 2; ++k) {
347 int v = j_get(0, scope_keys[k]);
348 if (v < 0 || g_tok[v].type != JT_STR) continue;
349 char s[256];
350 j_copy(v, s, sizeof(s));
351 for (char *c = s; *c; ++c) *c = (char)tolower((unsigned char)*c);
352 char basis[96];
353 snprintf(basis, sizeof(basis), "%s", scope_keys[k]);
354 if (strstr(s, "simulat")) scope_signal(VISOR_QUAL_SIMULATED, basis, &cur, &have, r);
355 if (strncmp(s, "host", 4) == 0 || strstr(s, "no silicon claim"))
356 scope_signal(VISOR_QUAL_HOST, basis, &cur, &have, r);
357 if (strstr(s, "qemu")) scope_signal(VISOR_QUAL_QEMU, basis, &cur, &have, r);
358 }
359 r->scope = have ? cur : VISOR_QUAL_UNKNOWN;
360 if (!have) r->scope_basis[0] = 0;
361 r->scope_name = visor_qual_scope_name(r->scope);
362}
363
364static void fill_tree(VisorEvidenceRecord *r) {
365 int td = j_get(0, "tree_dirty");
366 if (j_is_lit(td, "true") || j_is_lit(td, "false")) {
367 r->tree_state_known = true;
368 r->tree_dirty = j_is_lit(td, "true");
369 return;
370 }
371 int tc = j_get(0, "candidate_trees_clean");
372 if (tc >= 0 && g_tok[tc].type == JT_OBJ) {
373 r->tree_state_known = true;
374 for (int k = tc + 1; k < g_tok[tc].next; k = g_tok[k + 1].next)
375 if (j_is_lit(k + 1, "false")) r->tree_dirty = true;
376 }
377}
378
379static int name_hash_match(const char *path, const char *receipt_hex) {
380 const char *base = strrchr(path, '/');
381 base = base ? base + 1 : path;
382 if (strlen(base) != 64 + 5 || strcmp(base + 64, ".json") != 0) return -1;
383 char name[65];
384 memcpy(name, base, 64);
385 name[64] = 0;
386 if (!is_hex_n(name, 64)) return -1;
387 return strcmp(name, receipt_hex) == 0 ? 1 : 0;
388}
389
390/* Read file into g_buf. -1 if unreadable, not a regular file, or oversize. */
391static int read_file(const char *path) {
392 g_len = 0;
393 g_buf[0] = 0;
394 FILE *f = fopen(path, "rb");
395 if (!f) return -1;
396 size_t n = fread(g_buf, 1, sizeof(g_buf), f);
397 int err = ferror(f);
398 fclose(f);
399 if (err || n > VISOR_EVIDENCE_MAX_FILE_BYTES) return -1; /* read one extra byte => oversize */
400 g_len = n;
401 g_buf[n] = 0;
402 return 0;
403}
404
405/* Build a record from g_buf (already read). */
406static int record_from_buf(const char *path, VisorEvidenceRecord *out) {
407 memset(out, 0, sizeof(*out));
408 snprintf(out->path, sizeof(out->path), "%s", path);
409 out->scope = VISOR_QUAL_UNKNOWN;
410 out->scope_name = visor_qual_scope_name(VISOR_QUAL_UNKNOWN);
411 out->name_hash_match = -1;
412 if (memchr(g_buf, 0, g_len)) return -1; /* binary content */
413 if (j_parse() != 0) return -1;
414
415 uint8_t d[SHA256_DIGEST_SIZE];
416 sha256_hash((const uint8_t *)g_buf, g_len, d);
417 SemanticId sid;
418 memcpy(sid.bytes, d, OMEGA_ID_BYTES);
419 char hex[65];
420 omega_hex_semantic_id(&sid, hex);
421 snprintf(out->receipt_id, sizeof(out->receipt_id), "sha256:%s", hex);
422 out->name_hash_match = name_hash_match(path, hex);
423
424 static const char *const commit_keys[] = {
425 "candidate_commit", "run_commit", "git_commit", "candidate_git_commit", "qualified_implementation_commit"
426 };
427 first_hex_str(commit_keys, 5, 40, false, out->commit, sizeof(out->commit), false);
428 static const char *const phys_keys[] = { "physics_commit", "physics_forge_commit" };
429 first_hex_str(phys_keys, 2, 40, false, out->physics_commit, sizeof(out->physics_commit), false);
430 if (!out->physics_commit[0])
431 first_hex_str(phys_keys, 2, 40, true, out->physics_commit, sizeof(out->physics_commit), false);
432 int rid = j_get(0, "run_id");
433 if (rid >= 0 && g_tok[rid].type == JT_STR) j_copy(rid, out->run_id, sizeof(out->run_id));
434 static const char *const real_keys[] = {
435 "realization_id", "selected_realization_identity", "promoted_realization_identity", "compiler_realization_id"
436 };
437 first_hex_str(real_keys, 4, 64, true, out->realization_id, sizeof(out->realization_id), true);
438 fill_machine(out);
439 fill_tree(out);
440 fill_gates_and_claim(out);
441 fill_scope(out);
442 return 0;
443}
444
445int visor_evidence_load(const char *path, VisorEvidenceRecord *out) {
446 if (!path || !out) return -1;
447 if (read_file(path) != 0) {
448 memset(out, 0, sizeof(*out));
449 snprintf(out->path, sizeof(out->path), "%s", path);
450 out->scope_name = visor_qual_scope_name(VISOR_QUAL_UNKNOWN);
451 out->name_hash_match = -1;
452 return -1;
453 }
454 return record_from_buf(path, out);
455}
456
457/* ------------------------------------------------------------------ */
458/* Directory walk (sorted, deterministic) */
459/* ------------------------------------------------------------------ */
460/* The kept set never depends on readdir order (omega-mv#404): below the cap every regular
461 * file is kept; past it the list is a max-heap on strcmp and a later path replaces the
462 * largest kept one when it sorts before it, so the scan keeps exactly the g_max_files
463 * smallest paths of the tree, whatever order the filesystem returned them in. */
464typedef char VisorPath[256];
465static VisorPath *g_paths;
466static size_t g_npaths, g_paths_alloc;
467static size_t g_max_files = VISOR_EVIDENCE_MAX_FILES;
468static bool g_paths_overflow, g_paths_oom;
469
470size_t visor_evidence_set_max_files(size_t cap) {
471 size_t prev = g_max_files;
472 g_max_files = cap ? cap : VISOR_EVIDENCE_MAX_FILES;
473 return prev;
474}
475
476static void heap_sift_down(size_t i) {
477 for (;;) {
478 size_t l = 2 * i + 1, r = l + 1, m = i;
479 if (l < g_npaths && strcmp(g_paths[l], g_paths[m]) > 0) m = l;
480 if (r < g_npaths && strcmp(g_paths[r], g_paths[m]) > 0) m = r;
481 if (m == i) return;
482 VisorPath t;
483 memcpy(t, g_paths[i], sizeof(t));
484 memcpy(g_paths[i], g_paths[m], sizeof(t));
485 memcpy(g_paths[m], t, sizeof(t));
486 i = m;
487 }
488}
489
490static void keep_path(const VisorPath p) {
491 if (g_npaths < g_max_files) {
492 if (g_npaths == g_paths_alloc) {
493 size_t n = g_paths_alloc ? g_paths_alloc * 2 : 1024;
494 if (n > g_max_files) n = g_max_files;
495 VisorPath *q = realloc(g_paths, n * sizeof(*q));
496 if (!q) { g_paths_oom = true; return; }
497 g_paths = q;
498 g_paths_alloc = n;
499 }
500 memcpy(g_paths[g_npaths++], p, sizeof(VisorPath));
501 if (g_npaths == g_max_files)
502 for (size_t i = g_npaths / 2; i-- > 0;) heap_sift_down(i);
503 return;
504 }
505 g_paths_overflow = true;
506 if (strcmp(p, g_paths[0]) >= 0) return; /* sorts after every kept path */
507 memcpy(g_paths[0], p, sizeof(VisorPath));
508 heap_sift_down(0);
509}
510
511static void walk(const char *dir, int depth) {
512 if (depth > 8) return;
513 DIR *d = opendir(dir);
514 if (!d) return;
515 struct dirent *e;
516 while ((e = readdir(d)) != NULL) {
517 if (e->d_name[0] == '.') continue;
518 VisorPath p;
519 int w = snprintf(p, sizeof(p), "%s%s%s", dir, dir[strlen(dir) - 1] == '/' ? "" : "/", e->d_name);
520 if (w < 0 || (size_t)w >= sizeof(p)) { g_paths_overflow = true; continue; }
521 struct stat st;
522 if (lstat(p, &st) != 0) continue;
523 if (S_ISDIR(st.st_mode)) { walk(p, depth + 1); continue; }
524 if (!S_ISREG(st.st_mode)) continue; /* symlinks and devices are not followed */
525 keep_path(p);
526 }
527 closedir(d);
528}
529
530static int cmp_path(const void *a, const void *b) { return strcmp((const char *)a, (const char *)b); }
531
532static int collect(const char *root) {
533 struct stat st;
534 if (!root || !root[0] || stat(root, &st) != 0 || !S_ISDIR(st.st_mode)) return -1;
535 g_npaths = 0;
536 g_paths_overflow = false;
537 g_paths_oom = false;
538 walk(root, 0);
539 if (g_paths_oom) return -1; /* fail closed: a dropped path could hide evidence */
540 if (g_npaths) qsort(g_paths, g_npaths, sizeof(g_paths[0]), cmp_path);
541 return 0;
542}
543
544static bool ends_with(const char *s, const char *suf) {
545 size_t a = strlen(s), b = strlen(suf);
546 return a >= b && strcmp(s + a - b, suf) == 0;
547}
548
549static void view_reset(VisorEvidenceView *v) { memset(v, 0, sizeof(*v)); }
550
551static void note_unparsed(VisorEvidenceView *v, const char *path) {
552 v->unparsed++;
553 if (v->unparsed_listed < VISOR_EVIDENCE_MAX_UNPARSED_PATHS)
554 snprintf(v->unparsed_paths[v->unparsed_listed++], 256, "%s", path);
555}
556
557static void view_add(VisorEvidenceView *v, const VisorEvidenceRecord *r) {
558 v->matched++;
559 if (v->count < VISOR_EVIDENCE_MAX_ITEMS) v->items[v->count++] = *r;
560 else v->truncated = true;
561}
562
563int visor_evidence_scan(const char *evidence_root, VisorEvidenceView *out) {
564 if (!out) return -1;
565 view_reset(out);
566 if (collect(evidence_root) != 0) return -1;
567 static VisorEvidenceRecord rec;
568 for (size_t i = 0; i < g_npaths; ++i) {
569 out->scanned++;
570 if (!ends_with(g_paths[i], ".json") || visor_evidence_load(g_paths[i], &rec) != 0) {
571 note_unparsed(out, g_paths[i]);
572 continue;
573 }
574 view_add(out, &rec);
575 }
576 if (g_paths_overflow) out->truncated = true;
577 return 0;
578}
579
580int visor_evidence_for_id(const char *evidence_root, const SemanticId *id, VisorEvidenceView *out) {
581 if (!out) return -1;
582 view_reset(out);
583 if (!id || collect(evidence_root) != 0) return -1;
584 char hex[65];
585 omega_hex_semantic_id(id, hex);
586 static VisorEvidenceRecord rec;
587 for (size_t i = 0; i < g_npaths; ++i) {
588 out->scanned++;
589 if (read_file(g_paths[i]) != 0) { note_unparsed(out, g_paths[i]); continue; } /* could hide a mention */
590 if (!memmem(g_buf, g_len, hex, 64)) continue;
591 /* Mentions the id: parse it, or report it UNPARSED with its path. */
592 if (!ends_with(g_paths[i], ".json") || record_from_buf(g_paths[i], &rec) != 0) {
593 note_unparsed(out, g_paths[i]);
594 continue;
595 }
596 view_add(out, &rec);
597 }
598 if (g_paths_overflow) out->truncated = true;
599 return 0;
600}
601
602/* ------------------------------------------------------------------ */
603/* Rendering */
604/* ------------------------------------------------------------------ */
605typedef struct { char *p; size_t n, len; bool overflow; } EBuf;
606
607static void eb_printf(EBuf *b, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
608static void eb_printf(EBuf *b, const char *fmt, ...) {
609 if (b->overflow) return;
610 va_list ap;
611 va_start(ap, fmt);
612 int w = vsnprintf(b->p + b->len, b->n - b->len, fmt, ap);
613 va_end(ap);
614 if (w < 0 || (size_t)w >= b->n - b->len) { b->overflow = true; b->p[b->len] = 0; return; }
615 b->len += (size_t)w;
616}
617
618static void eb_json_str(EBuf *b, const char *s) {
619 eb_printf(b, "\"");
620 for (const unsigned char *c = (const unsigned char *)(s ? s : ""); *c && !b->overflow; ++c) {
621 if (*c == '"' || *c == '\\') eb_printf(b, "\\%c", *c);
622 else if (*c < 0x20) eb_printf(b, "\\u%04x", *c);
623 else eb_printf(b, "%c", *c);
624 }
625 eb_printf(b, "\"");
626}
627
628static const char *or_none(const char *s) { return (s && s[0]) ? s : "(none)"; }
629
630int visor_evidence_format_text(const VisorEvidenceView *v, char *out, size_t n) {
631 if (!v || !out || n == 0) return -1;
632 EBuf b = { out, n, 0, false };
633 out[0] = 0;
634 eb_printf(&b, "evidence: %zu shown, %zu matched, %zu scanned, %zu unparsed%s\n",
635 v->count, v->matched, v->scanned, v->unparsed, v->truncated ? " (truncated)" : "");
636 if (v->count == 0) eb_printf(&b, "no evidence\n");
637 for (size_t i = 0; i < v->count; ++i) {
638 const VisorEvidenceRecord *r = &v->items[i];
639 eb_printf(&b, "receipt %s%s\n", r->receipt_id,
640 r->name_hash_match == 1 ? " (name = content hash)" :
641 r->name_hash_match == 0 ? " (NAME != CONTENT HASH)" : "");
642 eb_printf(&b, " path %s\n", r->path);
643 eb_printf(&b, " claim %s\n", or_none(r->claim));
644 eb_printf(&b, " scope %s%s%s%s\n", r->scope_name ? r->scope_name : "UNKNOWN",
645 r->scope_basis[0] ? " (from " : "", r->scope_basis, r->scope_basis[0] ? ")" : "");
646 eb_printf(&b, " gates %u/%u passed\n", r->gates_passed, r->gates_run);
647 eb_printf(&b, " commit %s\n", or_none(r->commit));
648 eb_printf(&b, " physics %s\n", or_none(r->physics_commit));
649 eb_printf(&b, " run %s\n", or_none(r->run_id));
650 eb_printf(&b, " machine %s\n", or_none(r->machine));
651 eb_printf(&b, " realization %s\n", or_none(r->realization_id));
652 eb_printf(&b, " tree %s\n", !r->tree_state_known ? "unknown" : r->tree_dirty ? "DIRTY" : "clean");
653 }
654 for (size_t i = 0; i < v->unparsed_listed; ++i) eb_printf(&b, "UNPARSED %s\n", v->unparsed_paths[i]);
655 if (v->unparsed > v->unparsed_listed)
656 eb_printf(&b, "UNPARSED (+%zu more)\n", v->unparsed - v->unparsed_listed);
657 return b.overflow ? -1 : (int)b.len;
658}
659
660int visor_evidence_format_json(const VisorEvidenceView *v, char *out, size_t n) {
661 if (!v || !out || n == 0) return -1;
662 EBuf b = { out, n, 0, false };
663 out[0] = 0;
664 eb_printf(&b, "{\"count\":%zu,\"matched\":%zu,\"scanned\":%zu,\"unparsed\":%zu,\"truncated\":%s,\"receipts\":[",
665 v->count, v->matched, v->scanned, v->unparsed, v->truncated ? "true" : "false");
666 for (size_t i = 0; i < v->count; ++i) {
667 const VisorEvidenceRecord *r = &v->items[i];
668 eb_printf(&b, "%s{\"receipt_id\":", i ? "," : "");
669 eb_json_str(&b, r->receipt_id);
670 eb_printf(&b, ",\"path\":"); eb_json_str(&b, r->path);
671 eb_printf(&b, ",\"claim\":"); eb_json_str(&b, r->claim);
672 eb_printf(&b, ",\"scope\":\"%s\",\"scope_basis\":", r->scope_name ? r->scope_name : "UNKNOWN");
673 eb_json_str(&b, r->scope_basis);
674 eb_printf(&b, ",\"gates_run\":%u,\"gates_passed\":%u,\"commit\":", r->gates_run, r->gates_passed);
675 eb_json_str(&b, r->commit);
676 eb_printf(&b, ",\"physics_commit\":"); eb_json_str(&b, r->physics_commit);
677 eb_printf(&b, ",\"run_id\":"); eb_json_str(&b, r->run_id);
678 eb_printf(&b, ",\"machine\":"); eb_json_str(&b, r->machine);
679 eb_printf(&b, ",\"realization_id\":"); eb_json_str(&b, r->realization_id);
680 eb_printf(&b, ",\"tree\":\"%s\",\"name_hash_match\":%d}",
681 !r->tree_state_known ? "unknown" : r->tree_dirty ? "dirty" : "clean", r->name_hash_match);
682 }
683 eb_printf(&b, "],\"unparsed_paths\":[");
684 for (size_t i = 0; i < v->unparsed_listed; ++i) {
685 if (i) eb_printf(&b, ",");
686 eb_json_str(&b, v->unparsed_paths[i]);
687 }
688 eb_printf(&b, "]}");
689 return b.overflow ? -1 : (int)b.len;
690}