@shieldaai/security-watch 0.1.0-alpha.0 → 1.0.1
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.
- package/CHANGELOG.md +178 -0
- package/CONTRIBUTING.md +4 -2
- package/README.md +173 -48
- package/SECURITY.md +24 -9
- package/dist/assessment.d.ts +12 -1
- package/dist/assessment.js +223 -52
- package/dist/cli.js +340 -27
- package/dist/config.d.ts +62 -2
- package/dist/config.js +88 -5
- package/dist/coverage.d.ts +4 -0
- package/dist/coverage.js +11 -0
- package/dist/cve-now.d.ts +32 -2
- package/dist/cve-now.js +715 -126
- package/dist/cvss4.d.ts +3 -0
- package/dist/cvss4.js +39 -0
- package/dist/delivery.d.ts +34 -2
- package/dist/delivery.js +391 -98
- package/dist/ecosystems.d.ts +23 -0
- package/dist/ecosystems.js +88 -10
- package/dist/engine.d.ts +55 -1
- package/dist/engine.js +101 -20
- package/dist/everyday-words.d.ts +11 -0
- package/dist/everyday-words.js +256 -0
- package/dist/health.d.ts +7 -0
- package/dist/health.js +55 -3
- package/dist/http.d.ts +7 -0
- package/dist/http.js +31 -2
- package/dist/index.d.ts +22 -4
- package/dist/index.js +12 -4
- package/dist/inventory-evidence.d.ts +10 -0
- package/dist/inventory-evidence.js +206 -0
- package/dist/inventory.d.ts +273 -0
- package/dist/inventory.js +210 -17
- package/dist/maintenance.d.ts +5 -0
- package/dist/maintenance.js +73 -5
- package/dist/matching.d.ts +29 -0
- package/dist/matching.js +537 -0
- package/dist/models.d.ts +17 -4
- package/dist/models.js +359 -29
- package/dist/pilot-cases.d.ts +171 -0
- package/dist/pilot-cases.js +330 -0
- package/dist/pilot-input.d.ts +16 -0
- package/dist/pilot-input.js +125 -0
- package/dist/pilot-recall.d.ts +166 -0
- package/dist/pilot-recall.js +231 -0
- package/dist/pilot-report.d.ts +113 -0
- package/dist/pilot-report.js +279 -0
- package/dist/pilot-responses.d.ts +111 -0
- package/dist/pilot-responses.js +159 -0
- package/dist/python-version.d.ts +3 -0
- package/dist/python-version.js +30 -0
- package/dist/rehearsal.d.ts +440 -0
- package/dist/rehearsal.js +372 -0
- package/dist/sbom.d.ts +13 -0
- package/dist/sbom.js +193 -0
- package/dist/source-error.d.ts +17 -1
- package/dist/source-error.js +18 -3
- package/dist/sources.d.ts +2 -2
- package/dist/sources.js +699 -45
- package/dist/store.d.ts +38 -13
- package/dist/store.js +325 -23
- package/dist/types.d.ts +159 -2
- package/dist/util.d.ts +23 -0
- package/dist/util.js +81 -1
- package/dist/vendor/cvss4-reference.d.ts +2 -0
- package/dist/vendor/cvss4-reference.js +789 -0
- package/dist/word-filter.d.ts +3 -0
- package/dist/word-filter.js +3291 -0
- package/docs/alert-outcome-evaluation.md +150 -0
- package/docs/compatibility.md +35 -0
- package/docs/configuration.md +289 -29
- package/docs/cvss-v4-support.md +41 -0
- package/docs/offline-advisory-preview.md +114 -0
- package/docs/offline-rehearsal.md +44 -0
- package/docs/pilot-cases.md +58 -0
- package/docs/pilot-recall.md +124 -0
- package/docs/pilot-report.md +52 -0
- package/docs/validation/alert-outcome-evaluation-2026-11-05.json +2935 -0
- package/docs/validation/cvss-v4-reference-parity-2026-11-05.json +93 -0
- package/docs/validation/rehearsal-accepted-2026-11-05.json +175 -0
- package/docs/validation/rehearsal-unknown-2026-11-05.json +175 -0
- package/docs/vendor/cvss-v4-LICENSE.txt +22 -0
- package/docs/vendor/cvss-v4-provenance.json +38 -0
- package/examples/agent-advisories-2026.json +145 -0
- package/examples/agent-advisory-cases-2026.json +397 -0
- package/examples/libraries.example.txt +4 -2
- package/examples/libraries.example.yaml +2 -0
- package/examples/offline-advisory-preview.mjs +42 -0
- package/examples/rehearsal.json +75 -0
- package/examples/systems.example.yaml +4 -0
- package/package.json +24 -7
- package/docs/quality-review.md +0 -104
package/dist/store.d.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
-
import type { Assessment, Config, Decision, Evidence, Notification } from './types.js';
|
|
1
|
+
import type { AiReview, Assessment, Config, Decision, Evidence, Notification } from './types.js';
|
|
2
|
+
import { type PilotWindow, type PilotReport } from './pilot-report.js';
|
|
2
3
|
import { type PruneReport, type RetentionPolicy } from './maintenance.js';
|
|
3
|
-
export declare const SCHEMA_VERSION =
|
|
4
|
+
export declare const SCHEMA_VERSION = 7;
|
|
4
5
|
/** Durable state for one local worker. Stores evidence and results, never provider credentials. */
|
|
5
6
|
export declare class Store {
|
|
6
7
|
#private;
|
|
8
|
+
/** Collect one consistent read-only snapshot from an existing local database. */
|
|
9
|
+
static readPilotReport(database: string, window: PilotWindow): PilotReport;
|
|
7
10
|
constructor(path: string, options?: {
|
|
8
11
|
readOnly?: boolean;
|
|
9
12
|
migrate?: boolean;
|
|
@@ -18,7 +21,29 @@ export declare class Store {
|
|
|
18
21
|
recorded_at: number;
|
|
19
22
|
}[];
|
|
20
23
|
checkpoints(): Record<string, string>;
|
|
21
|
-
saveAssessment(assessment: Assessment, decision: Decision, now?: number, digestMs?: number): void;
|
|
24
|
+
saveAssessment(assessment: Assessment, decision: Decision, now?: number, digestMs?: number, reviewBasis?: string): void;
|
|
25
|
+
/** Bounded local queue. Cursor is the stable (created_at, finding_id, revision) tuple. */
|
|
26
|
+
reviews(options?: {
|
|
27
|
+
includeResolved?: boolean;
|
|
28
|
+
limit?: number;
|
|
29
|
+
after?: {
|
|
30
|
+
created_at: number;
|
|
31
|
+
finding_id: string;
|
|
32
|
+
revision: number;
|
|
33
|
+
};
|
|
34
|
+
}): AiReview[];
|
|
35
|
+
reviewSummary(now?: number): {
|
|
36
|
+
pending: number;
|
|
37
|
+
investigate: number;
|
|
38
|
+
oldest_open_at: number | null;
|
|
39
|
+
oldest_open_age_ms: number | null;
|
|
40
|
+
};
|
|
41
|
+
/** OS/private database access authenticates this local operation; reviewer is a declared label. */
|
|
42
|
+
reviewFinding(id: string, revision: number, decision: {
|
|
43
|
+
disposition: 'dismiss' | 'investigate';
|
|
44
|
+
reviewer: string;
|
|
45
|
+
reason: string;
|
|
46
|
+
}, now?: number): void;
|
|
22
47
|
findings(): Assessment[];
|
|
23
48
|
getFinding(id: string): Assessment | undefined;
|
|
24
49
|
controls(id: string, now?: number): {
|
|
@@ -47,18 +72,13 @@ export declare class Store {
|
|
|
47
72
|
recorded_at: number;
|
|
48
73
|
}[];
|
|
49
74
|
jobs(): Notification[];
|
|
50
|
-
claimDue(now?: number, excludedChannels?: Notification['channel'][]): Notification | undefined;
|
|
51
|
-
claimAdditionalDigest(channel: Notification['channel'], now?: number, limit?: number): Notification[];
|
|
52
|
-
completeJob(id: string, status: 'accepted' | 'unknown' | 'failed' | 'pending', nextAt: number, error?: string): void;
|
|
53
|
-
deferJob(id: string, nextAt: number, reason?: string): void;
|
|
54
75
|
retryJob(id: string, now?: number): void;
|
|
55
|
-
|
|
56
|
-
|
|
76
|
+
/** The current revision number of a finding, or undefined when it does not exist. */
|
|
77
|
+
revisionOf(id: string): number | undefined;
|
|
78
|
+
/** Acknowledge the current revision. Pass the revision that was read to refuse a newer, unseen one. */
|
|
79
|
+
acknowledge(id: string, revision?: number): number;
|
|
57
80
|
suppress(id: string, until: number, reason: string): void;
|
|
58
|
-
getMeta(key: string): string | undefined;
|
|
59
|
-
setMeta(key: string, value: string, now?: number): void;
|
|
60
81
|
prune(policy: RetentionPolicy, now?: number, apply?: boolean): PruneReport;
|
|
61
|
-
reserveBudget(day: string, maxRequests: number, maxTokens: number, maxUsd: number | undefined, tokens: number, usd: number | undefined): boolean;
|
|
62
82
|
budgets(): {
|
|
63
83
|
day: string;
|
|
64
84
|
requests: number;
|
|
@@ -67,5 +87,10 @@ export declare class Store {
|
|
|
67
87
|
known_usd?: number;
|
|
68
88
|
unpriced_requests?: number;
|
|
69
89
|
}[];
|
|
70
|
-
|
|
90
|
+
/**
|
|
91
|
+
* Write a snapshot and publish it at `path`. When `verify` is given it checks the snapshot first,
|
|
92
|
+
* and a snapshot that fails is removed instead of being left at the destination.
|
|
93
|
+
*/
|
|
94
|
+
backup(path: string, verify?: (snapshot: string) => Promise<void>): Promise<void>;
|
|
71
95
|
}
|
|
96
|
+
export declare const readPilotReport: typeof Store.readPilotReport;
|
package/dist/store.js
CHANGED
|
@@ -2,10 +2,11 @@ import { DatabaseSync, backup as sqliteBackup } from 'node:sqlite';
|
|
|
2
2
|
import { closeSync, constants, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, openSync, rmSync, } from 'node:fs';
|
|
3
3
|
import { dirname, join, resolve } from 'node:path';
|
|
4
4
|
import { randomUUID } from 'node:crypto';
|
|
5
|
-
import { hash } from './util.js';
|
|
5
|
+
import { hash, canonicalHash } from './util.js';
|
|
6
6
|
import { decide } from './assessment.js';
|
|
7
|
+
import { aggregatePilotReport, validatePilotWindow, PilotReportError, } from './pilot-report.js';
|
|
7
8
|
import { validateRetentionPolicy, } from './maintenance.js';
|
|
8
|
-
export const SCHEMA_VERSION =
|
|
9
|
+
export const SCHEMA_VERSION = 7;
|
|
9
10
|
function verifyFile(path) {
|
|
10
11
|
// Closing any descriptor for a live SQLite inode releases this process's POSIX locks.
|
|
11
12
|
// Inspect existing files without opening them, including when another Store is already open.
|
|
@@ -44,11 +45,13 @@ function notification(row) {
|
|
|
44
45
|
return {
|
|
45
46
|
id: String(row.id),
|
|
46
47
|
finding_id: String(row.finding_id),
|
|
48
|
+
revision: Number(row.revision),
|
|
47
49
|
channel: row.channel,
|
|
48
50
|
payload: String(row.payload),
|
|
49
51
|
status: row.status,
|
|
50
52
|
attempts: Number(row.attempts),
|
|
51
53
|
available_at: Number(row.available_at),
|
|
54
|
+
...(row.accepted_at == null ? {} : { accepted_at: Number(row.accepted_at) }),
|
|
52
55
|
...(row.last_error == null ? {} : { last_error: String(row.last_error) }),
|
|
53
56
|
};
|
|
54
57
|
}
|
|
@@ -72,13 +75,84 @@ function fingerprint(a, decision) {
|
|
|
72
75
|
withdrawn: a.withdrawn ?? false,
|
|
73
76
|
active: a.active !== false,
|
|
74
77
|
fix: a.fix ?? null,
|
|
78
|
+
remediation: a.remediation
|
|
79
|
+
? {
|
|
80
|
+
status: a.remediation.status,
|
|
81
|
+
artifact_digest: a.remediation.artifact_digest,
|
|
82
|
+
configuration: a.remediation.configuration,
|
|
83
|
+
}
|
|
84
|
+
: null,
|
|
75
85
|
action: decision.action,
|
|
76
86
|
});
|
|
77
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* The fingerprints earlier releases stored for the same finding. A finding saved by an earlier
|
|
90
|
+
* release and unchanged in everything that release compared is not a new revision: an upgrade must
|
|
91
|
+
* not re-send alerts or drop acknowledgements. Keep one entry per released fingerprint format.
|
|
92
|
+
*/
|
|
93
|
+
function earlierFingerprints(a, decision) {
|
|
94
|
+
// A snapshot packed before the alpha tag (schema 4).
|
|
95
|
+
const alpha = {
|
|
96
|
+
event: a.event_id,
|
|
97
|
+
system: a.system_id,
|
|
98
|
+
component: a.component_id,
|
|
99
|
+
category: a.category,
|
|
100
|
+
applicability: a.applicability,
|
|
101
|
+
severity: a.source_severity,
|
|
102
|
+
priority: a.priority,
|
|
103
|
+
exploited: a.exploited,
|
|
104
|
+
withdrawn: a.withdrawn ?? false,
|
|
105
|
+
active: a.active !== false,
|
|
106
|
+
fix: a.fix ?? null,
|
|
107
|
+
action: decision.action,
|
|
108
|
+
};
|
|
109
|
+
// The tagged 0.1.0-alpha.0 (schema 5) and later development builds (schema 6) have the news fields.
|
|
110
|
+
const { event, system, component, category, applicability, ...rest } = alpha;
|
|
111
|
+
const withNews = {
|
|
112
|
+
event,
|
|
113
|
+
system,
|
|
114
|
+
component,
|
|
115
|
+
category,
|
|
116
|
+
applicability,
|
|
117
|
+
news_classification: a.news_analysis?.classification ?? null,
|
|
118
|
+
news_impact: a.news_analysis?.impact ?? null,
|
|
119
|
+
...rest,
|
|
120
|
+
};
|
|
121
|
+
return [hash(alpha), hash(withNews)];
|
|
122
|
+
}
|
|
78
123
|
/** Durable state for one local worker. Stores evidence and results, never provider credentials. */
|
|
79
124
|
export class Store {
|
|
80
125
|
#db;
|
|
81
126
|
#path;
|
|
127
|
+
/** Collect one consistent read-only snapshot from an existing local database. */
|
|
128
|
+
static readPilotReport(database, window) {
|
|
129
|
+
const now = Date.now();
|
|
130
|
+
const range = validatePilotWindow(window, now);
|
|
131
|
+
if (typeof database !== 'string' || !database || database === ':memory:')
|
|
132
|
+
throw new PilotReportError('database');
|
|
133
|
+
let reader;
|
|
134
|
+
try {
|
|
135
|
+
reader = new Store(database, { readOnly: true });
|
|
136
|
+
reader.#db.exec('PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; BEGIN');
|
|
137
|
+
const report = aggregatePilotReport(reader.#db, range, now);
|
|
138
|
+
reader.#db.exec('COMMIT');
|
|
139
|
+
return report;
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
if (error instanceof PilotReportError)
|
|
143
|
+
throw error;
|
|
144
|
+
throw new PilotReportError('database');
|
|
145
|
+
}
|
|
146
|
+
finally {
|
|
147
|
+
// Closing also releases an unfinished read transaction on failure.
|
|
148
|
+
try {
|
|
149
|
+
reader?.close();
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
throw new PilotReportError('database');
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
82
156
|
constructor(path, options = {}) {
|
|
83
157
|
this.#path = path === ':memory:' ? path : resolve(path);
|
|
84
158
|
if (this.#path !== ':memory:') {
|
|
@@ -100,8 +174,8 @@ export class Store {
|
|
|
100
174
|
throw new Error('Database migration required; stop the worker and run scan or start first');
|
|
101
175
|
if (!options.readOnly)
|
|
102
176
|
this.#db.exec('PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL;');
|
|
103
|
-
if (version
|
|
104
|
-
this.#
|
|
177
|
+
if (version < SCHEMA_VERSION)
|
|
178
|
+
this.#migrate(1, () => {
|
|
105
179
|
this.#db.exec(`
|
|
106
180
|
CREATE TABLE evidence (source TEXT NOT NULL, id TEXT NOT NULL, payload TEXT NOT NULL, PRIMARY KEY(source,id));
|
|
107
181
|
CREATE TABLE metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
@@ -117,8 +191,8 @@ export class Store {
|
|
|
117
191
|
PRAGMA user_version = 1;
|
|
118
192
|
`);
|
|
119
193
|
});
|
|
120
|
-
if (version <
|
|
121
|
-
this.#
|
|
194
|
+
if (version < SCHEMA_VERSION)
|
|
195
|
+
this.#migrate(2, () => {
|
|
122
196
|
this.#db
|
|
123
197
|
.exec(`CREATE TABLE finding_revisions (finding_id TEXT NOT NULL REFERENCES findings(id), revision INTEGER NOT NULL,
|
|
124
198
|
payload TEXT NOT NULL, decision TEXT NOT NULL, recorded_at INTEGER NOT NULL, PRIMARY KEY(finding_id,revision));
|
|
@@ -126,8 +200,8 @@ export class Store {
|
|
|
126
200
|
SELECT id,revision,payload,'{"action":"record","channels":[],"reason":"Imported from schema 1"}',0 FROM findings;
|
|
127
201
|
PRAGMA user_version = 2;`);
|
|
128
202
|
});
|
|
129
|
-
if (version <
|
|
130
|
-
this.#
|
|
203
|
+
if (version < SCHEMA_VERSION)
|
|
204
|
+
this.#migrate(3, () => {
|
|
131
205
|
this.#db
|
|
132
206
|
.exec(`CREATE TABLE evidence_revisions (source TEXT NOT NULL, id TEXT NOT NULL, content_hash TEXT NOT NULL,
|
|
133
207
|
payload TEXT NOT NULL, recorded_at INTEGER NOT NULL, PRIMARY KEY(source,id,content_hash));`);
|
|
@@ -138,12 +212,12 @@ export class Store {
|
|
|
138
212
|
}
|
|
139
213
|
this.#db.exec('PRAGMA user_version = 3;');
|
|
140
214
|
});
|
|
141
|
-
if (version <
|
|
142
|
-
this.#
|
|
215
|
+
if (version < SCHEMA_VERSION)
|
|
216
|
+
this.#migrate(4, () => {
|
|
143
217
|
this.#db.exec('CREATE INDEX IF NOT EXISTS evidence_by_id ON evidence(id); PRAGMA user_version = 4;');
|
|
144
218
|
});
|
|
145
|
-
if (version <
|
|
146
|
-
this.#
|
|
219
|
+
if (version < SCHEMA_VERSION)
|
|
220
|
+
this.#migrate(5, () => {
|
|
147
221
|
this.#db.exec(`
|
|
148
222
|
ALTER TABLE metadata ADD COLUMN updated_at INTEGER;
|
|
149
223
|
ALTER TABLE evidence ADD COLUMN content_hash TEXT;
|
|
@@ -172,6 +246,28 @@ export class Store {
|
|
|
172
246
|
}
|
|
173
247
|
this.#db.exec('PRAGMA user_version = 5');
|
|
174
248
|
});
|
|
249
|
+
if (version < SCHEMA_VERSION)
|
|
250
|
+
this.#migrate(6, () => {
|
|
251
|
+
this.#db.exec(`CREATE TABLE IF NOT EXISTS ai_reviews (
|
|
252
|
+
finding_id TEXT NOT NULL REFERENCES findings(id), revision INTEGER NOT NULL,
|
|
253
|
+
reason TEXT NOT NULL CHECK(reason IN ('ai_general_news','ai_not_affected','ai_irrelevant')),
|
|
254
|
+
status TEXT NOT NULL CHECK(status IN ('pending','investigate','dismissed','superseded')),
|
|
255
|
+
evidence_refs TEXT NOT NULL, created_at INTEGER NOT NULL,
|
|
256
|
+
reviewed_at INTEGER, reviewer TEXT, note TEXT,
|
|
257
|
+
PRIMARY KEY(finding_id,revision),
|
|
258
|
+
FOREIGN KEY(finding_id,revision) REFERENCES finding_revisions(finding_id,revision));
|
|
259
|
+
CREATE INDEX IF NOT EXISTS ai_reviews_queue ON ai_reviews(status,created_at,finding_id);
|
|
260
|
+
PRAGMA user_version = 6;`);
|
|
261
|
+
});
|
|
262
|
+
if (version < SCHEMA_VERSION)
|
|
263
|
+
this.#migrate(7, () => {
|
|
264
|
+
// available_at records scheduling. Old accepted notifications have no observed receipt time.
|
|
265
|
+
this.#db.exec(`ALTER TABLE notifications ADD COLUMN accepted_at INTEGER
|
|
266
|
+
CHECK (accepted_at IS NULL OR (status='accepted' AND typeof(accepted_at)='integer'
|
|
267
|
+
AND accepted_at BETWEEN 1 AND 8640000000000000));
|
|
268
|
+
CREATE INDEX notifications_by_acceptance ON notifications(accepted_at) WHERE accepted_at IS NOT NULL;
|
|
269
|
+
PRAGMA user_version = 7;`);
|
|
270
|
+
});
|
|
175
271
|
if (!options.readOnly)
|
|
176
272
|
this.#privateSidecars();
|
|
177
273
|
}
|
|
@@ -186,6 +282,19 @@ export class Store {
|
|
|
186
282
|
existingSidecars(this.#path);
|
|
187
283
|
}
|
|
188
284
|
}
|
|
285
|
+
/**
|
|
286
|
+
* Run one schema step unless another process already applied it. The version is read again inside
|
|
287
|
+
* the write transaction, so two processes opening an old database cannot repeat or undo a step.
|
|
288
|
+
*/
|
|
289
|
+
#migrate(target, step) {
|
|
290
|
+
this.#transaction(() => {
|
|
291
|
+
const current = Number(this.#db.prepare('PRAGMA user_version').get().user_version);
|
|
292
|
+
if (current > SCHEMA_VERSION)
|
|
293
|
+
throw new Error(`Database schema ${current} is newer than supported schema ${SCHEMA_VERSION}`);
|
|
294
|
+
if (current < target)
|
|
295
|
+
step();
|
|
296
|
+
});
|
|
297
|
+
}
|
|
189
298
|
#transaction(fn) {
|
|
190
299
|
this.#db.exec('BEGIN IMMEDIATE');
|
|
191
300
|
try {
|
|
@@ -259,7 +368,7 @@ export class Store {
|
|
|
259
368
|
.all()
|
|
260
369
|
.map((r) => [String(r.key).slice('checkpoint:'.length), String(r.value)]));
|
|
261
370
|
}
|
|
262
|
-
saveAssessment(assessment, decision, now = Date.now(), digestMs = 86_400_000) {
|
|
371
|
+
saveAssessment(assessment, decision, now = Date.now(), digestMs = 86_400_000, reviewBasis) {
|
|
263
372
|
if (!Number.isSafeInteger(now) ||
|
|
264
373
|
!Number.isSafeInteger(digestMs) ||
|
|
265
374
|
digestMs < 0 ||
|
|
@@ -267,8 +376,33 @@ export class Store {
|
|
|
267
376
|
throw new Error('Invalid notification time');
|
|
268
377
|
this.#transaction(() => {
|
|
269
378
|
const old = this.#db.prepare('SELECT * FROM findings WHERE id=?').get(assessment.id);
|
|
270
|
-
const
|
|
271
|
-
|
|
379
|
+
const references = decision.review
|
|
380
|
+
? this.#db
|
|
381
|
+
.prepare('SELECT source,id,content_hash FROM evidence WHERE id IN (SELECT value FROM json_each(?)) ORDER BY source,id')
|
|
382
|
+
.all(JSON.stringify(assessment.evidence_ids))
|
|
383
|
+
.map((row) => ({
|
|
384
|
+
source: String(row.source),
|
|
385
|
+
id: String(row.id),
|
|
386
|
+
content_hash: String(row.content_hash),
|
|
387
|
+
}))
|
|
388
|
+
: [];
|
|
389
|
+
// Where the finding lives (inventory names and notes) is shown to the reader; it is not part
|
|
390
|
+
// of the conclusion a reviewer approves, so editing a note does not ask for a new review.
|
|
391
|
+
const { updated_at: _updated, location: _location, ...reviewedAssessment } = assessment;
|
|
392
|
+
// Ordinary alert deduplication stays semantic. A human review instead binds the exact
|
|
393
|
+
// supplied conclusion, source content and host inventory/model context, excluding scan time.
|
|
394
|
+
const signature = decision.review
|
|
395
|
+
? canonicalHash({
|
|
396
|
+
finding: fingerprint(assessment, decision),
|
|
397
|
+
review: decision.review,
|
|
398
|
+
assessment: reviewedAssessment,
|
|
399
|
+
evidence: references,
|
|
400
|
+
basis: reviewBasis ?? null,
|
|
401
|
+
})
|
|
402
|
+
: fingerprint(assessment, decision);
|
|
403
|
+
const changed = !old ||
|
|
404
|
+
(signature !== old.fingerprint &&
|
|
405
|
+
!earlierFingerprints(assessment, decision).includes(String(old.fingerprint)));
|
|
272
406
|
const revision = old ? Number(old.revision) + (changed ? 1 : 0) : 1;
|
|
273
407
|
this.#db
|
|
274
408
|
.prepare(`INSERT INTO findings(id,payload,fingerprint,revision,updated_at) VALUES(?,?,?,?,?)
|
|
@@ -278,6 +412,15 @@ export class Store {
|
|
|
278
412
|
this.#db
|
|
279
413
|
.prepare('INSERT INTO finding_revisions(finding_id,revision,payload,decision,recorded_at) VALUES(?,?,?,?,?)')
|
|
280
414
|
.run(assessment.id, revision, JSON.stringify(assessment), JSON.stringify(decision), now);
|
|
415
|
+
if (changed || !decision.review)
|
|
416
|
+
this.#db
|
|
417
|
+
.prepare("UPDATE ai_reviews SET status='superseded' WHERE finding_id=? AND status IN ('pending','investigate')")
|
|
418
|
+
.run(assessment.id);
|
|
419
|
+
if (decision.review && assessment.active !== false && !assessment.withdrawn)
|
|
420
|
+
this.#db
|
|
421
|
+
.prepare(`INSERT INTO ai_reviews(finding_id,revision,reason,status,evidence_refs,created_at)
|
|
422
|
+
VALUES(?,?,?,'pending',?,?) ON CONFLICT(finding_id,revision) DO NOTHING`)
|
|
423
|
+
.run(assessment.id, revision, decision.review, JSON.stringify(references), now);
|
|
281
424
|
if (changed)
|
|
282
425
|
this.#db
|
|
283
426
|
.prepare("UPDATE notifications SET status='failed',last_error='Superseded by a newer assessment' WHERE finding_id=? AND status='pending'")
|
|
@@ -310,6 +453,108 @@ export class Store {
|
|
|
310
453
|
.run(randomUUID(), assessment.id, revision, channel, payload, availableAt);
|
|
311
454
|
});
|
|
312
455
|
}
|
|
456
|
+
/** Bounded local queue. Cursor is the stable (created_at, finding_id, revision) tuple. */
|
|
457
|
+
reviews(options = {}) {
|
|
458
|
+
const limit = options.limit ?? 100;
|
|
459
|
+
if (!Number.isSafeInteger(limit) ||
|
|
460
|
+
limit < 1 ||
|
|
461
|
+
limit > 1000 ||
|
|
462
|
+
(options.includeResolved !== undefined && typeof options.includeResolved !== 'boolean'))
|
|
463
|
+
throw new Error('Invalid review list options');
|
|
464
|
+
const after = options.after;
|
|
465
|
+
if (after &&
|
|
466
|
+
(!Number.isSafeInteger(after.created_at) ||
|
|
467
|
+
!Number.isSafeInteger(after.revision) ||
|
|
468
|
+
after.revision < 1 ||
|
|
469
|
+
typeof after.finding_id !== 'string' ||
|
|
470
|
+
!after.finding_id.length))
|
|
471
|
+
throw new Error('Invalid review cursor');
|
|
472
|
+
return this.#db
|
|
473
|
+
.prepare(`SELECT r.*,h.payload FROM ai_reviews r JOIN finding_revisions h
|
|
474
|
+
ON h.finding_id=r.finding_id AND h.revision=r.revision
|
|
475
|
+
WHERE ${options.includeResolved ? '1' : "r.status IN ('pending','investigate')"}
|
|
476
|
+
${after ? 'AND (r.created_at,r.finding_id,r.revision) > (?,?,?)' : ''}
|
|
477
|
+
ORDER BY r.created_at,r.finding_id,r.revision LIMIT ?`)
|
|
478
|
+
.all(...(after ? [after.created_at, after.finding_id, after.revision] : []), limit)
|
|
479
|
+
.map((row) => ({
|
|
480
|
+
finding_id: String(row.finding_id),
|
|
481
|
+
revision: Number(row.revision),
|
|
482
|
+
reason: row.reason,
|
|
483
|
+
status: row.status,
|
|
484
|
+
created_at: Number(row.created_at),
|
|
485
|
+
reviewed_at: row.reviewed_at === null ? null : Number(row.reviewed_at),
|
|
486
|
+
reviewer: row.reviewer === null ? null : String(row.reviewer),
|
|
487
|
+
note: row.note === null ? null : String(row.note),
|
|
488
|
+
evidence: JSON.parse(String(row.evidence_refs)),
|
|
489
|
+
assessment: JSON.parse(String(row.payload)),
|
|
490
|
+
}));
|
|
491
|
+
}
|
|
492
|
+
reviewSummary(now = Date.now()) {
|
|
493
|
+
if (!Number.isSafeInteger(now) || now < 0)
|
|
494
|
+
throw new Error('Invalid review timestamp');
|
|
495
|
+
const row = this.#db
|
|
496
|
+
.prepare(`SELECT SUM(status='pending') AS pending,SUM(status='investigate') AS investigate,
|
|
497
|
+
MIN(created_at) AS oldest FROM ai_reviews WHERE status IN ('pending','investigate')`)
|
|
498
|
+
.get();
|
|
499
|
+
const oldest = row.oldest == null ? null : Number(row.oldest);
|
|
500
|
+
return {
|
|
501
|
+
pending: Number(row.pending ?? 0),
|
|
502
|
+
investigate: Number(row.investigate ?? 0),
|
|
503
|
+
oldest_open_at: oldest,
|
|
504
|
+
oldest_open_age_ms: oldest === null ? null : Math.max(0, now - oldest),
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
/** OS/private database access authenticates this local operation; reviewer is a declared label. */
|
|
508
|
+
reviewFinding(id, revision, decision, now = Date.now()) {
|
|
509
|
+
const text = (value, max) => typeof value === 'string' &&
|
|
510
|
+
value.trim().length > 0 &&
|
|
511
|
+
value.length <= max &&
|
|
512
|
+
!/[\u0000-\u001f\u007f]/u.test(value);
|
|
513
|
+
if (!text(id, 500) ||
|
|
514
|
+
!Number.isSafeInteger(revision) ||
|
|
515
|
+
revision < 1 ||
|
|
516
|
+
!Number.isSafeInteger(now) ||
|
|
517
|
+
now < 0 ||
|
|
518
|
+
!decision ||
|
|
519
|
+
!['dismiss', 'investigate'].includes(decision.disposition) ||
|
|
520
|
+
!text(decision.reviewer, 200) ||
|
|
521
|
+
!text(decision.reason, 2000))
|
|
522
|
+
throw new Error('Review requires a current revision, disposition, reviewer and bounded reason');
|
|
523
|
+
this.#transaction(() => {
|
|
524
|
+
const row = this.#db
|
|
525
|
+
.prepare(`SELECT r.status,r.evidence_refs,f.revision AS current_revision,f.payload FROM ai_reviews r
|
|
526
|
+
JOIN findings f ON f.id=r.finding_id WHERE r.finding_id=? AND r.revision=?`)
|
|
527
|
+
.get(id, revision);
|
|
528
|
+
if (!row ||
|
|
529
|
+
row.current_revision !== revision ||
|
|
530
|
+
!['pending', 'investigate'].includes(String(row.status)))
|
|
531
|
+
throw new Error('Review is stale or already resolved; read the current review queue');
|
|
532
|
+
const finding = JSON.parse(String(row.payload));
|
|
533
|
+
if (finding.active === false || finding.withdrawn || finding.applicability === 'not_affected')
|
|
534
|
+
throw new Error('Review is no longer current');
|
|
535
|
+
const currentEvidence = this.#db
|
|
536
|
+
.prepare('SELECT source,id,content_hash FROM evidence WHERE id IN (SELECT value FROM json_each(?)) ORDER BY source,id')
|
|
537
|
+
.all(JSON.stringify(finding.evidence_ids))
|
|
538
|
+
.map((item) => ({
|
|
539
|
+
source: String(item.source),
|
|
540
|
+
id: String(item.id),
|
|
541
|
+
content_hash: String(item.content_hash),
|
|
542
|
+
}));
|
|
543
|
+
if (hash(currentEvidence) !== hash(JSON.parse(String(row.evidence_refs))))
|
|
544
|
+
throw new Error('Review evidence is stale; wait for reassessment and read the current review queue');
|
|
545
|
+
this.#db
|
|
546
|
+
.prepare('UPDATE ai_reviews SET status=?,reviewed_at=?,reviewer=?,note=? WHERE finding_id=? AND revision=?')
|
|
547
|
+
.run(decision.disposition === 'dismiss' ? 'dismissed' : 'investigate', now, decision.reviewer.trim(), decision.reason.trim(), id, revision);
|
|
548
|
+
if (decision.disposition === 'dismiss') {
|
|
549
|
+
this.#db
|
|
550
|
+
.prepare('UPDATE findings SET acknowledged_revision=? WHERE id=? AND revision=?')
|
|
551
|
+
.run(revision, id, revision);
|
|
552
|
+
this.#db
|
|
553
|
+
.prepare("UPDATE notifications SET status='failed',last_error='Finding acknowledged before delivery' WHERE finding_id=? AND revision=? AND status='pending'")
|
|
554
|
+
.run(id, revision);
|
|
555
|
+
}
|
|
556
|
+
});
|
|
557
|
+
}
|
|
313
558
|
findings() {
|
|
314
559
|
return this.#db
|
|
315
560
|
.prepare('SELECT payload FROM findings ORDER BY id')
|
|
@@ -400,6 +645,7 @@ export class Store {
|
|
|
400
645
|
jobs() {
|
|
401
646
|
return this.#db.prepare('SELECT * FROM notifications ORDER BY available_at,id').all().map(notification);
|
|
402
647
|
}
|
|
648
|
+
/** @internal Used by the scan and delivery workers; not part of the public API. */
|
|
403
649
|
claimDue(now = Date.now(), excludedChannels = []) {
|
|
404
650
|
return this.#transaction(() => {
|
|
405
651
|
const row = this.#db
|
|
@@ -418,6 +664,7 @@ export class Store {
|
|
|
418
664
|
return { ...notification(row), status: 'sending', attempts: Number(row.attempts) + 1 };
|
|
419
665
|
});
|
|
420
666
|
}
|
|
667
|
+
/** @internal Used by the scan and delivery workers; not part of the public API. */
|
|
421
668
|
claimAdditionalDigest(channel, now = Date.now(), limit = 4) {
|
|
422
669
|
if (!Number.isSafeInteger(limit) || limit < 0 || limit > 4)
|
|
423
670
|
throw new Error('Digest batch limit must be 0–4 additional findings');
|
|
@@ -441,13 +688,33 @@ export class Store {
|
|
|
441
688
|
}));
|
|
442
689
|
});
|
|
443
690
|
}
|
|
444
|
-
|
|
691
|
+
/** @internal Used by the scan and delivery workers; not part of the public API. */
|
|
692
|
+
completeJob(id, status, nextAt, error, acceptedAt) {
|
|
693
|
+
if (acceptedAt !== undefined &&
|
|
694
|
+
(status !== 'accepted' ||
|
|
695
|
+
!Number.isSafeInteger(acceptedAt) ||
|
|
696
|
+
acceptedAt <= 0 ||
|
|
697
|
+
acceptedAt > 8_640_000_000_000_000))
|
|
698
|
+
throw new Error('Invalid notification acceptance time');
|
|
445
699
|
const changed = this.#db
|
|
446
|
-
.prepare("UPDATE notifications SET status=?,available_at=?,last_error=? WHERE id=? AND status='sending'")
|
|
447
|
-
.run(status, nextAt, error ?? null, id);
|
|
700
|
+
.prepare("UPDATE notifications SET status=?,available_at=?,last_error=?,accepted_at=? WHERE id=? AND status='sending'")
|
|
701
|
+
.run(status, nextAt, error ?? null, acceptedAt ?? null, id);
|
|
448
702
|
if (Number(changed.changes) !== 1)
|
|
449
703
|
throw new Error('Notification is not in flight');
|
|
450
704
|
}
|
|
705
|
+
/**
|
|
706
|
+
* Persist one destination response for the whole claimed digest, including the shared receipt time.
|
|
707
|
+
* @internal Used by the scan and delivery workers; not part of the public API.
|
|
708
|
+
*/
|
|
709
|
+
completeBatch(ids, status, nextAt, error, acceptedAt) {
|
|
710
|
+
if (ids.length < 1 || ids.length > 5)
|
|
711
|
+
throw new Error('Invalid notification batch size');
|
|
712
|
+
this.#transaction(() => {
|
|
713
|
+
for (const id of ids)
|
|
714
|
+
this.completeJob(id, status, nextAt, error, acceptedAt);
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
/** @internal Used by the scan and delivery workers; not part of the public API. */
|
|
451
718
|
deferJob(id, nextAt, reason = 'Waiting for destination rate limit') {
|
|
452
719
|
const changed = this.#db
|
|
453
720
|
.prepare("UPDATE notifications SET status='pending',available_at=?,attempts=MAX(0,attempts-1),last_error=? WHERE id=? AND status='sending'")
|
|
@@ -472,18 +739,42 @@ export class Store {
|
|
|
472
739
|
.run(now, id);
|
|
473
740
|
});
|
|
474
741
|
}
|
|
742
|
+
/** @internal Used by the scan and delivery workers; not part of the public API. */
|
|
475
743
|
recoverSending(now = Date.now()) {
|
|
476
744
|
this.#db
|
|
477
745
|
.prepare("UPDATE notifications SET status='unknown',available_at=?,last_error='Delivery interrupted; receipt is unknown. Check the destination before retrying.' WHERE status='sending'")
|
|
478
746
|
.run(now);
|
|
479
747
|
}
|
|
480
|
-
|
|
748
|
+
/** The current revision number of a finding, or undefined when it does not exist. */
|
|
749
|
+
revisionOf(id) {
|
|
750
|
+
const row = this.#db.prepare('SELECT revision FROM findings WHERE id=?').get(id);
|
|
751
|
+
return row ? Number(row.revision) : undefined;
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* A send whose result could not be recorded may have reached its destination: never resend it unasked.
|
|
755
|
+
* @internal Used by the scan and delivery workers; not part of the public API.
|
|
756
|
+
*/
|
|
757
|
+
markUncertain(ids, error) {
|
|
481
758
|
this.#transaction(() => {
|
|
482
|
-
|
|
759
|
+
for (const id of ids)
|
|
760
|
+
this.#db
|
|
761
|
+
.prepare("UPDATE notifications SET status='unknown',last_error=? WHERE id=? AND status IN ('pending','sending')")
|
|
762
|
+
.run(error, id);
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
/** Acknowledge the current revision. Pass the revision that was read to refuse a newer, unseen one. */
|
|
766
|
+
acknowledge(id, revision) {
|
|
767
|
+
return this.#transaction(() => {
|
|
768
|
+
const current = this.revisionOf(id);
|
|
769
|
+
if (current === undefined)
|
|
483
770
|
throw new Error('Finding not found');
|
|
771
|
+
if (revision !== undefined && revision !== current)
|
|
772
|
+
throw new Error(`Finding is now at revision ${current}, not ${revision}; read the current revision before acknowledging it`);
|
|
773
|
+
this.#db.prepare('UPDATE findings SET acknowledged_revision=revision WHERE id=?').run(id);
|
|
484
774
|
this.#db
|
|
485
775
|
.prepare("UPDATE notifications SET status='failed',last_error='Finding acknowledged before delivery' WHERE finding_id=? AND status='pending'")
|
|
486
776
|
.run(id);
|
|
777
|
+
return current;
|
|
487
778
|
});
|
|
488
779
|
}
|
|
489
780
|
suppress(id, until, reason) {
|
|
@@ -499,9 +790,11 @@ export class Store {
|
|
|
499
790
|
.run(until, id);
|
|
500
791
|
});
|
|
501
792
|
}
|
|
793
|
+
/** @internal Used by the scan and delivery workers; not part of the public API. */
|
|
502
794
|
getMeta(key) {
|
|
503
795
|
return this.#db.prepare('SELECT value FROM metadata WHERE key=?').get(key)?.value;
|
|
504
796
|
}
|
|
797
|
+
/** @internal Used by the scan and delivery workers; not part of the public API. */
|
|
505
798
|
setMeta(key, value, now = Date.now()) {
|
|
506
799
|
if (!Number.isSafeInteger(now) || now < 0)
|
|
507
800
|
throw new Error('Invalid metadata timestamp');
|
|
@@ -539,7 +832,7 @@ export class Store {
|
|
|
539
832
|
};
|
|
540
833
|
// Inactive means absent from the current assessment, not remediated. Uncertain or affected
|
|
541
834
|
// findings stay protected until authoritative exclusion, withdrawal, or confirmed general news.
|
|
542
|
-
const resolved = `COALESCE((json_type(f.payload,'$.active')='false' AND (
|
|
835
|
+
const resolved = `COALESCE((NOT EXISTS (SELECT 1 FROM ai_reviews review WHERE review.finding_id=f.id) AND json_type(f.payload,'$.active')='false' AND (
|
|
543
836
|
json_extract(f.payload,'$.applicability')='not_affected' OR json_type(f.payload,'$.withdrawn')='true' OR
|
|
544
837
|
(json_extract(f.payload,'$.ai.status')='complete' AND json_extract(f.payload,'$.news_analysis.classification')='general_news' AND json_extract(f.payload,'$.news_analysis.impact')='not_applicable')
|
|
545
838
|
) AND NOT EXISTS (SELECT 1 FROM notifications pending WHERE pending.finding_id=f.id AND pending.status<>'accepted')),0)`;
|
|
@@ -549,8 +842,9 @@ export class Store {
|
|
|
549
842
|
this.#db.exec(apply ? 'BEGIN IMMEDIATE' : 'BEGIN');
|
|
550
843
|
try {
|
|
551
844
|
take('metadata', `SELECT rowid FROM metadata WHERE key GLOB 'analysis:*' AND updated_at < ${cutoff(limits.analysis_cache_days)} ORDER BY updated_at,rowid`, [], 'analysis_cache');
|
|
845
|
+
const receiptTime = 'COALESCE(n.accepted_at,n.available_at)';
|
|
552
846
|
const accepted = take('notifications', `SELECT n.rowid FROM notifications n JOIN findings f ON f.id=n.finding_id WHERE n.status='accepted' AND (${resolved}) AND
|
|
553
|
-
(
|
|
847
|
+
(${receiptTime} < ${cutoff(limits.accepted_delivery_days)} OR ((${inactive}) AND ${receiptTime} < ${cutoff(limits.inactive_findings_days)})) ORDER BY ${receiptTime},n.rowid`, [], 'accepted_deliveries');
|
|
554
848
|
const revisions = take('finding_revisions', `SELECT r.rowid FROM finding_revisions r JOIN findings f ON f.id=r.finding_id WHERE (${resolved}) AND
|
|
555
849
|
(r.recorded_at < ${cutoff(limits.finding_history_days)} OR ((${inactive}) AND r.recorded_at < ${cutoff(limits.inactive_findings_days)})) AND
|
|
556
850
|
NOT EXISTS(SELECT 1 FROM notifications n WHERE n.finding_id=r.finding_id AND n.revision=r.revision AND n.rowid NOT IN(SELECT value FROM json_each(?))) ORDER BY r.recorded_at,r.rowid`, [JSON.stringify(accepted)], 'finding_history');
|
|
@@ -589,6 +883,7 @@ export class Store {
|
|
|
589
883
|
throw error;
|
|
590
884
|
}
|
|
591
885
|
}
|
|
886
|
+
/** @internal Used by the scan and delivery workers; not part of the public API. */
|
|
592
887
|
reserveBudget(day, maxRequests, maxTokens, maxUsd, tokens, usd) {
|
|
593
888
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(day) ||
|
|
594
889
|
![maxRequests, maxTokens, tokens].every((n) => Number.isSafeInteger(n) && n >= 0) ||
|
|
@@ -631,7 +926,11 @@ export class Store {
|
|
|
631
926
|
};
|
|
632
927
|
});
|
|
633
928
|
}
|
|
634
|
-
|
|
929
|
+
/**
|
|
930
|
+
* Write a snapshot and publish it at `path`. When `verify` is given it checks the snapshot first,
|
|
931
|
+
* and a snapshot that fails is removed instead of being left at the destination.
|
|
932
|
+
*/
|
|
933
|
+
async backup(path, verify) {
|
|
635
934
|
const destination = resolve(path);
|
|
636
935
|
if (existsSync(destination))
|
|
637
936
|
throw new Error('Backup destination already exists');
|
|
@@ -641,6 +940,8 @@ export class Store {
|
|
|
641
940
|
try {
|
|
642
941
|
privateFile(snapshot);
|
|
643
942
|
await sqliteBackup(this.#db, snapshot);
|
|
943
|
+
if (verify)
|
|
944
|
+
await verify(snapshot);
|
|
644
945
|
// Publish a complete snapshot atomically, and never overwrite a file that appeared during backup.
|
|
645
946
|
linkSync(snapshot, destination);
|
|
646
947
|
}
|
|
@@ -649,3 +950,4 @@ export class Store {
|
|
|
649
950
|
}
|
|
650
951
|
}
|
|
651
952
|
}
|
|
953
|
+
export const readPilotReport = Store.readPilotReport;
|