@shieldaai/security-watch 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/CONTRIBUTING.md +92 -0
  3. package/LICENSE +202 -0
  4. package/README.md +394 -2
  5. package/SECURITY.md +62 -0
  6. package/dist/assessment.d.ts +16 -0
  7. package/dist/assessment.js +569 -0
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.js +1105 -0
  10. package/dist/config.d.ts +302 -0
  11. package/dist/config.js +381 -0
  12. package/dist/coverage.d.ts +4 -0
  13. package/dist/coverage.js +11 -0
  14. package/dist/cve-now.d.ts +35 -0
  15. package/dist/cve-now.js +1002 -0
  16. package/dist/cvss4.d.ts +3 -0
  17. package/dist/cvss4.js +39 -0
  18. package/dist/delivery.d.ts +58 -0
  19. package/dist/delivery.js +687 -0
  20. package/dist/ecosystems.d.ts +48 -0
  21. package/dist/ecosystems.js +332 -0
  22. package/dist/engine.d.ts +80 -0
  23. package/dist/engine.js +388 -0
  24. package/dist/everyday-words.d.ts +11 -0
  25. package/dist/everyday-words.js +256 -0
  26. package/dist/health.d.ts +24 -0
  27. package/dist/health.js +122 -0
  28. package/dist/heartbeat.d.ts +13 -0
  29. package/dist/heartbeat.js +74 -0
  30. package/dist/http.d.ts +15 -0
  31. package/dist/http.js +280 -0
  32. package/dist/index.d.ts +36 -0
  33. package/dist/index.js +23 -0
  34. package/dist/inventory-evidence.d.ts +10 -0
  35. package/dist/inventory-evidence.js +206 -0
  36. package/dist/inventory.d.ts +276 -0
  37. package/dist/inventory.js +336 -0
  38. package/dist/lock.d.ts +3 -0
  39. package/dist/lock.js +112 -0
  40. package/dist/maintenance.d.ts +48 -0
  41. package/dist/maintenance.js +295 -0
  42. package/dist/matching.d.ts +29 -0
  43. package/dist/matching.js +537 -0
  44. package/dist/models.d.ts +33 -0
  45. package/dist/models.js +932 -0
  46. package/dist/operations.d.ts +17 -0
  47. package/dist/operations.js +117 -0
  48. package/dist/pilot-cases.d.ts +171 -0
  49. package/dist/pilot-cases.js +330 -0
  50. package/dist/pilot-input.d.ts +16 -0
  51. package/dist/pilot-input.js +125 -0
  52. package/dist/pilot-recall.d.ts +166 -0
  53. package/dist/pilot-recall.js +231 -0
  54. package/dist/pilot-report.d.ts +113 -0
  55. package/dist/pilot-report.js +279 -0
  56. package/dist/pilot-responses.d.ts +111 -0
  57. package/dist/pilot-responses.js +159 -0
  58. package/dist/providers.d.ts +209 -0
  59. package/dist/providers.js +459 -0
  60. package/dist/python-version.d.ts +3 -0
  61. package/dist/python-version.js +30 -0
  62. package/dist/rehearsal.d.ts +440 -0
  63. package/dist/rehearsal.js +372 -0
  64. package/dist/sbom.d.ts +13 -0
  65. package/dist/sbom.js +193 -0
  66. package/dist/setup.d.ts +113 -0
  67. package/dist/setup.js +100 -0
  68. package/dist/source-error.d.ts +38 -0
  69. package/dist/source-error.js +71 -0
  70. package/dist/sources.d.ts +3 -0
  71. package/dist/sources.js +1725 -0
  72. package/dist/store.d.ts +96 -0
  73. package/dist/store.js +953 -0
  74. package/dist/types.d.ts +404 -0
  75. package/dist/types.js +1 -0
  76. package/dist/util.d.ts +29 -0
  77. package/dist/util.js +94 -0
  78. package/dist/vendor/cvss4-reference.d.ts +2 -0
  79. package/dist/vendor/cvss4-reference.js +789 -0
  80. package/dist/vendor-sources.d.ts +24 -0
  81. package/dist/vendor-sources.js +56 -0
  82. package/dist/word-filter.d.ts +3 -0
  83. package/dist/word-filter.js +3291 -0
  84. package/docs/alert-outcome-evaluation.md +150 -0
  85. package/docs/compatibility.md +35 -0
  86. package/docs/configuration.md +666 -0
  87. package/docs/cvss-v4-support.md +41 -0
  88. package/docs/offline-advisory-preview.md +114 -0
  89. package/docs/offline-rehearsal.md +44 -0
  90. package/docs/pilot-cases.md +58 -0
  91. package/docs/pilot-recall.md +124 -0
  92. package/docs/pilot-report.md +52 -0
  93. package/docs/validation/alert-outcome-evaluation-2026-11-05.json +2935 -0
  94. package/docs/validation/cvss-v4-reference-parity-2026-11-05.json +93 -0
  95. package/docs/validation/rehearsal-accepted-2026-11-05.json +175 -0
  96. package/docs/validation/rehearsal-unknown-2026-11-05.json +175 -0
  97. package/docs/vendor/cvss-v4-LICENSE.txt +22 -0
  98. package/docs/vendor/cvss-v4-provenance.json +38 -0
  99. package/examples/advisories.json +17 -0
  100. package/examples/agent-advisories-2026.json +145 -0
  101. package/examples/agent-advisory-cases-2026.json +397 -0
  102. package/examples/common-systems.yaml +243 -0
  103. package/examples/libraries.example.txt +18 -0
  104. package/examples/libraries.example.yaml +40 -0
  105. package/examples/library-watch.example.yaml +27 -0
  106. package/examples/offline-advisory-preview.mjs +42 -0
  107. package/examples/rehearsal.json +75 -0
  108. package/examples/security-watch.example.yaml +86 -0
  109. package/examples/systems.example.yaml +35 -0
  110. package/package.json +85 -4
@@ -0,0 +1,279 @@
1
+ import { coverageFreshness } from './coverage.js';
2
+ const DAY = 86_400_000;
3
+ const MAX_ROWS = 100_000;
4
+ const states = () => ({ pending: 0, sending: 0, accepted: 0, failed: 0, unknown: 0 });
5
+ const decisions = () => ({ record: 0, digest: 0, notify: 0 });
6
+ const messages = {
7
+ window: 'Choose 1 to 31 complete UTC days using YYYY-MM-DD dates and an exclusive end date.',
8
+ database: 'Could not read the pilot database. Choose an existing private monitor database or backup with the supported schema.',
9
+ bounds: 'Pilot report size limit exceeded. See the documented database and window limits.',
10
+ data: 'Pilot report could not validate the retained monitor records.',
11
+ incidents: 'Invalid independent incident reference. Check the date window, exact deployment targets, aliases and response deadlines.',
12
+ responses: 'Invalid pilot response register. Check the frozen evaluation, independent reviewer, evidence references and observation times.',
13
+ labels: 'Invalid pilot feedback. Check the snapshot, window, case references and independent reviewer declarations.',
14
+ };
15
+ export class PilotReportError extends Error {
16
+ constructor(code) {
17
+ super(messages[code]);
18
+ }
19
+ }
20
+ function midnight(day) {
21
+ if (typeof day !== 'string' || !/^\d{4}-\d{2}-\d{2}$/u.test(day))
22
+ throw new PilotReportError('window');
23
+ const time = Date.parse(day + 'T00:00:00Z');
24
+ if (!Number.isSafeInteger(time) || time < 0 || new Date(time).toISOString().slice(0, 10) !== day)
25
+ throw new PilotReportError('window');
26
+ return time;
27
+ }
28
+ export function validatePilotWindow(input, now) {
29
+ const from = input?.from, until = input?.until;
30
+ const start = midnight(from);
31
+ const end = midnight(until);
32
+ const days = (end - start) / DAY;
33
+ if (days < 1 || days > 31 || end > Math.floor(now / DAY) * DAY)
34
+ throw new PilotReportError('window');
35
+ return { from, until, start, end, days };
36
+ }
37
+ function count(value) {
38
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
39
+ throw new PilotReportError('data');
40
+ return value;
41
+ }
42
+ function add(counts, key, value) {
43
+ if (typeof key !== 'string' || !Object.hasOwn(counts, key))
44
+ throw new PilotReportError('data');
45
+ counts[key] += count(value);
46
+ }
47
+ function checkWork(db, start, end) {
48
+ // OFFSET probes avoid materializing records. Both history tables have a recorded_at index.
49
+ for (const table of ['finding_revisions', 'evidence_revisions']) {
50
+ if (db
51
+ .prepare(`SELECT 1 FROM ${table} WHERE recorded_at >= ? AND recorded_at < ? LIMIT 1 OFFSET ?`)
52
+ .get(start, end, MAX_ROWS))
53
+ throw new PilotReportError('bounds');
54
+ }
55
+ for (const table of ['notifications', 'ai_reviews']) {
56
+ if (db.prepare(`SELECT 1 FROM ${table} LIMIT 1 OFFSET ?`).get(MAX_ROWS))
57
+ throw new PilotReportError('bounds');
58
+ }
59
+ if (db
60
+ .prepare('SELECT 1 FROM finding_revisions WHERE recorded_at>=? AND recorded_at<? AND length(CAST(decision AS BLOB))>16384 LIMIT 1')
61
+ .get(start, end))
62
+ throw new PilotReportError('bounds');
63
+ }
64
+ function coverageSnapshot(db, now) {
65
+ const size = db
66
+ .prepare("SELECT length(CAST(value AS BLOB)) AS bytes FROM metadata WHERE key='source:coverage'")
67
+ .get();
68
+ if (!size)
69
+ return null;
70
+ if (count(size.bytes) > 1024 * 1024)
71
+ throw new PilotReportError('bounds');
72
+ // Project only fields used for freshness; raw source names, URLs, error text and scope stay in SQLite.
73
+ const shape = db
74
+ .prepare("SELECT json_type(value) AS kind, json_array_length(value) AS n FROM metadata WHERE key='source:coverage'")
75
+ .get();
76
+ if (shape.kind !== 'array')
77
+ throw new PilotReportError('data');
78
+ if (count(shape.n) > 128)
79
+ throw new PilotReportError('bounds');
80
+ const rows = db
81
+ .prepare(`SELECT json_extract(r.value,'$.status') AS status,
82
+ json_extract(r.value,'$.last_success_at') AS last_success_at, json_extract(r.value,'$.fresh_until') AS fresh_until
83
+ FROM metadata, json_each(metadata.value) r WHERE metadata.key='source:coverage'`)
84
+ .all();
85
+ const status = { complete: 0, partial: 0, failed: 0 };
86
+ const freshness = { fresh: 0, stale: 0, never: 0 };
87
+ for (const row of rows) {
88
+ add(status, row.status, 1);
89
+ for (const value of [row.last_success_at, row.fresh_until]) {
90
+ if (value !== null && (typeof value !== 'string' || !Number.isFinite(Date.parse(value))))
91
+ throw new PilotReportError('data');
92
+ }
93
+ const state = coverageFreshness({
94
+ last_success_at: typeof row.last_success_at === 'string' ? row.last_success_at : undefined,
95
+ fresh_until: typeof row.fresh_until === 'string' ? row.fresh_until : undefined,
96
+ }, now);
97
+ freshness[state]++;
98
+ }
99
+ return { receipts: rows.length, status, freshness };
100
+ }
101
+ function lastScan(db, now) {
102
+ const size = db
103
+ .prepare("SELECT length(CAST(value AS BLOB)) AS bytes FROM metadata WHERE key='last_scan'")
104
+ .get();
105
+ if (!size)
106
+ return null;
107
+ if (count(size.bytes) > 1024 * 1024)
108
+ throw new PilotReportError('bounds');
109
+ const row = db
110
+ .prepare(`SELECT json_extract(value,'$.started_at') AS started,
111
+ COALESCE(json_extract(value,'$.completed_at'),json_extract(value,'$.at')) AS completed,
112
+ json_type(value,'$.degraded') AS degraded FROM metadata WHERE key='last_scan'`)
113
+ .get();
114
+ const completed = typeof row.completed === 'string' ? Date.parse(row.completed) : NaN;
115
+ const started = typeof row.started === 'string' ? Date.parse(row.started) : NaN;
116
+ if (!Number.isFinite(completed) ||
117
+ (row.degraded !== null && row.degraded !== 'true' && row.degraded !== 'false'))
118
+ throw new PilotReportError('data');
119
+ return {
120
+ age_ms: completed <= now ? now - completed : null,
121
+ duration_ms: Number.isFinite(started) && started <= completed ? completed - started : null,
122
+ degraded: row.degraded === null ? null : row.degraded === 'true',
123
+ };
124
+ }
125
+ function modelReservations(db, window) {
126
+ const rows = db
127
+ .prepare(`SELECT substr(b.day,1,11) AS day, b.requests, b.tokens, b.usd,
128
+ CASE WHEN length(CAST(m.value AS BLOB))>20 THEN 'invalid' ELSE m.value END AS unpriced
129
+ FROM budgets b LEFT JOIN metadata m ON m.key='unpriced:' || b.day
130
+ WHERE b.day>=? AND b.day<? ORDER BY b.day LIMIT 32`)
131
+ .all(window.from, window.until);
132
+ if (rows.length > 31)
133
+ throw new PilotReportError('data');
134
+ let requests = 0, tokens = 0, knownUsd = 0, unpriced = 0;
135
+ for (const row of rows) {
136
+ midnight(row.day);
137
+ const n = count(row.requests);
138
+ const u = row.unpriced === null ? 0 : count(Number(row.unpriced));
139
+ if (u > n ||
140
+ (row.unpriced !== null && String(u) !== row.unpriced) ||
141
+ typeof row.usd !== 'number' ||
142
+ !Number.isFinite(row.usd) ||
143
+ row.usd < 0)
144
+ throw new PilotReportError('data');
145
+ requests = count(requests + n);
146
+ tokens = count(tokens + count(row.tokens));
147
+ unpriced = count(unpriced + u);
148
+ knownUsd += row.usd;
149
+ }
150
+ if (!Number.isFinite(knownUsd))
151
+ throw new PilotReportError('data');
152
+ return {
153
+ requests,
154
+ tokens,
155
+ unpriced_requests: unpriced,
156
+ known_reserved_usd: knownUsd,
157
+ reserved_usd: unpriced ? null : knownUsd,
158
+ };
159
+ }
160
+ function reviewActivity(db, start, end) {
161
+ const opened = db
162
+ .prepare('SELECT COUNT(*) AS n FROM ai_reviews WHERE created_at>=? AND created_at<?')
163
+ .get(start, end);
164
+ // Each row stores the most recent operator action for one review revision. Later edits overwrite that timestamp.
165
+ const responses = db
166
+ .prepare(`SELECT created_at, reviewed_at FROM ai_reviews
167
+ WHERE reviewed_at>=? AND reviewed_at<? ORDER BY reviewed_at-created_at`)
168
+ .iterate(start, end);
169
+ let observed = 0, invalid = 0;
170
+ const durations = [];
171
+ for (const row of responses) {
172
+ observed++;
173
+ const elapsed = Number(row.reviewed_at) - Number(row.created_at);
174
+ if (typeof row.created_at !== 'number' ||
175
+ !Number.isSafeInteger(row.created_at) ||
176
+ row.created_at < 0 ||
177
+ typeof row.reviewed_at !== 'number' ||
178
+ !Number.isSafeInteger(elapsed) ||
179
+ elapsed < 0)
180
+ invalid++;
181
+ else
182
+ durations.push(elapsed);
183
+ }
184
+ return {
185
+ opened: count(opened.n),
186
+ latest_response_rows: observed,
187
+ latency_samples: durations.length,
188
+ invalid_latency_rows: invalid,
189
+ open_to_latest_response_p95_ms: durations[Math.ceil(durations.length * 0.95) - 1] ?? null,
190
+ };
191
+ }
192
+ /** The caller owns a READONLY handle and a deferred read transaction covering every query. */
193
+ export function aggregatePilotReport(db, range, asOf) {
194
+ const { from, until, days, start, end } = range;
195
+ checkWork(db, start, end);
196
+ const daily = Array.from({ length: days }, (_, i) => ({
197
+ date: new Date(start + i * DAY).toISOString().slice(0, 10),
198
+ evidence_revisions: 0,
199
+ finding_revisions: 0,
200
+ decisions: decisions(),
201
+ }));
202
+ const routes = decisions();
203
+ let findingRevisions = 0, evidenceRevisions = 0;
204
+ for (const row of db
205
+ .prepare(`SELECT CAST((recorded_at-?)/86400000 AS INTEGER) AS day,
206
+ CASE json_extract(decision,'$.action') WHEN 'notify' THEN 'notify' WHEN 'digest' THEN 'digest' WHEN 'record' THEN 'record' ELSE 'invalid' END AS action,
207
+ COUNT(*) AS n
208
+ FROM finding_revisions WHERE recorded_at>0 AND recorded_at>=? AND recorded_at<? GROUP BY day, action`)
209
+ .all(start, start, end)) {
210
+ const bucket = daily[count(row.day)];
211
+ add(bucket.decisions, row.action, row.n);
212
+ add(routes, row.action, row.n);
213
+ bucket.finding_revisions += count(row.n);
214
+ findingRevisions += count(row.n);
215
+ }
216
+ for (const row of db
217
+ .prepare(`SELECT CAST((recorded_at-?)/86400000 AS INTEGER) AS day, COUNT(*) AS n
218
+ FROM evidence_revisions WHERE recorded_at>0 AND recorded_at>=? AND recorded_at<? GROUP BY day`)
219
+ .all(start, start, end)) {
220
+ daily[count(row.day)].evidence_revisions = count(row.n);
221
+ evidenceRevisions += count(row.n);
222
+ }
223
+ const distinct = db
224
+ .prepare(`SELECT COUNT(DISTINCT finding_id) AS n FROM finding_revisions
225
+ WHERE recorded_at>0 AND recorded_at>=? AND recorded_at<?`)
226
+ .get(start, end);
227
+ // available_at is a scheduling field. Cohort by finding revision, then report each associated job's state as read.
228
+ const cohortStates = states();
229
+ for (const row of db
230
+ .prepare(`SELECT n.status, COUNT(*) AS n FROM finding_revisions r
231
+ JOIN notifications n ON n.finding_id=r.finding_id AND n.revision=r.revision
232
+ WHERE r.recorded_at>0 AND r.recorded_at>=? AND r.recorded_at<? GROUP BY n.status`)
233
+ .all(start, end))
234
+ add(cohortStates, row.status, row.n);
235
+ const allStates = states();
236
+ for (const row of db.prepare('SELECT status, COUNT(*) AS n FROM notifications GROUP BY status').all())
237
+ add(allStates, row.status, row.n);
238
+ const review = db
239
+ .prepare(`SELECT COUNT(*) FILTER(WHERE status='pending') AS pending,
240
+ COUNT(*) FILTER(WHERE status='investigate') AS investigate,
241
+ MIN(created_at) FILTER(WHERE status IN ('pending','investigate')) AS oldest FROM ai_reviews`)
242
+ .get();
243
+ const oldest = review.oldest === null ? null : count(review.oldest);
244
+ return {
245
+ version: 1,
246
+ mode: 'pilot_report',
247
+ window: { from, until, days },
248
+ activity: {
249
+ finding_revisions: findingRevisions,
250
+ distinct_findings: count(distinct.n),
251
+ evidence_revisions: evidenceRevisions,
252
+ days_with_retained_revisions: daily.filter((d) => d.finding_revisions || d.evidence_revisions).length,
253
+ decisions: routes,
254
+ daily,
255
+ delivery_states_for_revisions: cohortStates,
256
+ reviews: reviewActivity(db, start, end),
257
+ model_reservations: modelReservations(db, range),
258
+ },
259
+ snapshot: {
260
+ source: 'monitor_database',
261
+ read_at: new Date(asOf).toISOString(),
262
+ delivery_states: allStates,
263
+ reviews: {
264
+ pending: count(review.pending),
265
+ investigate: count(review.investigate),
266
+ oldest_open_age_ms: oldest === null || oldest > asOf ? null : asOf - oldest,
267
+ },
268
+ source_coverage: coverageSnapshot(db, asOf),
269
+ last_scan: lastScan(db, asOf),
270
+ },
271
+ unmeasured: {
272
+ urgent_recall: null,
273
+ false_alert_rate: null,
274
+ source_to_triage_p95_ms: null,
275
+ monitored_days: null,
276
+ actual_model_spend_usd: null,
277
+ },
278
+ };
279
+ }
@@ -0,0 +1,111 @@
1
+ import { type PilotIncidentReference } from './pilot-recall.js';
2
+ import { type PilotWindow } from './pilot-report.js';
3
+ type ResponseEvidence = {
4
+ status: 'observed';
5
+ at: string;
6
+ evidence_ref: string;
7
+ } | {
8
+ status: 'no_record';
9
+ at: null;
10
+ evidence_ref: string;
11
+ } | {
12
+ status: 'unresolved' | 'unreviewed';
13
+ at: null;
14
+ evidence_ref: null;
15
+ };
16
+ interface IncidentResponse {
17
+ incident_id: string;
18
+ acknowledgement: ResponseEvidence;
19
+ triage: ResponseEvidence;
20
+ }
21
+ export interface PilotResponseRegister {
22
+ version: 1;
23
+ recall_evaluation_id: string;
24
+ reviewer: string;
25
+ reviewed_independently: true;
26
+ reviewed_through: string;
27
+ responses: IncidentResponse[];
28
+ }
29
+ export declare function readPilotResponseRegister(path: string): PilotResponseRegister;
30
+ /** Compare independent human records with provider receipt evidence on the exact same frozen incidents. */
31
+ export declare function scorePilotResponses(backup: string, window: PilotWindow, input: PilotIncidentReference, register: PilotResponseRegister): Promise<{
32
+ version: 1;
33
+ mode: 'pilot_responses';
34
+ window: PilotWindow;
35
+ recall_evaluation_id: string;
36
+ evaluation_id: string;
37
+ reviewed_through: string;
38
+ reference_incidents: number;
39
+ acknowledgement: {
40
+ on_time: {
41
+ numerator: number;
42
+ denominator: number;
43
+ rate: number | null;
44
+ };
45
+ reviewed: {
46
+ numerator: number;
47
+ denominator: number;
48
+ rate: number | null;
49
+ };
50
+ resolved: {
51
+ numerator: number;
52
+ denominator: number;
53
+ rate: number | null;
54
+ };
55
+ outcomes: {
56
+ on_time: number;
57
+ late: number;
58
+ no_record: number;
59
+ unresolved: number;
60
+ unreviewed: number;
61
+ };
62
+ first_response_after_availability: {
63
+ count: number;
64
+ median_ms: number | null;
65
+ p95_ms: number | null;
66
+ };
67
+ paired_with_on_time_provider: {
68
+ both: number;
69
+ provider_only_confirmed: number;
70
+ human_only_confirmed: number;
71
+ neither_confirmed: number;
72
+ };
73
+ };
74
+ triage: {
75
+ on_time: {
76
+ numerator: number;
77
+ denominator: number;
78
+ rate: number | null;
79
+ };
80
+ reviewed: {
81
+ numerator: number;
82
+ denominator: number;
83
+ rate: number | null;
84
+ };
85
+ resolved: {
86
+ numerator: number;
87
+ denominator: number;
88
+ rate: number | null;
89
+ };
90
+ outcomes: {
91
+ on_time: number;
92
+ late: number;
93
+ no_record: number;
94
+ unresolved: number;
95
+ unreviewed: number;
96
+ };
97
+ first_response_after_availability: {
98
+ count: number;
99
+ median_ms: number | null;
100
+ p95_ms: number | null;
101
+ };
102
+ paired_with_on_time_provider: {
103
+ both: number;
104
+ provider_only_confirmed: number;
105
+ human_only_confirmed: number;
106
+ neither_confirmed: number;
107
+ };
108
+ };
109
+ }>;
110
+ export type PilotResponseScore = Awaited<ReturnType<typeof scorePilotResponses>>;
111
+ export {};
@@ -0,0 +1,159 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { latencySummary, metric } from './pilot-cases.js';
3
+ import { dataArray, dataFields, pilotInstant, readPrivatePilotJson } from './pilot-input.js';
4
+ import { capturePilotIncidentReference, evaluatePilotReference, } from './pilot-recall.js';
5
+ import { PilotReportError } from './pilot-report.js';
6
+ function invalid() {
7
+ throw new PilotReportError('responses');
8
+ }
9
+ function captureEvidence(value) {
10
+ const { status, at, evidence_ref } = dataFields(value, ['status', 'at', 'evidence_ref'], 'responses');
11
+ if (status === 'unresolved' || status === 'unreviewed') {
12
+ if (at !== null || evidence_ref !== null)
13
+ invalid();
14
+ return { status, at, evidence_ref };
15
+ }
16
+ if (typeof evidence_ref !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(evidence_ref))
17
+ invalid();
18
+ if (status === 'no_record' && at === null)
19
+ return { status, at, evidence_ref };
20
+ if (status !== 'observed')
21
+ invalid();
22
+ return { status, at: pilotInstant(at, 'responses'), evidence_ref };
23
+ }
24
+ function captureRegister(input) {
25
+ const fields = dataFields(input, [
26
+ 'version',
27
+ 'recall_evaluation_id',
28
+ 'reviewer',
29
+ 'reviewed_independently',
30
+ 'reviewed_through',
31
+ 'responses',
32
+ ], 'responses');
33
+ if (fields.version !== 1 ||
34
+ fields.reviewed_independently !== true ||
35
+ typeof fields.recall_evaluation_id !== 'string' ||
36
+ !/^[a-f0-9]{64}$/u.test(fields.recall_evaluation_id) ||
37
+ typeof fields.reviewer !== 'string' ||
38
+ !/^[a-z][a-z0-9_-]{0,63}$/u.test(fields.reviewer))
39
+ invalid();
40
+ const reviewed_through = pilotInstant(fields.reviewed_through, 'responses');
41
+ if (Date.parse(reviewed_through) > Date.now())
42
+ invalid();
43
+ const ids = new Set();
44
+ const observedSources = new Map();
45
+ let totalBytes = 0;
46
+ const responses = dataArray(fields.responses, 1000, 'responses').map((item) => {
47
+ const row = dataFields(item, ['incident_id', 'acknowledgement', 'triage'], 'responses');
48
+ const id = row.incident_id;
49
+ if (typeof id !== 'string' || !id || id.length > 512 || ids.has(id))
50
+ invalid();
51
+ ids.add(id);
52
+ const result = {
53
+ incident_id: id,
54
+ acknowledgement: captureEvidence(row.acknowledgement),
55
+ triage: captureEvidence(row.triage),
56
+ };
57
+ for (const action of [result.acknowledgement, result.triage]) {
58
+ if (action.status !== 'observed')
59
+ continue;
60
+ if (action.at > reviewed_through)
61
+ invalid();
62
+ // One underlying record can document both stages for the same target.
63
+ const owner = observedSources.get(action.evidence_ref);
64
+ if (owner !== undefined && owner !== id)
65
+ invalid();
66
+ observedSources.set(action.evidence_ref, id);
67
+ }
68
+ totalBytes += Buffer.byteLength(JSON.stringify(result));
69
+ if (totalBytes > 2 * 1024 * 1024)
70
+ invalid();
71
+ return result;
72
+ });
73
+ responses.sort((a, b) => (a.incident_id < b.incident_id ? -1 : a.incident_id > b.incident_id ? 1 : 0));
74
+ return {
75
+ version: 1,
76
+ recall_evaluation_id: fields.recall_evaluation_id,
77
+ reviewer: fields.reviewer,
78
+ reviewed_independently: true,
79
+ reviewed_through,
80
+ responses,
81
+ };
82
+ }
83
+ export function readPilotResponseRegister(path) {
84
+ return captureRegister(readPrivatePilotJson(path, 'responses'));
85
+ }
86
+ function scoreStage(stage, incidents, responses, onTimeProvider) {
87
+ const outcomes = { on_time: 0, late: 0, no_record: 0, unresolved: 0, unreviewed: 0 };
88
+ const pairs = { both: 0, provider_only_confirmed: 0, human_only_confirmed: 0, neither_confirmed: 0 };
89
+ const delays = [];
90
+ for (const incident of incidents) {
91
+ const answer = responses.get(incident.incident_id)?.[stage];
92
+ const timely = answer?.status === 'observed' && answer.at < incident.deadline_at;
93
+ if (!answer)
94
+ outcomes.unreviewed++;
95
+ else if (answer.status === 'observed') {
96
+ delays.push(Date.parse(answer.at) - Date.parse(incident.available_at));
97
+ if (timely)
98
+ outcomes.on_time++;
99
+ else
100
+ outcomes.late++;
101
+ }
102
+ else
103
+ outcomes[answer.status]++;
104
+ if (onTimeProvider.has(incident.incident_id)) {
105
+ if (timely)
106
+ pairs.both++;
107
+ else
108
+ pairs.provider_only_confirmed++;
109
+ }
110
+ else if (timely)
111
+ pairs.human_only_confirmed++;
112
+ else
113
+ pairs.neither_confirmed++;
114
+ }
115
+ const n = incidents.length;
116
+ return {
117
+ on_time: metric(outcomes.on_time, n),
118
+ reviewed: metric(n - outcomes.unreviewed, n),
119
+ resolved: metric(n - outcomes.unreviewed - outcomes.unresolved, n),
120
+ outcomes,
121
+ first_response_after_availability: latencySummary(delays),
122
+ paired_with_on_time_provider: pairs,
123
+ };
124
+ }
125
+ /** Compare independent human records with provider receipt evidence on the exact same frozen incidents. */
126
+ export async function scorePilotResponses(backup, window, input, register) {
127
+ const reference = capturePilotIncidentReference(input);
128
+ const evidence = captureRegister(register);
129
+ if (evidence.reviewer === reference.curator ||
130
+ Date.parse(evidence.reviewed_through) < Date.parse(reference.window.until))
131
+ invalid();
132
+ const responses = new Map(evidence.responses.map((row) => [row.incident_id, row]));
133
+ const byId = new Map(reference.incidents.map((incident) => [incident.incident_id, incident]));
134
+ for (const row of evidence.responses) {
135
+ const incident = byId.get(row.incident_id);
136
+ if (!incident)
137
+ invalid();
138
+ for (const action of [row.acknowledgement, row.triage]) {
139
+ if (action.status === 'observed' && action.at < incident.available_at)
140
+ invalid();
141
+ }
142
+ }
143
+ const { report, onTimeProvider } = await evaluatePilotReference(backup, window, reference);
144
+ if (evidence.recall_evaluation_id !== report.evaluation_id)
145
+ invalid();
146
+ return {
147
+ version: 1,
148
+ mode: 'pilot_responses',
149
+ window: reference.window,
150
+ recall_evaluation_id: report.evaluation_id,
151
+ evaluation_id: createHash('sha256')
152
+ .update(JSON.stringify(['security-watch.pilot-responses.v1', evidence]))
153
+ .digest('hex'),
154
+ reviewed_through: evidence.reviewed_through,
155
+ reference_incidents: reference.incidents.length,
156
+ acknowledgement: scoreStage('acknowledgement', reference.incidents, responses, onTimeProvider),
157
+ triage: scoreStage('triage', reference.incidents, responses, onTimeProvider),
158
+ };
159
+ }