@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,125 @@
1
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from 'node:fs';
2
+ import { types } from 'node:util';
3
+ import { PilotReportError, validatePilotWindow } from './pilot-report.js';
4
+ const MAX_INPUT_BYTES = 1024 * 1024;
5
+ export function pilotInstant(value, problem) {
6
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u.test(value))
7
+ throw new PilotReportError(problem);
8
+ const time = Date.parse(value);
9
+ if (!Number.isSafeInteger(time) || new Date(time).toISOString() !== value)
10
+ throw new PilotReportError(problem);
11
+ return value;
12
+ }
13
+ /** Copy only own enumerable data properties. Public API values may originate outside a JSON parser. */
14
+ export function dataFields(input, names, problem) {
15
+ if (!input || typeof input !== 'object' || types.isProxy(input))
16
+ throw new PilotReportError(problem);
17
+ const prototype = Object.getPrototypeOf(input);
18
+ if ((prototype !== null && prototype !== Object.prototype) ||
19
+ Reflect.ownKeys(input).length !== names.length)
20
+ throw new PilotReportError(problem);
21
+ const data = Object.create(null);
22
+ for (const name of names) {
23
+ const descriptor = Object.getOwnPropertyDescriptor(input, name);
24
+ if (!descriptor?.enumerable || !Object.hasOwn(descriptor, 'value'))
25
+ throw new PilotReportError(problem);
26
+ data[name] = descriptor.value;
27
+ }
28
+ return data;
29
+ }
30
+ export function dataArray(rows, max, problem) {
31
+ if (types.isProxy(rows) ||
32
+ !Array.isArray(rows) ||
33
+ Object.getPrototypeOf(rows) !== Array.prototype ||
34
+ rows.length > max ||
35
+ Reflect.ownKeys(rows).length !== rows.length + 1)
36
+ throw new PilotReportError(problem);
37
+ const result = [];
38
+ for (let i = 0; i < rows.length; i++) {
39
+ const item = Object.getOwnPropertyDescriptor(rows, String(i));
40
+ if (!item?.enumerable || !Object.hasOwn(item, 'value'))
41
+ throw new PilotReportError(problem);
42
+ result.push(item.value);
43
+ }
44
+ return result;
45
+ }
46
+ export function capturePilotWindow(window) {
47
+ const requested = dataFields(window, ['from', 'until'], 'window');
48
+ if (typeof requested.from !== 'string' || typeof requested.until !== 'string')
49
+ throw new PilotReportError('window');
50
+ return validatePilotWindow({ from: requested.from, until: requested.until }, Date.now());
51
+ }
52
+ /** JSON.parse checks grammar but would otherwise discard earlier duplicate labels or case references. */
53
+ function parseJson(text, problem) {
54
+ const value = JSON.parse(text);
55
+ const stack = [];
56
+ for (const token of text.matchAll(/"(?:[^"\\]|\\.)*"|[{}\[\]]/gu)) {
57
+ if (token[0] === '{' || token[0] === '[') {
58
+ if (stack.length >= 6)
59
+ throw new PilotReportError(problem);
60
+ stack.push(token[0] === '{' ? new Set() : null);
61
+ }
62
+ else if (token[0] === '}' || token[0] === ']')
63
+ stack.pop();
64
+ else {
65
+ const keys = stack.at(-1);
66
+ if (!keys)
67
+ continue;
68
+ let next = token.index + token[0].length;
69
+ while (next < text.length && /[ \t\r\n]/u.test(text[next]))
70
+ next++;
71
+ if (text[next] !== ':')
72
+ continue;
73
+ const key = JSON.parse(token[0]);
74
+ if (keys.has(key))
75
+ throw new PilotReportError(problem);
76
+ keys.add(key);
77
+ }
78
+ }
79
+ return value;
80
+ }
81
+ /** Read bounded private feedback without following links or opening a special file for blocking I/O. */
82
+ export function readPrivatePilotJson(path, problem) {
83
+ let fd;
84
+ try {
85
+ const original = lstatSync(path, { bigint: true });
86
+ if (!original.isFile() || original.nlink !== 1n)
87
+ throw new PilotReportError(problem);
88
+ fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
89
+ const stat = fstatSync(fd, { bigint: true });
90
+ if (!stat.isFile() ||
91
+ stat.nlink !== 1n ||
92
+ original.ino !== stat.ino ||
93
+ original.dev !== stat.dev ||
94
+ stat.size > BigInt(problem === 'responses' ? 2 * MAX_INPUT_BYTES : MAX_INPUT_BYTES) ||
95
+ (process.platform !== 'win32' && (stat.mode & 63n) !== 0n))
96
+ throw new PilotReportError(problem);
97
+ const bytes = Buffer.alloc(Number(stat.size) + 1);
98
+ let pos = 0;
99
+ while (pos < bytes.length) {
100
+ const length = readSync(fd, bytes, pos, bytes.length - pos, null);
101
+ if (!length)
102
+ break;
103
+ pos += length;
104
+ }
105
+ const after = fstatSync(fd, { bigint: true });
106
+ const current = lstatSync(path, { bigint: true });
107
+ if (BigInt(pos) !== stat.size ||
108
+ !current.isFile() ||
109
+ current.ino !== stat.ino ||
110
+ current.dev !== stat.dev ||
111
+ after.nlink !== 1n ||
112
+ after.mtimeNs !== stat.mtimeNs ||
113
+ after.ctimeNs !== stat.ctimeNs ||
114
+ after.size !== stat.size)
115
+ throw new PilotReportError(problem);
116
+ return parseJson(new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, pos)), problem);
117
+ }
118
+ catch {
119
+ throw new PilotReportError(problem);
120
+ }
121
+ finally {
122
+ if (fd !== undefined)
123
+ closeSync(fd);
124
+ }
125
+ }
@@ -0,0 +1,166 @@
1
+ import { type PilotWindow } from './pilot-report.js';
2
+ interface UrgentIncident {
3
+ incident_id: string;
4
+ event_refs: string[];
5
+ system_ref: string;
6
+ component_ref: string | null;
7
+ available_at: string;
8
+ deadline_at: string;
9
+ }
10
+ export interface PilotIncidentReference {
11
+ version: 1;
12
+ window: PilotWindow;
13
+ curator: string;
14
+ selected_independently: true;
15
+ incidents: UrgentIncident[];
16
+ }
17
+ /** Copy and validate the whole external denominator before starting asynchronous backup verification. */
18
+ export declare function capturePilotIncidentReference(input: unknown): PilotIncidentReference;
19
+ export declare function readPilotIncidentReference(path: string): PilotIncidentReference;
20
+ /** Evaluate each independently enumerated incident against retained decisions and transport receipts. */
21
+ export declare function evaluatePilotReference(backup: string, window: PilotWindow, reference: PilotIncidentReference): Promise<{
22
+ report: {
23
+ version: 1;
24
+ mode: 'pilot_recall';
25
+ window: PilotWindow;
26
+ evaluation_id: string;
27
+ reference_incidents: number;
28
+ outcomes: {
29
+ on_time_immediate: number;
30
+ on_time_other: number;
31
+ late_only: number;
32
+ prior_and_late: number;
33
+ prior_only: number;
34
+ no_retained_match: number;
35
+ };
36
+ metrics: {
37
+ on_time_observed: {
38
+ numerator: number;
39
+ denominator: number;
40
+ rate: number | null;
41
+ };
42
+ on_time_immediate: {
43
+ numerator: number;
44
+ denominator: number;
45
+ rate: number | null;
46
+ };
47
+ };
48
+ provider_acceptance: {
49
+ on_time: {
50
+ numerator: number;
51
+ denominator: number;
52
+ rate: number | null;
53
+ };
54
+ on_time_immediate: {
55
+ numerator: number;
56
+ denominator: number;
57
+ rate: number | null;
58
+ };
59
+ incidents_with: {
60
+ on_time: number;
61
+ before_availability: number;
62
+ at_or_after_deadline: number;
63
+ accepted_time_unknown: number;
64
+ pending: number;
65
+ sending: number;
66
+ unknown: number;
67
+ failed: number;
68
+ };
69
+ without_retained_job: number;
70
+ first_acceptance_after_availability: {
71
+ count: number;
72
+ median_ms: number | null;
73
+ p95_ms: number | null;
74
+ };
75
+ };
76
+ unmeasured: {
77
+ population_urgent_recall: null;
78
+ delivered_alert_recall: null;
79
+ monitor_window_completeness: null;
80
+ };
81
+ };
82
+ onTimeProvider: Set<string>;
83
+ }>;
84
+ export declare function scorePilotRecall(backup: string, window: PilotWindow, input: PilotIncidentReference): Promise<{
85
+ version: 1;
86
+ mode: 'pilot_recall';
87
+ window: PilotWindow;
88
+ evaluation_id: string;
89
+ reference_incidents: number;
90
+ outcomes: {
91
+ on_time_immediate: number;
92
+ on_time_other: number;
93
+ late_only: number;
94
+ prior_and_late: number;
95
+ prior_only: number;
96
+ no_retained_match: number;
97
+ };
98
+ metrics: {
99
+ on_time_observed: {
100
+ numerator: number;
101
+ denominator: number;
102
+ rate: number | null;
103
+ };
104
+ on_time_immediate: {
105
+ numerator: number;
106
+ denominator: number;
107
+ rate: number | null;
108
+ };
109
+ };
110
+ provider_acceptance: {
111
+ on_time: {
112
+ numerator: number;
113
+ denominator: number;
114
+ rate: number | null;
115
+ };
116
+ on_time_immediate: {
117
+ numerator: number;
118
+ denominator: number;
119
+ rate: number | null;
120
+ };
121
+ incidents_with: {
122
+ on_time: number;
123
+ before_availability: number;
124
+ at_or_after_deadline: number;
125
+ accepted_time_unknown: number;
126
+ pending: number;
127
+ sending: number;
128
+ unknown: number;
129
+ failed: number;
130
+ };
131
+ without_retained_job: number;
132
+ first_acceptance_after_availability: {
133
+ count: number;
134
+ median_ms: number | null;
135
+ p95_ms: number | null;
136
+ };
137
+ };
138
+ unmeasured: {
139
+ population_urgent_recall: null;
140
+ delivered_alert_recall: null;
141
+ monitor_window_completeness: null;
142
+ };
143
+ }>;
144
+ export type PilotRecallScore = Awaited<ReturnType<typeof scorePilotRecall>>;
145
+ /** Prepare a blind worksheet for the independent reviewer of this exact backup and incident list. */
146
+ export declare function createPilotResponseTemplate(backup: string, window: PilotWindow, input: PilotIncidentReference): Promise<{
147
+ version: 1;
148
+ recall_evaluation_id: string;
149
+ reviewer: null;
150
+ reviewed_independently: false;
151
+ reviewed_through: null;
152
+ responses: {
153
+ incident_id: string;
154
+ acknowledgement: {
155
+ status: 'unreviewed';
156
+ at: null;
157
+ evidence_ref: null;
158
+ };
159
+ triage: {
160
+ status: 'unreviewed';
161
+ at: null;
162
+ evidence_ref: null;
163
+ };
164
+ }[];
165
+ }>;
166
+ export {};
@@ -0,0 +1,231 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { normalizeEventId } from './assessment.js';
3
+ import { latencySummary, loadPilotCohort, metric } from './pilot-cases.js';
4
+ import { capturePilotWindow, dataArray, dataFields, pilotInstant, readPrivatePilotJson, } from './pilot-input.js';
5
+ import { PilotReportError } from './pilot-report.js';
6
+ function invalid() {
7
+ throw new PilotReportError('incidents');
8
+ }
9
+ function referenceText(value) {
10
+ if (typeof value !== 'string' ||
11
+ !value ||
12
+ value.length > 512 ||
13
+ value.trim() !== value ||
14
+ /[\u0000-\u001f\u007f]/u.test(value))
15
+ invalid();
16
+ return value;
17
+ }
18
+ function target(system, component, event) {
19
+ return JSON.stringify([system, component, event]);
20
+ }
21
+ /** Copy and validate the whole external denominator before starting asynchronous backup verification. */
22
+ export function capturePilotIncidentReference(input) {
23
+ const ref = dataFields(input, ['version', 'window', 'curator', 'selected_independently', 'incidents'], 'incidents');
24
+ if (ref.version !== 1 ||
25
+ ref.selected_independently !== true ||
26
+ typeof ref.curator !== 'string' ||
27
+ !/^[a-z][a-z0-9_-]{0,63}$/u.test(ref.curator))
28
+ invalid();
29
+ const window = dataFields(ref.window, ['from', 'until'], 'incidents');
30
+ if (typeof window.from !== 'string' || typeof window.until !== 'string')
31
+ invalid();
32
+ const { from, until, start, end } = capturePilotWindow({ from: window.from, until: window.until });
33
+ const ids = new Set(), targets = new Set();
34
+ let totalBytes = 0;
35
+ const incidents = dataArray(ref.incidents, 1000, 'incidents').map((item) => {
36
+ const row = dataFields(item, ['incident_id', 'event_refs', 'system_ref', 'component_ref', 'available_at', 'deadline_at'], 'incidents');
37
+ const incident_id = referenceText(row.incident_id), system_ref = referenceText(row.system_ref);
38
+ const component_ref = row.component_ref === null ? null : referenceText(row.component_ref);
39
+ const available_at = pilotInstant(row.available_at, 'incidents'), deadline_at = pilotInstant(row.deadline_at, 'incidents');
40
+ if (Date.parse(available_at) < start ||
41
+ Date.parse(deadline_at) > end ||
42
+ available_at >= deadline_at ||
43
+ ids.has(incident_id))
44
+ invalid();
45
+ ids.add(incident_id);
46
+ const event_refs = dataArray(row.event_refs, 16, 'incidents')
47
+ .map((alias) => {
48
+ const event = normalizeEventId(referenceText(alias));
49
+ const key = target(system_ref, component_ref, event);
50
+ if (targets.has(key))
51
+ invalid();
52
+ targets.add(key);
53
+ return event;
54
+ })
55
+ .sort();
56
+ if (!event_refs.length)
57
+ invalid();
58
+ const incident = { incident_id, event_refs, system_ref, component_ref, available_at, deadline_at };
59
+ totalBytes += Buffer.byteLength(JSON.stringify(incident));
60
+ if (totalBytes > 1024 * 1024)
61
+ invalid();
62
+ return incident;
63
+ });
64
+ incidents.sort((a, b) => (a.incident_id < b.incident_id ? -1 : a.incident_id > b.incident_id ? 1 : 0));
65
+ return {
66
+ version: 1,
67
+ window: { from, until },
68
+ curator: ref.curator,
69
+ selected_independently: true,
70
+ incidents,
71
+ };
72
+ }
73
+ export function readPilotIncidentReference(path) {
74
+ return capturePilotIncidentReference(readPrivatePilotJson(path, 'incidents'));
75
+ }
76
+ const receiptCounts = () => ({
77
+ on_time: 0,
78
+ before_availability: 0,
79
+ at_or_after_deadline: 0,
80
+ accepted_time_unknown: 0,
81
+ pending: 0,
82
+ sending: 0,
83
+ unknown: 0,
84
+ failed: 0,
85
+ });
86
+ /** Evaluate each independently enumerated incident against retained decisions and transport receipts. */
87
+ export async function evaluatePilotReference(backup, window, reference) {
88
+ const range = capturePilotWindow(window);
89
+ if (range.from !== reference.window.from || range.until !== reference.window.until)
90
+ invalid();
91
+ const { packet, routes, deliveryRevisions } = await loadPilotCohort(backup, reference.window, true);
92
+ const outcomes = {
93
+ on_time_immediate: 0,
94
+ on_time_other: 0,
95
+ late_only: 0,
96
+ prior_and_late: 0,
97
+ prior_only: 0,
98
+ no_retained_match: 0,
99
+ };
100
+ const observations = reference.incidents.map((incident) => ({
101
+ incident,
102
+ prior: false,
103
+ late: false,
104
+ onTime: false,
105
+ immediate: false,
106
+ availableAt: Date.parse(incident.available_at),
107
+ deadlineAt: Date.parse(incident.deadline_at),
108
+ receipts: new Set(),
109
+ onTimeImmediateReceipt: false,
110
+ firstLatencyMs: null,
111
+ }));
112
+ const byTarget = new Map();
113
+ for (const item of observations) {
114
+ for (const event of item.incident.event_refs)
115
+ byTarget.set(target(item.incident.system_ref, item.incident.component_ref, event), item);
116
+ }
117
+ for (const c of packet.cases) {
118
+ const match = byTarget.get(target(c.system_ref, c.component_ref, normalizeEventId(c.event_ref)));
119
+ if (!match)
120
+ continue;
121
+ // Both timestamps are canonical UTC ISO strings with the same precision.
122
+ if (c.recorded_at < match.incident.available_at)
123
+ match.prior = true;
124
+ else if (c.recorded_at >= match.incident.deadline_at)
125
+ match.late = true;
126
+ else {
127
+ match.onTime = true;
128
+ if (routes.get(c.case_id).immediate)
129
+ match.immediate = true;
130
+ }
131
+ }
132
+ for (const revision of deliveryRevisions) {
133
+ const match = byTarget.get(target(revision.system_ref, revision.component_ref, normalizeEventId(revision.event_ref)));
134
+ if (!match)
135
+ continue;
136
+ for (const job of revision.jobs) {
137
+ if (job.status !== 'accepted')
138
+ match.receipts.add(job.status);
139
+ else if (job.accepted_at === null)
140
+ match.receipts.add('accepted_time_unknown');
141
+ else if (job.accepted_at < match.availableAt)
142
+ match.receipts.add('before_availability');
143
+ else {
144
+ const delay = job.accepted_at - match.availableAt;
145
+ match.firstLatencyMs = Math.min(delay, match.firstLatencyMs ?? delay);
146
+ if (job.accepted_at >= match.deadlineAt)
147
+ match.receipts.add('at_or_after_deadline');
148
+ else {
149
+ match.receipts.add('on_time');
150
+ if (job.mode === 'notify')
151
+ match.onTimeImmediateReceipt = true;
152
+ }
153
+ }
154
+ }
155
+ }
156
+ const incidentsWith = receiptCounts();
157
+ const latencies = [];
158
+ let withoutRetainedJob = 0, onTimeImmediate = 0;
159
+ for (const observation of observations) {
160
+ if (observation.immediate)
161
+ outcomes.on_time_immediate++;
162
+ else if (observation.onTime)
163
+ outcomes.on_time_other++;
164
+ else if (observation.late && observation.prior)
165
+ outcomes.prior_and_late++;
166
+ else if (observation.late)
167
+ outcomes.late_only++;
168
+ else if (observation.prior)
169
+ outcomes.prior_only++;
170
+ else
171
+ outcomes.no_retained_match++;
172
+ if (!observation.receipts.size)
173
+ withoutRetainedJob++;
174
+ for (const state of observation.receipts)
175
+ incidentsWith[state]++;
176
+ if (observation.onTimeImmediateReceipt)
177
+ onTimeImmediate++;
178
+ if (observation.firstLatencyMs !== null)
179
+ latencies.push(observation.firstLatencyMs);
180
+ }
181
+ const denominator = observations.length;
182
+ const report = {
183
+ version: 1,
184
+ mode: 'pilot_recall',
185
+ window: reference.window,
186
+ evaluation_id: createHash('sha256')
187
+ .update(JSON.stringify(['security-watch.pilot-recall.v1', packet.packet_id, reference]))
188
+ .digest('hex'),
189
+ reference_incidents: denominator,
190
+ outcomes,
191
+ metrics: {
192
+ on_time_observed: metric(outcomes.on_time_other + outcomes.on_time_immediate, denominator),
193
+ on_time_immediate: metric(outcomes.on_time_immediate, denominator),
194
+ },
195
+ provider_acceptance: {
196
+ on_time: metric(incidentsWith.on_time, denominator),
197
+ on_time_immediate: metric(onTimeImmediate, denominator),
198
+ incidents_with: incidentsWith,
199
+ without_retained_job: withoutRetainedJob,
200
+ first_acceptance_after_availability: latencySummary(latencies),
201
+ },
202
+ unmeasured: {
203
+ population_urgent_recall: null,
204
+ delivered_alert_recall: null,
205
+ monitor_window_completeness: null,
206
+ },
207
+ };
208
+ const onTimeProvider = new Set(observations.filter((o) => o.receipts.has('on_time')).map((o) => o.incident.incident_id));
209
+ return { report, onTimeProvider };
210
+ }
211
+ export async function scorePilotRecall(backup, window, input) {
212
+ return (await evaluatePilotReference(backup, window, capturePilotIncidentReference(input))).report;
213
+ }
214
+ /** Prepare a blind worksheet for the independent reviewer of this exact backup and incident list. */
215
+ export async function createPilotResponseTemplate(backup, window, input) {
216
+ const reference = capturePilotIncidentReference(input);
217
+ const { report } = await evaluatePilotReference(backup, window, reference);
218
+ const blankStage = () => ({ status: 'unreviewed', at: null, evidence_ref: null });
219
+ return {
220
+ version: 1,
221
+ recall_evaluation_id: report.evaluation_id,
222
+ reviewer: null,
223
+ reviewed_independently: false,
224
+ reviewed_through: null,
225
+ responses: reference.incidents.map(({ incident_id }) => ({
226
+ incident_id,
227
+ acknowledgement: blankStage(),
228
+ triage: blankStage(),
229
+ })),
230
+ };
231
+ }
@@ -0,0 +1,113 @@
1
+ import type { DatabaseSync } from 'node:sqlite';
2
+ /** Both dates are UTC dates. The end is exclusive. */
3
+ export interface PilotWindow {
4
+ from: string;
5
+ until: string;
6
+ }
7
+ declare const messages: {
8
+ readonly window: 'Choose 1 to 31 complete UTC days using YYYY-MM-DD dates and an exclusive end date.';
9
+ readonly database: 'Could not read the pilot database. Choose an existing private monitor database or backup with the supported schema.';
10
+ readonly bounds: 'Pilot report size limit exceeded. See the documented database and window limits.';
11
+ readonly data: 'Pilot report could not validate the retained monitor records.';
12
+ readonly incidents: 'Invalid independent incident reference. Check the date window, exact deployment targets, aliases and response deadlines.';
13
+ readonly responses: 'Invalid pilot response register. Check the frozen evaluation, independent reviewer, evidence references and observation times.';
14
+ readonly labels: 'Invalid pilot feedback. Check the snapshot, window, case references and independent reviewer declarations.';
15
+ };
16
+ export declare class PilotReportError extends Error {
17
+ constructor(code: keyof typeof messages);
18
+ }
19
+ export declare function validatePilotWindow(input: PilotWindow, now: number): {
20
+ from: string;
21
+ until: string;
22
+ start: number;
23
+ end: number;
24
+ days: number;
25
+ };
26
+ interface PilotCoverage {
27
+ receipts: number;
28
+ status: Record<'complete' | 'partial' | 'failed', number>;
29
+ freshness: Record<'fresh' | 'stale' | 'never', number> | null;
30
+ }
31
+ /** The caller owns a READONLY handle and a deferred read transaction covering every query. */
32
+ export declare function aggregatePilotReport(db: DatabaseSync, range: ReturnType<typeof validatePilotWindow>, asOf: number): {
33
+ version: 1;
34
+ mode: 'pilot_report';
35
+ window: {
36
+ from: string;
37
+ until: string;
38
+ days: number;
39
+ };
40
+ activity: {
41
+ finding_revisions: number;
42
+ distinct_findings: number;
43
+ evidence_revisions: number;
44
+ days_with_retained_revisions: number;
45
+ decisions: {
46
+ record: number;
47
+ digest: number;
48
+ notify: number;
49
+ };
50
+ daily: {
51
+ date: string;
52
+ evidence_revisions: number;
53
+ finding_revisions: number;
54
+ decisions: {
55
+ record: number;
56
+ digest: number;
57
+ notify: number;
58
+ };
59
+ }[];
60
+ delivery_states_for_revisions: {
61
+ pending: number;
62
+ sending: number;
63
+ accepted: number;
64
+ failed: number;
65
+ unknown: number;
66
+ };
67
+ reviews: {
68
+ opened: number;
69
+ latest_response_rows: number;
70
+ latency_samples: number;
71
+ invalid_latency_rows: number;
72
+ open_to_latest_response_p95_ms: number | null;
73
+ };
74
+ model_reservations: {
75
+ requests: number;
76
+ tokens: number;
77
+ unpriced_requests: number;
78
+ known_reserved_usd: number;
79
+ reserved_usd: number | null;
80
+ };
81
+ };
82
+ snapshot: {
83
+ source: 'monitor_database' | 'verified_backup';
84
+ read_at: string;
85
+ delivery_states: {
86
+ pending: number;
87
+ sending: number;
88
+ accepted: number;
89
+ failed: number;
90
+ unknown: number;
91
+ };
92
+ reviews: {
93
+ pending: number;
94
+ investigate: number;
95
+ oldest_open_age_ms: number | null;
96
+ };
97
+ source_coverage: PilotCoverage | null;
98
+ last_scan: {
99
+ age_ms: number | null;
100
+ duration_ms: number | null;
101
+ degraded: boolean | null;
102
+ } | null;
103
+ };
104
+ unmeasured: {
105
+ urgent_recall: null;
106
+ false_alert_rate: null;
107
+ source_to_triage_p95_ms: null;
108
+ monitored_days: null;
109
+ actual_model_spend_usd: null;
110
+ };
111
+ };
112
+ export type PilotReport = ReturnType<typeof aggregatePilotReport>;
113
+ export {};