@akasecurity/ai-tc-claude-code 0.9.10 → 0.9.12
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/.claude-plugin/plugin.json +1 -1
- package/commands/scan.md +1 -1
- package/commands/setup.md +31 -3
- package/package.json +4 -4
- package/scripts/apply-suppressions.js +1761 -947
- package/scripts/backfill.js +2097 -1184
- package/scripts/content-retention.js +33995 -0
- package/scripts/filescan.js +2149 -1102
- package/scripts/firstrun.js +1989 -1063
- package/scripts/history-sync.js +1943 -1037
- package/scripts/intro.js +530 -120
- package/scripts/message-display.js +1744 -930
- package/scripts/onboard.js +1748 -925
- package/scripts/post-model-switch.js +560 -144
- package/scripts/post-tool-use.js +2119 -1047
- package/scripts/pre-model-switch.js +2035 -1142
- package/scripts/pre-tool-use.js +2101 -1180
- package/scripts/query.js +2066 -1075
- package/scripts/reconcile.js +2058 -1165
- package/scripts/remediate.js +2091 -1176
- package/scripts/scan-worker.js +388 -74
- package/scripts/session-start.js +2025 -1108
- package/scripts/start-light.js +528 -118
- package/scripts/statusline.js +2031 -1138
- package/scripts/stop.js +791 -154
- package/scripts/sync.js +2144 -1099
- package/scripts/user-prompt-submit.js +2089 -1174
|
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
|
|
|
50
50
|
var REGEX_SPLITALL_CRLF = /\r?\n/g;
|
|
51
51
|
var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
|
|
52
52
|
var REGEX_TEST_TRAILING_SLASH = /\/$/;
|
|
53
|
-
var
|
|
53
|
+
var SLASH2 = "/";
|
|
54
54
|
var TMP_KEY_IGNORE = "node-ignore";
|
|
55
55
|
if (typeof Symbol !== "undefined") {
|
|
56
56
|
TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
|
|
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
|
|
|
422
422
|
if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
|
|
423
423
|
return this.test(path);
|
|
424
424
|
}
|
|
425
|
-
const slices = path.split(
|
|
425
|
+
const slices = path.split(SLASH2).filter(Boolean);
|
|
426
426
|
slices.pop();
|
|
427
427
|
if (slices.length) {
|
|
428
428
|
const parent = this._t(
|
|
429
|
-
slices.join(
|
|
429
|
+
slices.join(SLASH2) + SLASH2,
|
|
430
430
|
this._testCache,
|
|
431
431
|
true,
|
|
432
432
|
slices
|
|
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
|
|
|
442
442
|
return cache[path];
|
|
443
443
|
}
|
|
444
444
|
if (!slices) {
|
|
445
|
-
slices = path.split(
|
|
445
|
+
slices = path.split(SLASH2).filter(Boolean);
|
|
446
446
|
}
|
|
447
447
|
slices.pop();
|
|
448
448
|
if (!slices.length) {
|
|
449
449
|
return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
|
|
450
450
|
}
|
|
451
451
|
const parent = this._t(
|
|
452
|
-
slices.join(
|
|
452
|
+
slices.join(SLASH2) + SLASH2,
|
|
453
453
|
cache,
|
|
454
454
|
checkUnignored,
|
|
455
455
|
slices
|
|
@@ -492,9 +492,9 @@ var require_ignore = __commonJS({
|
|
|
492
492
|
});
|
|
493
493
|
|
|
494
494
|
// src/apply-suppressions.ts
|
|
495
|
-
import { existsSync as
|
|
495
|
+
import { existsSync as existsSync12, readFileSync as readFileSync18 } from "fs";
|
|
496
496
|
import { userInfo } from "os";
|
|
497
|
-
import { dirname as dirname8, join as
|
|
497
|
+
import { dirname as dirname8, join as join28 } from "path";
|
|
498
498
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
499
499
|
|
|
500
500
|
// ../../packages/persistence/src/attached-derived.ts
|
|
@@ -506,6 +506,14 @@ var POLICY_CACHE_FILENAME = "policy-cache.json";
|
|
|
506
506
|
import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
|
|
507
507
|
import { join as join2 } from "path";
|
|
508
508
|
|
|
509
|
+
// ../../packages/schema/src/drizzle/deferred-migrations.ts
|
|
510
|
+
var DEFERRED_MIGRATION_TAGS = [
|
|
511
|
+
"0031_audit_capture_by_time_index",
|
|
512
|
+
"0032_audit_capture_by_id_index",
|
|
513
|
+
"0033_audit_capture_location_index",
|
|
514
|
+
"0034_findings_read_indexes"
|
|
515
|
+
];
|
|
516
|
+
|
|
509
517
|
// ../../packages/schema/src/drizzle/sqlite-ddl.ts
|
|
510
518
|
var SQLITE_MIGRATIONS = [
|
|
511
519
|
{
|
|
@@ -623,6 +631,30 @@ var SQLITE_MIGRATIONS = [
|
|
|
623
631
|
{
|
|
624
632
|
tag: "0028_activity_session_probe_indexes",
|
|
625
633
|
sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"
|
|
634
|
+
},
|
|
635
|
+
{
|
|
636
|
+
tag: "0029_audit_capture_rollup_index",
|
|
637
|
+
sql: "CREATE INDEX `idx_audit_capture_rollup` ON `audit_events` (`event_type`,`started_at`,`repo`,`id`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
|
|
638
|
+
},
|
|
639
|
+
{
|
|
640
|
+
tag: "0030_audit_content_expiry",
|
|
641
|
+
sql: "ALTER TABLE `audit_events` ADD `content_expired_at` integer;--> statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"
|
|
642
|
+
},
|
|
643
|
+
{
|
|
644
|
+
tag: "0031_audit_capture_by_time_index",
|
|
645
|
+
sql: "CREATE INDEX `idx_audit_capture_by_time` ON `audit_events` (`started_at`,`id`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
|
|
646
|
+
},
|
|
647
|
+
{
|
|
648
|
+
tag: "0032_audit_capture_by_id_index",
|
|
649
|
+
sql: "CREATE INDEX `idx_audit_capture_by_id` ON `audit_events` (`id`,`started_at`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
|
|
650
|
+
},
|
|
651
|
+
{
|
|
652
|
+
tag: "0033_audit_capture_location_index",
|
|
653
|
+
sql: "CREATE INDEX `idx_audit_capture_location` ON `audit_events` (`repo`,`file_path`,`started_at`,`id`,`event_type`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
|
|
654
|
+
},
|
|
655
|
+
{
|
|
656
|
+
tag: "0034_findings_read_indexes",
|
|
657
|
+
sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
|
|
626
658
|
}
|
|
627
659
|
];
|
|
628
660
|
|
|
@@ -20670,6 +20702,15 @@ var FindingCategory = external_exports.enum([
|
|
|
20670
20702
|
]).meta({ id: "FindingCategory" });
|
|
20671
20703
|
var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
|
|
20672
20704
|
var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
|
|
20705
|
+
var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
|
|
20706
|
+
var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
|
|
20707
|
+
var FindingDelivery = external_exports.object({
|
|
20708
|
+
state: FindingDeliveryState,
|
|
20709
|
+
// The delivery time for `sent`; the failure time for `not_sent` when recorded.
|
|
20710
|
+
at: external_exports.iso.datetime().optional(),
|
|
20711
|
+
// Only on `not_sent`, and only when a known reason was recorded.
|
|
20712
|
+
reason: SyncFailureReason.optional()
|
|
20713
|
+
}).meta({ id: "FindingDelivery" });
|
|
20673
20714
|
var ResolutionMethod = external_exports.enum([
|
|
20674
20715
|
"enforced-in-flight",
|
|
20675
20716
|
"fixed-at-source",
|
|
@@ -20726,7 +20767,10 @@ var FindingInstance = external_exports.object({
|
|
|
20726
20767
|
// The session that event belongs to, when it has one — the seam a
|
|
20727
20768
|
// per-instance "view session" link needs. Absent for events captured
|
|
20728
20769
|
// outside a session.
|
|
20729
|
-
sessionId: external_exports.string().optional()
|
|
20770
|
+
sessionId: external_exports.string().optional(),
|
|
20771
|
+
// The delivery state of the event above (see FindingDelivery). Optional so
|
|
20772
|
+
// readers that do not project it stay valid.
|
|
20773
|
+
delivery: FindingDelivery.optional()
|
|
20730
20774
|
}).meta({ id: "FindingInstance" });
|
|
20731
20775
|
var FindingGroup = external_exports.object({
|
|
20732
20776
|
id: external_exports.string(),
|
|
@@ -20743,13 +20787,11 @@ var FindingGroup = external_exports.object({
|
|
|
20743
20787
|
latestDetectedAt: external_exports.iso.datetime(),
|
|
20744
20788
|
instances: external_exports.array(FindingInstance),
|
|
20745
20789
|
// Derived from instances' statuses with open-dominates precedence (see
|
|
20746
|
-
//
|
|
20790
|
+
// foldGroupStatus). Undefined only when no instance carries a status.
|
|
20747
20791
|
status: FindingStatus.optional(),
|
|
20748
|
-
// The distinct people across the WHOLE group, not just the
|
|
20749
|
-
//
|
|
20750
|
-
//
|
|
20751
|
-
// instance carries a user, or when the store supplied whole-group folds
|
|
20752
|
-
// without one.
|
|
20792
|
+
// The distinct people across the WHOLE group, not just the instances
|
|
20793
|
+
// carried here. Undefined when no instance carries a user, or when the
|
|
20794
|
+
// store supplied whole-group folds without one.
|
|
20753
20795
|
users: external_exports.array(FindingUser).optional()
|
|
20754
20796
|
}).meta({ id: "FindingGroup" });
|
|
20755
20797
|
var FindingStats = external_exports.object({
|
|
@@ -20778,21 +20820,34 @@ var FindingFacets = external_exports.object({
|
|
|
20778
20820
|
// counted under no value.
|
|
20779
20821
|
status: external_exports.array(FindingFacetItem),
|
|
20780
20822
|
// Host tool (attributes.tool_name). Present only on the instance-level
|
|
20781
|
-
// reads, which can filter by it; the
|
|
20823
|
+
// reads, which can filter by it; the type-level read omits the dimension
|
|
20782
20824
|
// because a group spans tools.
|
|
20783
|
-
tool: external_exports.array(FindingFacetItem).optional()
|
|
20825
|
+
tool: external_exports.array(FindingFacetItem).optional(),
|
|
20826
|
+
// Delivery states (FindingDeliveryState). Present only on the
|
|
20827
|
+
// instance-level reads, like `tool`.
|
|
20828
|
+
deployment: external_exports.array(FindingFacetItem).optional()
|
|
20784
20829
|
}).meta({ id: "FindingFacets" });
|
|
20785
|
-
var
|
|
20786
|
-
|
|
20830
|
+
var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
|
|
20831
|
+
id: "FindingTypeSummary"
|
|
20832
|
+
});
|
|
20833
|
+
var DEFAULT_FINDING_TYPES_LIMIT = 50;
|
|
20834
|
+
var MAX_FINDING_TYPES_LIMIT = 100;
|
|
20835
|
+
var ListFindingTypesQuery = external_exports.object({
|
|
20787
20836
|
// NOTE: severity filters by Severity (critical/high/medium/low), not by
|
|
20788
|
-
// FindingAction.
|
|
20837
|
+
// FindingAction. It narrows TYPES: a type's severity is the one its newest
|
|
20838
|
+
// firing version carries, and this list pages types.
|
|
20839
|
+
//
|
|
20840
|
+
// That is NOT a claim the findings of a type share it. A rule can hold several
|
|
20841
|
+
// definition versions at different severities, so a type kept by this filter
|
|
20842
|
+
// can hold findings that individually do not match — see totals.findings on
|
|
20843
|
+
// ListFindingTypesResponse, which counts them all.
|
|
20789
20844
|
severity: external_exports.array(Severity).optional(),
|
|
20790
20845
|
subtype: external_exports.array(external_exports.string()).optional(),
|
|
20791
20846
|
provider: external_exports.array(FindingProvider).optional(),
|
|
20792
20847
|
action: external_exports.array(FindingAction).optional(),
|
|
20793
|
-
// Matches a
|
|
20794
|
-
// individual
|
|
20795
|
-
//
|
|
20848
|
+
// Matches a type's DERIVED status (see FindingGroup.status), not its
|
|
20849
|
+
// individual findings' — so a filtered row's status always reads one of the
|
|
20850
|
+
// requested values.
|
|
20796
20851
|
status: external_exports.array(FindingStatus).optional(),
|
|
20797
20852
|
q: external_exports.string().optional(),
|
|
20798
20853
|
// Scope to findings whose event carries this session id (the Activity page's
|
|
@@ -20802,23 +20857,37 @@ var ListGroupedFindingsQuery = external_exports.object({
|
|
|
20802
20857
|
// from a time-scoped page (Activity's range) can carry that scope. Absent
|
|
20803
20858
|
// means all time — this list has no default window.
|
|
20804
20859
|
from: external_exports.iso.datetime().optional(),
|
|
20805
|
-
// A
|
|
20806
|
-
//
|
|
20807
|
-
//
|
|
20808
|
-
//
|
|
20809
|
-
//
|
|
20860
|
+
// A RULE id that must appear in the page even when the cursor has already
|
|
20861
|
+
// advanced past its sort position. This is what keeps the selected type
|
|
20862
|
+
// visible in the list once it paginates: the target is appended out of sort
|
|
20863
|
+
// order rather than scanned forward for. Never affects totals, facets or the
|
|
20864
|
+
// cursor. Unlike the grouped read this replaces, it names a rule only — an
|
|
20865
|
+
// instance id is resolved by `findingInstance`, which is a primary-key seek
|
|
20866
|
+
// and so is not bounded by what any page happens to hold.
|
|
20810
20867
|
includeId: external_exports.string().optional(),
|
|
20811
|
-
|
|
20812
|
-
limit: external_exports.coerce.number().int().min(1).max(100).optional(),
|
|
20868
|
+
limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
|
|
20813
20869
|
cursor: external_exports.string().optional()
|
|
20814
20870
|
});
|
|
20815
|
-
var
|
|
20871
|
+
var ListFindingTypesResponse = external_exports.object({
|
|
20816
20872
|
totals: external_exports.object({
|
|
20873
|
+
// Findings belonging to the matching TYPES — not findings that each match
|
|
20874
|
+
// the filters. The filters here select types, so a type that survives
|
|
20875
|
+
// contributes its whole instanceCount.
|
|
20876
|
+
//
|
|
20877
|
+
// `status` is the one exception, narrowed per finding via
|
|
20878
|
+
// countInstancesByStatus. `severity`, `provider` and `action` are not, so
|
|
20879
|
+
// this can exceed what the instance read reports for the same filters: a
|
|
20880
|
+
// rule whose severity moved between versions is kept on its newest and
|
|
20881
|
+
// still counts its older findings. Narrowing the other three needs
|
|
20882
|
+
// per-dimension counts the aggregate does not carry today.
|
|
20817
20883
|
findings: external_exports.number().int().nonnegative(),
|
|
20818
|
-
|
|
20884
|
+
// Counts TYPES, which is the unit this read pages. The instance read's
|
|
20885
|
+
// own totals count findings; the two deliberately answer different
|
|
20886
|
+
// questions and are never summed.
|
|
20887
|
+
types: external_exports.number().int().nonnegative()
|
|
20819
20888
|
}),
|
|
20820
20889
|
facets: FindingFacets,
|
|
20821
|
-
items: external_exports.array(
|
|
20890
|
+
items: external_exports.array(FindingTypeSummary),
|
|
20822
20891
|
nextCursor: external_exports.string().nullable(),
|
|
20823
20892
|
// Present only on session-scoped queries (`sessionId` set): per ruleId, how
|
|
20824
20893
|
// many times that rule fired in the session's persisted transcript. Findings
|
|
@@ -20826,7 +20895,7 @@ var ListGroupedFindingsResponse = external_exports.object({
|
|
|
20826
20895
|
// every firing, so the two numbers legitimately differ — this map lets a
|
|
20827
20896
|
// session-scoped view show both.
|
|
20828
20897
|
sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
|
|
20829
|
-
}).meta({ id: "
|
|
20898
|
+
}).meta({ id: "ListFindingTypesResponse" });
|
|
20830
20899
|
var ApplyFindingActionRequest = external_exports.object({
|
|
20831
20900
|
// 'quarantined' is system-assigned (see FindingAction) — clients may not set
|
|
20832
20901
|
// it, so it is excluded from the request contract. The mapping helper
|
|
@@ -20856,16 +20925,19 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
|
|
|
20856
20925
|
var MAX_FLAT_FINDINGS_LIMIT = 200;
|
|
20857
20926
|
var ListFindingInstancesQuery = external_exports.object({
|
|
20858
20927
|
severity: external_exports.array(Severity).optional(),
|
|
20859
|
-
// Rule ids, the same vocabulary the
|
|
20928
|
+
// Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
|
|
20929
|
+
// ONE of them is how the master/detail view scopes its right-hand panel.
|
|
20860
20930
|
subtype: external_exports.array(external_exports.string()).optional(),
|
|
20861
20931
|
provider: external_exports.array(FindingProvider).optional(),
|
|
20862
20932
|
action: external_exports.array(FindingAction).optional(),
|
|
20863
20933
|
// Matches each instance's OWN derived status (deriveFindingStatus), unlike
|
|
20864
|
-
// the
|
|
20934
|
+
// the types query's type-level fold.
|
|
20865
20935
|
status: external_exports.array(FindingStatus).optional(),
|
|
20866
20936
|
// Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
|
|
20867
20937
|
// where the free-text `q` can only match the rendered "via Bash" label.
|
|
20868
20938
|
tool: external_exports.array(external_exports.string()).optional(),
|
|
20939
|
+
// The delivery state of each finding's event (see FindingDelivery).
|
|
20940
|
+
deployment: external_exports.array(FindingDeliveryState).optional(),
|
|
20869
20941
|
// Exact repository / file-path matches, for the drill-down out of the
|
|
20870
20942
|
// locations view. A row whose event carries no repo/file matches neither.
|
|
20871
20943
|
repo: external_exports.string().optional(),
|
|
@@ -20878,37 +20950,51 @@ var ListFindingInstancesQuery = external_exports.object({
|
|
|
20878
20950
|
});
|
|
20879
20951
|
var ListFindingInstancesResponse = external_exports.object({
|
|
20880
20952
|
// Instances matching the filters across the whole scope, not just this
|
|
20881
|
-
// page — cursor-independent, like the
|
|
20953
|
+
// page — cursor-independent, like the types list's totals.
|
|
20882
20954
|
totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
|
|
20883
|
-
// Counts in INSTANCES here, where the
|
|
20955
|
+
// Counts in INSTANCES here, where the types response counts types. Each
|
|
20884
20956
|
// dimension still excludes its own filter.
|
|
20885
20957
|
facets: FindingFacets,
|
|
20886
20958
|
items: external_exports.array(FindingInstanceDetail),
|
|
20887
20959
|
nextCursor: external_exports.string().nullable()
|
|
20888
20960
|
}).meta({ id: "ListFindingInstancesResponse" });
|
|
20889
|
-
var
|
|
20890
|
-
|
|
20891
|
-
|
|
20892
|
-
|
|
20893
|
-
|
|
20894
|
-
|
|
20895
|
-
|
|
20896
|
-
//
|
|
20897
|
-
//
|
|
20898
|
-
|
|
20899
|
-
|
|
20900
|
-
// chips, and the count is what conveys scale.
|
|
20901
|
-
ruleIds: external_exports.array(external_exports.string())
|
|
20902
|
-
}).meta({ id: "FindingLocationFile" });
|
|
20903
|
-
var FindingLocationRepo = external_exports.object({
|
|
20961
|
+
var ListFindingInstancesPage = external_exports.object({
|
|
20962
|
+
items: external_exports.array(FindingInstanceDetail),
|
|
20963
|
+
nextCursor: external_exports.string().nullable()
|
|
20964
|
+
}).meta({ id: "ListFindingInstancesPage" });
|
|
20965
|
+
var FindingLocationSummary = external_exports.object({
|
|
20966
|
+
// Opaque, stable, minted from the pair by encodeLocationId. It exists
|
|
20967
|
+
// because a location's identity is two values and a URL param carries one:
|
|
20968
|
+
// `?loc=` names a location the way `?rule=` names a type. Only ever compared
|
|
20969
|
+
// for EQUALITY — the page's selection check, this read's `includeId`, the
|
|
20970
|
+
// client's page dedupe — never decoded, and never a sort key.
|
|
20971
|
+
id: external_exports.string(),
|
|
20904
20972
|
/** Empty when the instances carried no repo attribute. */
|
|
20905
20973
|
repo: external_exports.string(),
|
|
20974
|
+
// Empty when the instances carried no file path (a prompt, or a tool call
|
|
20975
|
+
// with no file attribution). Both halves empty is a real location — usually
|
|
20976
|
+
// the largest one in a store — and is selectable like any other.
|
|
20977
|
+
file: external_exports.string(),
|
|
20906
20978
|
instanceCount: external_exports.number().int().nonnegative(),
|
|
20979
|
+
// The WORST severity present, not the first row's. It is this list's primary
|
|
20980
|
+
// sort key, so it is also what explains why a row is where it is, and it is
|
|
20981
|
+
// how a reader decides what to open without opening everything.
|
|
20907
20982
|
maxSeverity: Severity,
|
|
20908
20983
|
latestDetectedAt: external_exports.iso.datetime(),
|
|
20984
|
+
// Folded from the instances' derived statuses with the same open-dominates
|
|
20985
|
+
// precedence a group uses, so it answers "is anything left to do here" and
|
|
20986
|
+
// not much more: a location holding 1 open among 40 resolved reads like one
|
|
20987
|
+
// holding 40 open. That loss is accepted — the panel beside this list
|
|
20988
|
+
// carries each finding's own status, and instanceCount sits next to the
|
|
20989
|
+
// badge.
|
|
20909
20990
|
status: FindingStatus.optional(),
|
|
20910
|
-
|
|
20911
|
-
|
|
20991
|
+
// Every distinct rule seen at this location, UNCAPPED — so the length is a
|
|
20992
|
+
// tally rather than a sample and a row can say how many there are. Bounded
|
|
20993
|
+
// by the ruleset, not by the store. The view bounds what it DISPLAYS.
|
|
20994
|
+
ruleIds: external_exports.array(external_exports.string())
|
|
20995
|
+
}).meta({ id: "FindingLocationSummary" });
|
|
20996
|
+
var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
|
|
20997
|
+
var MAX_FINDING_LOCATIONS_LIMIT = 100;
|
|
20912
20998
|
var ListFindingLocationsQuery = external_exports.object({
|
|
20913
20999
|
severity: external_exports.array(Severity).optional(),
|
|
20914
21000
|
subtype: external_exports.array(external_exports.string()).optional(),
|
|
@@ -20918,21 +21004,47 @@ var ListFindingLocationsQuery = external_exports.object({
|
|
|
20918
21004
|
// instances that match, and folds its status from those.
|
|
20919
21005
|
status: external_exports.array(FindingStatus).optional(),
|
|
20920
21006
|
tool: external_exports.array(external_exports.string()).optional(),
|
|
21007
|
+
// The delivery state of each finding's event (see FindingDelivery).
|
|
21008
|
+
deployment: external_exports.array(FindingDeliveryState).optional(),
|
|
20921
21009
|
q: external_exports.string().optional(),
|
|
20922
21010
|
sessionId: external_exports.string().optional(),
|
|
20923
21011
|
from: external_exports.iso.datetime().optional(),
|
|
20924
|
-
|
|
21012
|
+
// A LOCATION id (see FindingLocationSummary.id) that must appear in the page
|
|
21013
|
+
// even when the cursor has already advanced past its sort position — the
|
|
21014
|
+
// counterpart of ListFindingTypesQuery.includeId, and needed far more often
|
|
21015
|
+
// here. Selecting a row pushes the URL, which re-renders the server and resets
|
|
21016
|
+
// the client's page cache to page 0; with distinct (repo, file) pairs running
|
|
21017
|
+
// into the thousands, a selection sitting off page 0 is the ordinary case
|
|
21018
|
+
// rather than a deep-link corner. Never affects totals, facets or the cursor.
|
|
21019
|
+
includeId: external_exports.string().optional(),
|
|
21020
|
+
limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
|
|
21021
|
+
cursor: external_exports.string().optional()
|
|
20925
21022
|
});
|
|
20926
21023
|
var ListFindingLocationsResponse = external_exports.object({
|
|
20927
21024
|
totals: external_exports.object({
|
|
21025
|
+
// Findings matching the filters across the whole scope. Unlike the types
|
|
21026
|
+
// read's same-named field this needs no caveat: the filters here narrow
|
|
21027
|
+
// per finding, so this is the sum of every row's instanceCount.
|
|
20928
21028
|
findings: external_exports.number().int().nonnegative(),
|
|
20929
|
-
|
|
20930
|
-
|
|
21029
|
+
// Counts LOCATIONS, the unit this read pages — the number the paginator
|
|
21030
|
+
// states. The facets beside it count FINDINGS (see below); a surface
|
|
21031
|
+
// showing both says which is which.
|
|
21032
|
+
locations: external_exports.number().int().nonnegative()
|
|
20931
21033
|
}),
|
|
20932
|
-
|
|
20933
|
-
|
|
20934
|
-
|
|
20935
|
-
|
|
21034
|
+
// Counts in FINDINGS, where the types response counts types, each dimension
|
|
21035
|
+
// still excluding its own filter. Deliberately not locations: counting those
|
|
21036
|
+
// needs a set of location keys per dimension per value — memory tracking the
|
|
21037
|
+
// store times the vocabulary, in a read whose scan promises flat memory —
|
|
21038
|
+
// and the cheap per-location version is not an approximation but WRONG. A
|
|
21039
|
+
// location holding {claudecode, block} and {codex, warn} would survive
|
|
21040
|
+
// provider=claudecode AND action=warn, under which no single finding
|
|
21041
|
+
// matches, so the facet would contradict the instanceCount this whole view
|
|
21042
|
+
// rests on. Findings also keep the toolbar in the same unit as the page
|
|
21043
|
+
// tally and the panel it sits above.
|
|
21044
|
+
facets: FindingFacets,
|
|
21045
|
+
/** Sorted by max severity, then most recent, then (repo, file). */
|
|
21046
|
+
items: external_exports.array(FindingLocationSummary),
|
|
21047
|
+
nextCursor: external_exports.string().nullable()
|
|
20936
21048
|
}).meta({ id: "ListFindingLocationsResponse" });
|
|
20937
21049
|
|
|
20938
21050
|
// ../../packages/schema/src/zod/meta.ts
|
|
@@ -21096,6 +21208,10 @@ var CaptureAttributes = external_exports.object({
|
|
|
21096
21208
|
// to 'allow' — the enforcement audit trail's link back to the grant that
|
|
21097
21209
|
// authorized the bypass.
|
|
21098
21210
|
exception_ids: external_exports.array(external_exports.guid()).optional(),
|
|
21211
|
+
// The persisted spellings of EventMetadata's messageId/conversationId — the
|
|
21212
|
+
// join back to the `llm_call` leaf for the same assistant turn.
|
|
21213
|
+
message_id: external_exports.string().optional(),
|
|
21214
|
+
conversation_id: external_exports.string().optional(),
|
|
21099
21215
|
// Whole milliseconds this capture's inspection blocked its caller — the
|
|
21100
21216
|
// plugin's own added latency (see EventMetadata.inspectionMs, whose value
|
|
21101
21217
|
// this is). Promoted to the `inspection_ms` generated column so the facet is
|
|
@@ -21104,7 +21220,19 @@ var CaptureAttributes = external_exports.object({
|
|
|
21104
21220
|
// inline json_extract and is not itself an optimization.
|
|
21105
21221
|
// ABSENT on replayed captures (backfill / worktree scan) and on rows written
|
|
21106
21222
|
// before the measurement shipped — never present as a placeholder 0.
|
|
21107
|
-
inspection_ms: external_exports.number().int().nonnegative().optional()
|
|
21223
|
+
inspection_ms: external_exports.number().int().nonnegative().optional(),
|
|
21224
|
+
// What a `redact` this capture could not carry out became instead (see
|
|
21225
|
+
// EventMetadata.redactDegradedTo, whose value this is). Present only when a
|
|
21226
|
+
// degrade actually happened, so absence is the ordinary case rather than a
|
|
21227
|
+
// reader having to distinguish it from a zero.
|
|
21228
|
+
//
|
|
21229
|
+
// PER CAPTURE, while `inspection_findings.action_taken` is per finding —
|
|
21230
|
+
// so on a multi-finding row this does not say which finding degraded, and
|
|
21231
|
+
// its presence does not mean the fallback decided the capture's action. A
|
|
21232
|
+
// capture denied by another finding's own Block policy carries `block`
|
|
21233
|
+
// here too. The full statement is on EventMetadata.redactDegradedTo; it is
|
|
21234
|
+
// repeated rather than referenced because a store reader opens this file.
|
|
21235
|
+
redact_degraded_to: ActionTaken.optional()
|
|
21108
21236
|
}).catchall(external_exports.unknown());
|
|
21109
21237
|
var ToolCallInspection = external_exports.object({
|
|
21110
21238
|
ruleId: external_exports.string().min(1),
|
|
@@ -21303,7 +21431,17 @@ var AuditEvent = external_exports.object({
|
|
|
21303
21431
|
/** `share` to a first-party/internal destination. */
|
|
21304
21432
|
internal: external_exports.boolean(),
|
|
21305
21433
|
/** Event needs review (e.g. unverified egress). */
|
|
21306
|
-
flagged: external_exports.boolean()
|
|
21434
|
+
flagged: external_exports.boolean(),
|
|
21435
|
+
/**
|
|
21436
|
+
* The body this event's `title` is drawn from was cleared by local body
|
|
21437
|
+
* expiry, so an EMPTY title here means "gone", not "never had one".
|
|
21438
|
+
*
|
|
21439
|
+
* A separate flag rather than a sentinel written into `title`: the title is
|
|
21440
|
+
* rendered text, and a store-layer module that invented display copy for it
|
|
21441
|
+
* would be choosing words the view is supposed to choose. Additive and
|
|
21442
|
+
* defaulted, so an older producer still validates.
|
|
21443
|
+
*/
|
|
21444
|
+
bodyExpired: external_exports.boolean().default(false)
|
|
21307
21445
|
}).meta({ id: "ActivityAuditEvent" });
|
|
21308
21446
|
var ActivitySessionSummary = external_exports.object({
|
|
21309
21447
|
id: external_exports.string(),
|
|
@@ -22100,6 +22238,14 @@ var ControlPlaneErrorBody = external_exports.object({
|
|
|
22100
22238
|
message: external_exports.string().optional()
|
|
22101
22239
|
}).optional()
|
|
22102
22240
|
});
|
|
22241
|
+
var RemoteFailureKind = external_exports.enum([
|
|
22242
|
+
"unauthorized",
|
|
22243
|
+
"forbidden",
|
|
22244
|
+
"route-absent",
|
|
22245
|
+
"invalid-request",
|
|
22246
|
+
"rejected",
|
|
22247
|
+
"unreachable"
|
|
22248
|
+
]);
|
|
22103
22249
|
var AttachDeviceRequest = external_exports.object({
|
|
22104
22250
|
// This machine's own continuity id, so re-attaching ROTATES the credential
|
|
22105
22251
|
// on one machine record instead of producing a second one. Client-minted
|
|
@@ -22635,6 +22781,12 @@ var EventMetadata = external_exports.object({
|
|
|
22635
22781
|
// to 'allow' — the enforcement audit trail's link back to the grant that
|
|
22636
22782
|
// authorized the bypass. Absent on captures where no exception applied.
|
|
22637
22783
|
exceptionIds: external_exports.array(external_exports.guid()).optional(),
|
|
22784
|
+
// The assistant message this capture belongs to, and the conversation it sits
|
|
22785
|
+
// in — set by the browser extension's network capture so a stored `response`
|
|
22786
|
+
// row can be joined to the `llm_call` leaf describing the same turn. Absent
|
|
22787
|
+
// on every other capture path, which has no such id.
|
|
22788
|
+
messageId: external_exports.string().optional(),
|
|
22789
|
+
conversationId: external_exports.string().optional(),
|
|
22638
22790
|
// How long THIS capture's inspection blocked its caller, in whole
|
|
22639
22791
|
// milliseconds — the plugin's own added latency, NOT the LLM call it sat in
|
|
22640
22792
|
// front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
|
|
@@ -22647,7 +22799,37 @@ var EventMetadata = external_exports.object({
|
|
|
22647
22799
|
// Absent is also what every pre-measurement client writes, and what a
|
|
22648
22800
|
// clock failure degrades to — a reader must treat absence as "not measured"
|
|
22649
22801
|
// and never as a zero, which would read as "inspection is free".
|
|
22650
|
-
inspectionMs: external_exports.number().int().nonnegative().optional()
|
|
22802
|
+
inspectionMs: external_exports.number().int().nonnegative().optional(),
|
|
22803
|
+
// What a `redact` this capture COULD NOT CARRY OUT became instead — the
|
|
22804
|
+
// workspace's `redactFallback`, applied because the field could not be
|
|
22805
|
+
// masked in place (a shell command, a URL, or any argument on a host whose
|
|
22806
|
+
// hook contract offers no rewrite channel).
|
|
22807
|
+
//
|
|
22808
|
+
// It exists because the action alone cannot say why. A finding recorded as
|
|
22809
|
+
// `warn` reads identically whether its detection was ASSIGNED Warn or was
|
|
22810
|
+
// assigned Redact on a field that could not take one — and those are
|
|
22811
|
+
// different facts about the same row: the first is a policy the user chose,
|
|
22812
|
+
// the second is a masking the host could not perform. Absent means no
|
|
22813
|
+
// degrade happened, which is every ordinary capture.
|
|
22814
|
+
//
|
|
22815
|
+
// TWO LIMITS a reader of a stored row has to know, because the grain here
|
|
22816
|
+
// is the CAPTURE while `actionTaken` is per FINDING:
|
|
22817
|
+
//
|
|
22818
|
+
// - It does not say WHICH finding degraded. A capture carrying a degraded
|
|
22819
|
+
// `redact` alongside a finding ASSIGNED the same action stores both
|
|
22820
|
+
// identically and one reason for the pair; attributing it to both
|
|
22821
|
+
// describes the assigned one wrongly, and to neither loses the degrade.
|
|
22822
|
+
// - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
|
|
22823
|
+
// became, not the reason the capture ended as it did — a capture denied
|
|
22824
|
+
// by some other finding's own Block policy still carries `block` here,
|
|
22825
|
+
// and clearing the workspace's fallback would not have let it through.
|
|
22826
|
+
// Gate on the value against what a fallback can produce; never read the
|
|
22827
|
+
// field's presence as "this was the fallback's doing".
|
|
22828
|
+
//
|
|
22829
|
+
// Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
|
|
22830
|
+
// Closing either means moving the reason onto the finding row, which
|
|
22831
|
+
// already carries its own action.
|
|
22832
|
+
redactDegradedTo: ActionTaken.optional()
|
|
22651
22833
|
}).meta({ id: "EventMetadata" });
|
|
22652
22834
|
var Event = external_exports.object({
|
|
22653
22835
|
id: external_exports.guid(),
|
|
@@ -22757,7 +22939,32 @@ var RotateKeyInput = external_exports.object({
|
|
|
22757
22939
|
confirmation: external_exports.string()
|
|
22758
22940
|
});
|
|
22759
22941
|
|
|
22942
|
+
// ../../packages/schema/src/zod/finding-delivery.ts
|
|
22943
|
+
var KNOWN_REASONS = SyncFailureReason.options;
|
|
22944
|
+
function knownReason(value) {
|
|
22945
|
+
return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
|
|
22946
|
+
}
|
|
22947
|
+
function deriveFindingDelivery(row) {
|
|
22948
|
+
if (row.kind === "code_change") return { state: "local_scan" };
|
|
22949
|
+
if (row.syncedAt !== null && row.syncedAt > 0) {
|
|
22950
|
+
return { state: "sent", at: epochMillisToIso(row.syncedAt) };
|
|
22951
|
+
}
|
|
22952
|
+
if (row.syncedAt !== null) {
|
|
22953
|
+
const reason = knownReason(row.syncFailure);
|
|
22954
|
+
return {
|
|
22955
|
+
state: "not_sent",
|
|
22956
|
+
...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
|
|
22957
|
+
...reason === void 0 ? {} : { reason }
|
|
22958
|
+
};
|
|
22959
|
+
}
|
|
22960
|
+
if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
|
|
22961
|
+
return { state: "never_offered" };
|
|
22962
|
+
}
|
|
22963
|
+
|
|
22760
22964
|
// ../../packages/schema/src/zod/findings-group-build.ts
|
|
22965
|
+
function lookupOwn(map2, key) {
|
|
22966
|
+
return Object.hasOwn(map2, key) ? map2[key] : void 0;
|
|
22967
|
+
}
|
|
22761
22968
|
function toApiAction(dbVal) {
|
|
22762
22969
|
const map2 = {
|
|
22763
22970
|
log: "monitored",
|
|
@@ -22766,7 +22973,7 @@ function toApiAction(dbVal) {
|
|
|
22766
22973
|
warn: "warned",
|
|
22767
22974
|
allow: "allowed"
|
|
22768
22975
|
};
|
|
22769
|
-
return map2
|
|
22976
|
+
return lookupOwn(map2, dbVal) ?? "allowed";
|
|
22770
22977
|
}
|
|
22771
22978
|
function toApiCategory(dbVal) {
|
|
22772
22979
|
if (dbVal === "code_context") return "source_code";
|
|
@@ -22774,13 +22981,18 @@ function toApiCategory(dbVal) {
|
|
|
22774
22981
|
return parsed.success ? parsed.data : "custom";
|
|
22775
22982
|
}
|
|
22776
22983
|
function toApiProvider(sourceTool) {
|
|
22777
|
-
return TOOL_TO_HARNESS
|
|
22984
|
+
return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
|
|
22778
22985
|
}
|
|
22779
|
-
var
|
|
22986
|
+
var FINDING_STATUS_PRECEDENCE = [
|
|
22987
|
+
"open",
|
|
22988
|
+
"handled",
|
|
22989
|
+
"dismissed",
|
|
22990
|
+
"resolved"
|
|
22991
|
+
];
|
|
22780
22992
|
function foldGroupStatus(instanceStatuses) {
|
|
22781
22993
|
const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
|
|
22782
22994
|
if (statuses.size === 0) return void 0;
|
|
22783
|
-
for (const candidate of
|
|
22995
|
+
for (const candidate of FINDING_STATUS_PRECEDENCE) {
|
|
22784
22996
|
if (statuses.has(candidate)) return candidate;
|
|
22785
22997
|
}
|
|
22786
22998
|
return void 0;
|
|
@@ -22793,139 +23005,62 @@ function deriveFindingStatus(row) {
|
|
|
22793
23005
|
if (row.latestResolutionStatus === "dismissed") return "dismissed";
|
|
22794
23006
|
return "open";
|
|
22795
23007
|
}
|
|
22796
|
-
function distinctUsers(instances) {
|
|
22797
|
-
const seen = /* @__PURE__ */ new Set();
|
|
22798
|
-
const users = [];
|
|
22799
|
-
for (const i of instances) {
|
|
22800
|
-
if (i.user === void 0 || seen.has(i.user.id)) continue;
|
|
22801
|
-
seen.add(i.user.id);
|
|
22802
|
-
users.push(i.user);
|
|
22803
|
-
}
|
|
22804
|
-
return users;
|
|
22805
|
-
}
|
|
22806
23008
|
function sortUsers(users) {
|
|
22807
23009
|
return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
|
|
22808
23010
|
}
|
|
22809
|
-
function
|
|
22810
|
-
const overrides = opts.overrides;
|
|
23011
|
+
function buildFindingTypes(aggregates, opts = {}) {
|
|
22811
23012
|
const packNames = opts.packNames;
|
|
22812
|
-
const
|
|
22813
|
-
const
|
|
22814
|
-
|
|
22815
|
-
const
|
|
22816
|
-
|
|
22817
|
-
else byRuleId.set(row.ruleId, [row]);
|
|
22818
|
-
}
|
|
22819
|
-
const groups = [];
|
|
22820
|
-
for (const [ruleId, ruleRows] of byRuleId) {
|
|
22821
|
-
const instances = ruleRows.map((r) => {
|
|
22822
|
-
const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
|
|
22823
|
-
return {
|
|
22824
|
-
id: r.id,
|
|
22825
|
-
provider: toApiProvider(r.sourceTool),
|
|
22826
|
-
repo: r.repo,
|
|
22827
|
-
file: r.file,
|
|
22828
|
-
...r.toolName === void 0 ? {} : { toolName: r.toolName },
|
|
22829
|
-
...r.eventId === void 0 ? {} : { eventId: r.eventId },
|
|
22830
|
-
...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
|
|
22831
|
-
...r.user === void 0 ? {} : { user: r.user },
|
|
22832
|
-
action: toApiAction(effectiveDbAction),
|
|
22833
|
-
detectedAt: r.occurredAt,
|
|
22834
|
-
confidence: r.confidence,
|
|
22835
|
-
status: r.status
|
|
22836
|
-
};
|
|
22837
|
-
});
|
|
22838
|
-
const agg = aggregates?.get(ruleId);
|
|
22839
|
-
const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
|
|
22840
|
-
const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
|
|
22841
|
-
(max, r) => r.occurredAt > max ? r.occurredAt : max,
|
|
22842
|
-
ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
|
|
22843
|
-
);
|
|
22844
|
-
const seenProviders = /* @__PURE__ */ new Set();
|
|
22845
|
-
const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
|
|
22846
|
-
if (seenProviders.has(p)) return false;
|
|
22847
|
-
seenProviders.add(p);
|
|
22848
|
-
return true;
|
|
22849
|
-
});
|
|
22850
|
-
const actionSet = new Set(
|
|
22851
|
-
agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
|
|
22852
|
-
);
|
|
23013
|
+
const types = [];
|
|
23014
|
+
for (const [ruleId, agg] of aggregates) {
|
|
23015
|
+
const users = sortUsers(agg.users ?? []);
|
|
23016
|
+
const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
|
|
23017
|
+
const actionSet = new Set(agg.actionsTaken.map(toApiAction));
|
|
22853
23018
|
const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
|
|
22854
|
-
const
|
|
22855
|
-
const
|
|
22856
|
-
id: ruleId,
|
|
22857
|
-
name: packNames?.get(ruleId) ?? null
|
|
22858
|
-
};
|
|
22859
|
-
const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
|
|
22860
|
-
const policy = { id: `category:${apiCategory}`, name: apiCategory };
|
|
22861
|
-
const match = {
|
|
22862
|
-
maskedValue: ruleRows[0]?.maskedMatch ?? "",
|
|
22863
|
-
contextPrefix: ""
|
|
22864
|
-
// empty (pending privacy review)
|
|
22865
|
-
};
|
|
22866
|
-
const status = foldGroupStatus(
|
|
22867
|
-
agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
|
|
22868
|
-
);
|
|
22869
|
-
const group = {
|
|
23019
|
+
const apiCategory = toApiCategory(agg.category ?? "custom");
|
|
23020
|
+
const type = {
|
|
22870
23021
|
id: ruleId,
|
|
22871
23022
|
category: apiCategory,
|
|
22872
23023
|
subtype: ruleId,
|
|
22873
23024
|
// human label comes with pack metadata later
|
|
22874
|
-
severity,
|
|
22875
|
-
|
|
22876
|
-
|
|
22877
|
-
|
|
22878
|
-
instanceCount: agg?.instanceCount ?? instances.length,
|
|
23025
|
+
severity: agg.severity ?? "low",
|
|
23026
|
+
detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
|
|
23027
|
+
policy: { id: `category:${apiCategory}`, name: apiCategory },
|
|
23028
|
+
instanceCount: agg.instanceCount,
|
|
22879
23029
|
providers,
|
|
22880
23030
|
aggregateAction,
|
|
22881
|
-
latestDetectedAt,
|
|
22882
|
-
|
|
22883
|
-
status,
|
|
23031
|
+
latestDetectedAt: agg.latestDetectedAt,
|
|
23032
|
+
status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
|
|
22884
23033
|
...users.length > 0 ? { users } : {}
|
|
22885
23034
|
};
|
|
22886
|
-
|
|
22887
|
-
|
|
22888
|
-
|
|
22889
|
-
haystackCache.set(group, buildHaystack(group, agg.searchText));
|
|
22890
|
-
}
|
|
23035
|
+
actionsCache.set(type, [...actionSet]);
|
|
23036
|
+
if (agg.searchText !== void 0) {
|
|
23037
|
+
haystackCache.set(type, buildHaystack(type, agg.searchText));
|
|
22891
23038
|
}
|
|
22892
|
-
|
|
23039
|
+
types.push(type);
|
|
22893
23040
|
}
|
|
22894
|
-
return
|
|
23041
|
+
return types;
|
|
22895
23042
|
}
|
|
22896
23043
|
var haystackCache = /* @__PURE__ */ new WeakMap();
|
|
22897
|
-
function buildHaystack(
|
|
23044
|
+
function buildHaystack(t, extra) {
|
|
22898
23045
|
return [
|
|
22899
|
-
|
|
22900
|
-
|
|
22901
|
-
|
|
22902
|
-
|
|
22903
|
-
|
|
22904
|
-
...g.instances.map((i) => i.repo),
|
|
22905
|
-
...g.instances.map((i) => i.file),
|
|
22906
|
-
...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
|
|
22907
|
-
...g.instances.map((i) => i.id),
|
|
22908
|
-
// The people: the whole group's list when the store folded one, plus the
|
|
22909
|
-
// preview's own — the two overlap, and a haystack does not mind.
|
|
22910
|
-
...(g.users ?? []).map((u) => u.name),
|
|
22911
|
-
...g.instances.map((i) => i.user?.name ?? ""),
|
|
23046
|
+
t.subtype,
|
|
23047
|
+
t.category,
|
|
23048
|
+
t.policy.name,
|
|
23049
|
+
t.id,
|
|
23050
|
+
...(t.users ?? []).map((u) => u.name),
|
|
22912
23051
|
...extra === void 0 ? [] : [extra]
|
|
22913
23052
|
].join(" ").toLowerCase();
|
|
22914
23053
|
}
|
|
22915
|
-
function
|
|
22916
|
-
const cached2 = haystackCache.get(
|
|
23054
|
+
function typeHaystack(t) {
|
|
23055
|
+
const cached2 = haystackCache.get(t);
|
|
22917
23056
|
if (cached2 !== void 0) return cached2;
|
|
22918
|
-
const haystack = buildHaystack(
|
|
22919
|
-
haystackCache.set(
|
|
23057
|
+
const haystack = buildHaystack(t);
|
|
23058
|
+
haystackCache.set(t, haystack);
|
|
22920
23059
|
return haystack;
|
|
22921
23060
|
}
|
|
22922
23061
|
var actionsCache = /* @__PURE__ */ new WeakMap();
|
|
22923
|
-
function
|
|
22924
|
-
|
|
22925
|
-
if (cached2 !== void 0) return cached2;
|
|
22926
|
-
const actions = [...new Set(g.instances.map((i) => i.action))];
|
|
22927
|
-
actionsCache.set(g, actions);
|
|
22928
|
-
return actions;
|
|
23062
|
+
function typeActions(t) {
|
|
23063
|
+
return actionsCache.get(t) ?? [];
|
|
22929
23064
|
}
|
|
22930
23065
|
function countInstancesByStatus(statusInputs, statuses) {
|
|
22931
23066
|
const statusSet = new Set(statuses);
|
|
@@ -22936,8 +23071,8 @@ function countInstancesByStatus(statusInputs, statuses) {
|
|
|
22936
23071
|
}
|
|
22937
23072
|
return sum;
|
|
22938
23073
|
}
|
|
22939
|
-
function applyFindingFilters(
|
|
22940
|
-
let filtered =
|
|
23074
|
+
function applyFindingFilters(types, opts) {
|
|
23075
|
+
let filtered = types;
|
|
22941
23076
|
if (opts.severity && opts.severity.length > 0) {
|
|
22942
23077
|
const sevSet = new Set(opts.severity);
|
|
22943
23078
|
filtered = filtered.filter((g) => sevSet.has(g.severity));
|
|
@@ -22948,7 +23083,7 @@ function applyFindingFilters(groups, opts) {
|
|
|
22948
23083
|
}
|
|
22949
23084
|
if (opts.actions && opts.actions.length > 0) {
|
|
22950
23085
|
const actionSet = new Set(opts.actions);
|
|
22951
|
-
filtered = filtered.filter((
|
|
23086
|
+
filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
|
|
22952
23087
|
}
|
|
22953
23088
|
if (opts.subtype && opts.subtype.length > 0) {
|
|
22954
23089
|
const subtypeSet = new Set(opts.subtype);
|
|
@@ -22960,26 +23095,31 @@ function applyFindingFilters(groups, opts) {
|
|
|
22960
23095
|
}
|
|
22961
23096
|
if (opts.q) {
|
|
22962
23097
|
const q = opts.q.toLowerCase();
|
|
22963
|
-
filtered = filtered.filter((
|
|
23098
|
+
filtered = filtered.filter((t) => typeHaystack(t).includes(q));
|
|
22964
23099
|
}
|
|
22965
23100
|
return filtered;
|
|
22966
23101
|
}
|
|
22967
|
-
|
|
22968
|
-
|
|
23102
|
+
function rankByOrder(members2) {
|
|
23103
|
+
return Object.fromEntries(members2.map((member, index) => [member, index]));
|
|
23104
|
+
}
|
|
23105
|
+
var SEVERITY_RANK = rankByOrder(Severity.options);
|
|
23106
|
+
function severityRank(severity) {
|
|
23107
|
+
return lookupOwn(SEVERITY_RANK, severity);
|
|
23108
|
+
}
|
|
22969
23109
|
function compareFindingGroupOrder(a, b) {
|
|
22970
|
-
const rankA =
|
|
22971
|
-
const rankB =
|
|
23110
|
+
const rankA = severityRank(a.severity) ?? -1;
|
|
23111
|
+
const rankB = severityRank(b.severity) ?? -1;
|
|
22972
23112
|
const severityDiff = rankA - rankB;
|
|
22973
23113
|
if (severityDiff !== 0) return severityDiff;
|
|
22974
23114
|
const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
|
|
22975
23115
|
if (recencyDiff !== 0) return recencyDiff;
|
|
22976
23116
|
return a.id.localeCompare(b.id);
|
|
22977
23117
|
}
|
|
22978
|
-
function
|
|
22979
|
-
return [...
|
|
23118
|
+
function sortFindingTypes(types) {
|
|
23119
|
+
return [...types].sort(compareFindingGroupOrder);
|
|
22980
23120
|
}
|
|
22981
|
-
function computeFindingFacets(
|
|
22982
|
-
const forSeverity = applyFindingFilters(
|
|
23121
|
+
function computeFindingFacets(allTypes, opts) {
|
|
23122
|
+
const forSeverity = applyFindingFilters(allTypes, {
|
|
22983
23123
|
providers: opts.providers,
|
|
22984
23124
|
actions: opts.actions,
|
|
22985
23125
|
statuses: opts.statuses,
|
|
@@ -22990,7 +23130,7 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
22990
23130
|
for (const g of forSeverity) {
|
|
22991
23131
|
severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
|
|
22992
23132
|
}
|
|
22993
|
-
const forProvider = applyFindingFilters(
|
|
23133
|
+
const forProvider = applyFindingFilters(allTypes, {
|
|
22994
23134
|
actions: opts.actions,
|
|
22995
23135
|
statuses: opts.statuses,
|
|
22996
23136
|
q: opts.q,
|
|
@@ -23001,7 +23141,7 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
23001
23141
|
for (const g of forProvider) {
|
|
23002
23142
|
for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
|
|
23003
23143
|
}
|
|
23004
|
-
const forAction = applyFindingFilters(
|
|
23144
|
+
const forAction = applyFindingFilters(allTypes, {
|
|
23005
23145
|
providers: opts.providers,
|
|
23006
23146
|
statuses: opts.statuses,
|
|
23007
23147
|
q: opts.q,
|
|
@@ -23010,9 +23150,9 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
23010
23150
|
});
|
|
23011
23151
|
const actionMap = /* @__PURE__ */ new Map();
|
|
23012
23152
|
for (const g of forAction) {
|
|
23013
|
-
for (const a of
|
|
23153
|
+
for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
|
|
23014
23154
|
}
|
|
23015
|
-
const forSubtype = applyFindingFilters(
|
|
23155
|
+
const forSubtype = applyFindingFilters(allTypes, {
|
|
23016
23156
|
providers: opts.providers,
|
|
23017
23157
|
actions: opts.actions,
|
|
23018
23158
|
statuses: opts.statuses,
|
|
@@ -23021,7 +23161,7 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
23021
23161
|
});
|
|
23022
23162
|
const subtypeMap = /* @__PURE__ */ new Map();
|
|
23023
23163
|
for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
|
|
23024
|
-
const forStatus = applyFindingFilters(
|
|
23164
|
+
const forStatus = applyFindingFilters(allTypes, {
|
|
23025
23165
|
providers: opts.providers,
|
|
23026
23166
|
actions: opts.actions,
|
|
23027
23167
|
q: opts.q,
|
|
@@ -23043,6 +23183,20 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
23043
23183
|
}
|
|
23044
23184
|
|
|
23045
23185
|
// ../../packages/schema/src/zod/findings-flat-build.ts
|
|
23186
|
+
function compareCodePoints(a, b) {
|
|
23187
|
+
const aIter = a[Symbol.iterator]();
|
|
23188
|
+
const bIter = b[Symbol.iterator]();
|
|
23189
|
+
for (; ; ) {
|
|
23190
|
+
const aNext = aIter.next();
|
|
23191
|
+
const bNext = bIter.next();
|
|
23192
|
+
if (aNext.done && bNext.done) return 0;
|
|
23193
|
+
if (aNext.done) return -1;
|
|
23194
|
+
if (bNext.done) return 1;
|
|
23195
|
+
const aPoint = aNext.value.codePointAt(0) ?? 0;
|
|
23196
|
+
const bPoint = bNext.value.codePointAt(0) ?? 0;
|
|
23197
|
+
if (aPoint !== bPoint) return aPoint - bPoint;
|
|
23198
|
+
}
|
|
23199
|
+
}
|
|
23046
23200
|
function rowHaystack(row) {
|
|
23047
23201
|
return [
|
|
23048
23202
|
row.ruleId,
|
|
@@ -23067,12 +23221,24 @@ function matchesDimension(row, opts, dimension) {
|
|
|
23067
23221
|
return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
|
|
23068
23222
|
case "statuses":
|
|
23069
23223
|
return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
|
|
23224
|
+
case "deliveries":
|
|
23225
|
+
return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
|
|
23070
23226
|
case "tools":
|
|
23071
23227
|
return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
|
|
23228
|
+
// An EMPTY value is a real filter here, not an absent one. The location
|
|
23229
|
+
// list buckets a finding whose event recorded no repo — or no file — under
|
|
23230
|
+
// the empty string, and selecting that bucket has to narrow the panel to
|
|
23231
|
+
// exactly it. Only `undefined` means "no filter"; a caller that wants every
|
|
23232
|
+
// row omits the key, which every call site already does.
|
|
23233
|
+
//
|
|
23234
|
+
// Reading '' as unset is what this replaced, and it failed in the one place
|
|
23235
|
+
// it mattered: the no-repo/no-file bucket is often the largest in a real
|
|
23236
|
+
// store, and its panel dropped both predicates and returned the WHOLE scope
|
|
23237
|
+
// — a row reading 3 findings beside a panel listing every finding there is.
|
|
23072
23238
|
case "repo":
|
|
23073
|
-
return opts.repo === void 0 ||
|
|
23239
|
+
return opts.repo === void 0 || row.repo === opts.repo;
|
|
23074
23240
|
case "file":
|
|
23075
|
-
return opts.file === void 0 ||
|
|
23241
|
+
return opts.file === void 0 || row.file === opts.file;
|
|
23076
23242
|
case "q":
|
|
23077
23243
|
return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
|
|
23078
23244
|
}
|
|
@@ -23083,6 +23249,7 @@ var DIMENSIONS = [
|
|
|
23083
23249
|
"providers",
|
|
23084
23250
|
"actions",
|
|
23085
23251
|
"statuses",
|
|
23252
|
+
"deliveries",
|
|
23086
23253
|
"tools",
|
|
23087
23254
|
"repo",
|
|
23088
23255
|
"file",
|
|
@@ -23096,10 +23263,19 @@ function matchesInstanceFilters(row, opts, except) {
|
|
|
23096
23263
|
return true;
|
|
23097
23264
|
}
|
|
23098
23265
|
function toItems(counts) {
|
|
23099
|
-
return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
|
|
23266
|
+
return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
|
|
23267
|
+
(a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
|
|
23268
|
+
// NFD spelling of the same text) as equal, so a count tie between
|
|
23269
|
+
// them would otherwise be ordered by whichever the Map iteration
|
|
23270
|
+
// produced. compareCodePoints breaks that tie deterministically, which
|
|
23271
|
+
// makes this a TOTAL order — not one that agrees with SQL collation,
|
|
23272
|
+
// which it need not: foldFacetTuples runs this same sort over grouped
|
|
23273
|
+
// tuples, so both paths order facets identically by construction.
|
|
23274
|
+
compareCodePoints(a.value, b.value)
|
|
23275
|
+
);
|
|
23100
23276
|
}
|
|
23101
|
-
function bump(counts, value) {
|
|
23102
|
-
counts.set(value, (counts.get(value) ?? 0) +
|
|
23277
|
+
function bump(counts, value, by = 1) {
|
|
23278
|
+
counts.set(value, (counts.get(value) ?? 0) + by);
|
|
23103
23279
|
}
|
|
23104
23280
|
function createInstanceFacetAccumulator(opts) {
|
|
23105
23281
|
const severity = /* @__PURE__ */ new Map();
|
|
@@ -23108,6 +23284,7 @@ function createInstanceFacetAccumulator(opts) {
|
|
|
23108
23284
|
const action = /* @__PURE__ */ new Map();
|
|
23109
23285
|
const status = /* @__PURE__ */ new Map();
|
|
23110
23286
|
const tool = /* @__PURE__ */ new Map();
|
|
23287
|
+
const deployment = /* @__PURE__ */ new Map();
|
|
23111
23288
|
return {
|
|
23112
23289
|
add(row) {
|
|
23113
23290
|
if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
|
|
@@ -23122,6 +23299,9 @@ function createInstanceFacetAccumulator(opts) {
|
|
|
23122
23299
|
if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
|
|
23123
23300
|
bump(tool, row.toolName);
|
|
23124
23301
|
}
|
|
23302
|
+
if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
|
|
23303
|
+
bump(deployment, row.delivery.state);
|
|
23304
|
+
}
|
|
23125
23305
|
},
|
|
23126
23306
|
facets: () => ({
|
|
23127
23307
|
severity: toItems(severity),
|
|
@@ -23129,7 +23309,8 @@ function createInstanceFacetAccumulator(opts) {
|
|
|
23129
23309
|
provider: toItems(provider),
|
|
23130
23310
|
action: toItems(action),
|
|
23131
23311
|
status: toItems(status),
|
|
23132
|
-
tool: toItems(tool)
|
|
23312
|
+
tool: toItems(tool),
|
|
23313
|
+
deployment: toItems(deployment)
|
|
23133
23314
|
})
|
|
23134
23315
|
};
|
|
23135
23316
|
}
|
|
@@ -23143,6 +23324,7 @@ function toInstanceDetail(row) {
|
|
|
23143
23324
|
...row.toolName === void 0 ? {} : { toolName: row.toolName },
|
|
23144
23325
|
eventId: row.eventId,
|
|
23145
23326
|
...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
|
|
23327
|
+
...row.delivery === void 0 ? {} : { delivery: row.delivery },
|
|
23146
23328
|
...row.user === void 0 ? {} : { user: row.user },
|
|
23147
23329
|
action: toApiAction(row.actionTaken),
|
|
23148
23330
|
detectedAt: row.occurredAt,
|
|
@@ -23157,12 +23339,6 @@ function toInstanceDetail(row) {
|
|
|
23157
23339
|
policy: { id: `category:${category}`, name: category }
|
|
23158
23340
|
};
|
|
23159
23341
|
}
|
|
23160
|
-
var SEVERITY_ORDER2 = {
|
|
23161
|
-
critical: 0,
|
|
23162
|
-
high: 1,
|
|
23163
|
-
medium: 2,
|
|
23164
|
-
low: 3
|
|
23165
|
-
};
|
|
23166
23342
|
function newLocationAccumulator() {
|
|
23167
23343
|
return {
|
|
23168
23344
|
instanceCount: 0,
|
|
@@ -23177,7 +23353,7 @@ function newLocationAccumulator() {
|
|
|
23177
23353
|
}
|
|
23178
23354
|
function addToLocation(acc, row) {
|
|
23179
23355
|
acc.instanceCount += 1;
|
|
23180
|
-
const rank =
|
|
23356
|
+
const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
|
|
23181
23357
|
if (rank < acc.maxSeverityRank) {
|
|
23182
23358
|
acc.maxSeverityRank = rank;
|
|
23183
23359
|
acc.maxSeverity = row.severity;
|
|
@@ -23186,6 +23362,23 @@ function addToLocation(acc, row) {
|
|
|
23186
23362
|
acc.statuses.push(row.status);
|
|
23187
23363
|
acc.ruleIds.add(row.ruleId);
|
|
23188
23364
|
}
|
|
23365
|
+
function compareLocationOrder(a, b) {
|
|
23366
|
+
const rankA = severityRank(a.maxSeverity) ?? -1;
|
|
23367
|
+
const rankB = severityRank(b.maxSeverity) ?? -1;
|
|
23368
|
+
if (rankA !== rankB) return rankA - rankB;
|
|
23369
|
+
if (a.latestDetectedAt !== b.latestDetectedAt) {
|
|
23370
|
+
return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
|
|
23371
|
+
}
|
|
23372
|
+
const repoDiff = compareCodePoints(a.repo, b.repo);
|
|
23373
|
+
if (repoDiff !== 0) return repoDiff;
|
|
23374
|
+
return compareCodePoints(a.file, b.file);
|
|
23375
|
+
}
|
|
23376
|
+
function encodeLocationId(repo, file2) {
|
|
23377
|
+
return `${encodePart(repo)}/${encodePart(file2)}`;
|
|
23378
|
+
}
|
|
23379
|
+
function encodePart(value) {
|
|
23380
|
+
return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
|
|
23381
|
+
}
|
|
23189
23382
|
|
|
23190
23383
|
// ../../packages/schema/src/zod/installed-pack.ts
|
|
23191
23384
|
var InstalledPack = external_exports.object({
|
|
@@ -23253,6 +23446,11 @@ var Policy = external_exports.object({
|
|
|
23253
23446
|
// test `prohibitedModels` passes and `reversibleRuleIds` fails.
|
|
23254
23447
|
provenance: PolicyProvenance.optional()
|
|
23255
23448
|
}).meta({ id: "Policy" });
|
|
23449
|
+
var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
|
|
23450
|
+
var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
|
|
23451
|
+
var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
|
|
23452
|
+
id: "RedactFallback"
|
|
23453
|
+
});
|
|
23256
23454
|
var PolicyBundle = external_exports.object({
|
|
23257
23455
|
version: external_exports.string(),
|
|
23258
23456
|
policies: external_exports.array(Policy),
|
|
@@ -23300,6 +23498,16 @@ var PolicyBundle = external_exports.object({
|
|
|
23300
23498
|
// control plane), so no name resolution stands between the decision and the
|
|
23301
23499
|
// comparison.
|
|
23302
23500
|
prohibitedModels: external_exports.array(external_exports.string()).optional(),
|
|
23501
|
+
// What a resolved `redact` becomes on a field the host cannot rewrite, as
|
|
23502
|
+
// the ORGANIZATION would have it. Merged raise-only against the device's own
|
|
23503
|
+
// `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
|
|
23504
|
+
// a control plane can tighten a machine and never loosen one — the same
|
|
23505
|
+
// direction `mergeRaiseOnly` enforces for policies.
|
|
23506
|
+
//
|
|
23507
|
+
// Optional so an older backend, and an older on-disk cache, still parses;
|
|
23508
|
+
// absent leaves the device's own setting in force, which is the behaviour
|
|
23509
|
+
// that predates the field and the safe direction to default.
|
|
23510
|
+
redactFallback: RedactFallback.optional(),
|
|
23303
23511
|
customKeywords: external_exports.array(external_exports.string()),
|
|
23304
23512
|
fetchedAt: external_exports.iso.datetime()
|
|
23305
23513
|
}).meta({ id: "PolicyBundle" });
|
|
@@ -23334,11 +23542,6 @@ function severityFloorPosture() {
|
|
|
23334
23542
|
for (const c of DetectionCategory.options) out[c] = severityFloorPolicy(c);
|
|
23335
23543
|
return out;
|
|
23336
23544
|
}
|
|
23337
|
-
var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
|
|
23338
|
-
var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
|
|
23339
|
-
var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
|
|
23340
|
-
id: "RedactFallback"
|
|
23341
|
-
});
|
|
23342
23545
|
var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
|
|
23343
23546
|
var BUILTIN_POLICY_SPECS = {
|
|
23344
23547
|
monitor: {
|
|
@@ -23634,7 +23837,7 @@ var VaultConsent = external_exports.object({
|
|
|
23634
23837
|
});
|
|
23635
23838
|
|
|
23636
23839
|
// ../../packages/schema/src/zod/local.ts
|
|
23637
|
-
var WORKSPACE_SETTINGS_SPEC_VERSION =
|
|
23840
|
+
var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
|
|
23638
23841
|
var MODEL_JUDGE_PAYLOAD_VERSION = 1;
|
|
23639
23842
|
var RunMode = external_exports.enum(["standalone", "attached"]);
|
|
23640
23843
|
var ControlPlaneConnection = external_exports.object({
|
|
@@ -23657,6 +23860,15 @@ var HistorySyncConsent = external_exports.object({
|
|
|
23657
23860
|
payloadVersion: external_exports.number().int().positive(),
|
|
23658
23861
|
endpoint: external_exports.string()
|
|
23659
23862
|
});
|
|
23863
|
+
var BODY_RETENTION_DEFAULT_DAYS = 30;
|
|
23864
|
+
var BodyRetention = external_exports.object({
|
|
23865
|
+
enabled: external_exports.boolean().default(false),
|
|
23866
|
+
// Never 0, and the ceiling is a fat-finger guard rather than a policy
|
|
23867
|
+
// limit — `enabled` is the real gate. A low value cannot reach a row the
|
|
23868
|
+
// sync ledger still owes: the sweep's age filter only ever NARROWS a
|
|
23869
|
+
// candidate set that is already bounded by "delivered, or never owed".
|
|
23870
|
+
retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
|
|
23871
|
+
}).meta({ id: "BodyRetention" });
|
|
23660
23872
|
var WorkspaceSettings = external_exports.object({
|
|
23661
23873
|
specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
|
|
23662
23874
|
runMode: RunMode.default("standalone"),
|
|
@@ -23700,12 +23912,18 @@ var WorkspaceSettings = external_exports.object({
|
|
|
23700
23912
|
// covers the current payload and must be re-granted.
|
|
23701
23913
|
modelJudgeConsent: ModelJudgeConsent.optional(),
|
|
23702
23914
|
// Records that the user consented to the DEFERRED send — the outbox — along
|
|
23703
|
-
// with the payload shape and the endpoint they agreed to. Since payload
|
|
23704
|
-
// that covers
|
|
23705
|
-
// carry prompt/reply text in `content
|
|
23706
|
-
// Absent until granted, and a grant for a different endpoint
|
|
23707
|
-
// payload no longer counts.
|
|
23708
|
-
historySyncConsent: HistorySyncConsent.optional()
|
|
23915
|
+
// with the payload shape and the endpoint they agreed to. Since payload v3
|
|
23916
|
+
// that covers the pre-attach backlog AND undelivered captures alike, and both
|
|
23917
|
+
// carry prompt/reply/tool-output text in `content`; the key name predates
|
|
23918
|
+
// both widenings. Absent until granted, and a grant for a different endpoint
|
|
23919
|
+
// or an older payload no longer counts.
|
|
23920
|
+
historySyncConsent: HistorySyncConsent.optional(),
|
|
23921
|
+
// Local body expiry (see BodyRetention). Off until switched on; expiring a
|
|
23922
|
+
// body never removes the row or its findings.
|
|
23923
|
+
bodyRetention: BodyRetention.default({
|
|
23924
|
+
enabled: false,
|
|
23925
|
+
retainDays: BODY_RETENTION_DEFAULT_DAYS
|
|
23926
|
+
})
|
|
23709
23927
|
});
|
|
23710
23928
|
function defaultWorkspaceSettings() {
|
|
23711
23929
|
return WorkspaceSettings.parse({});
|
|
@@ -23800,12 +24018,15 @@ function toCaptureAttributes(event) {
|
|
|
23800
24018
|
...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
|
|
23801
24019
|
...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
|
|
23802
24020
|
...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
|
|
24021
|
+
...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
|
|
23803
24022
|
// `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
|
|
23804
24023
|
// has ever populated either), but every legacy metadata key still rides
|
|
23805
24024
|
// the bag rather than being silently dropped — CaptureAttributes'
|
|
23806
24025
|
// `.catchall(z.unknown())` carries the long tail.
|
|
23807
24026
|
...metadata?.model !== void 0 ? { model: metadata.model } : {},
|
|
23808
|
-
...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
|
|
24027
|
+
...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
|
|
24028
|
+
...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
|
|
24029
|
+
...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
|
|
23809
24030
|
};
|
|
23810
24031
|
}
|
|
23811
24032
|
function captureDefinitionVersion(finding) {
|
|
@@ -23833,10 +24054,22 @@ var ManagedSettingKey = external_exports.enum([
|
|
|
23833
24054
|
"vaultInlineReveal",
|
|
23834
24055
|
"modelJudgeConsent",
|
|
23835
24056
|
"dataSharesInPlace",
|
|
23836
|
-
"redactFallback"
|
|
24057
|
+
"redactFallback",
|
|
24058
|
+
// Pins the toggle and the day count together — see BodyRetention on why the
|
|
24059
|
+
// two are one unit. An administrator mandating a window wants the count
|
|
24060
|
+
// enforced with it, not one a user can widen while the toggle stays on.
|
|
24061
|
+
"bodyRetention"
|
|
23837
24062
|
]).meta({ id: "ManagedSettingKey" });
|
|
24063
|
+
function isManagedSettingKey(value) {
|
|
24064
|
+
return ManagedSettingKey.safeParse(value).success;
|
|
24065
|
+
}
|
|
23838
24066
|
var ManagedSettingsValues = external_exports.object({
|
|
23839
24067
|
runMode: external_exports.enum(["standalone", "attached"]).optional(),
|
|
24068
|
+
// `controlPlane` and `bodyRetention` are the two nested values, and both are
|
|
24069
|
+
// plain, non-strict objects: a key under either that this build does not know
|
|
24070
|
+
// is stripped and nothing reports it. The unknown-value split in
|
|
24071
|
+
// ManagedSettings below classifies top-level names only, so it stops at
|
|
24072
|
+
// these boundaries.
|
|
23840
24073
|
controlPlane: external_exports.object({
|
|
23841
24074
|
endpoint: external_exports.string().min(1),
|
|
23842
24075
|
label: external_exports.string().min(1).optional()
|
|
@@ -23847,7 +24080,8 @@ var ManagedSettingsValues = external_exports.object({
|
|
|
23847
24080
|
vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
|
|
23848
24081
|
modelJudgeConsent: external_exports.boolean().optional(),
|
|
23849
24082
|
dataSharesInPlace: external_exports.boolean().optional(),
|
|
23850
|
-
redactFallback: RedactFallback.optional()
|
|
24083
|
+
redactFallback: RedactFallback.optional(),
|
|
24084
|
+
bodyRetention: BodyRetention.optional()
|
|
23851
24085
|
}).meta({ id: "ManagedSettingsValues" });
|
|
23852
24086
|
var ManagedSettings = external_exports.object({
|
|
23853
24087
|
specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
|
|
@@ -23855,11 +24089,59 @@ var ManagedSettings = external_exports.object({
|
|
|
23855
24089
|
// decision from a bug. Absent renders as a generic "your organization".
|
|
23856
24090
|
organization: external_exports.string().min(1).optional(),
|
|
23857
24091
|
// What the administrator pinned.
|
|
23858
|
-
|
|
24092
|
+
//
|
|
24093
|
+
// Parsed as a RECORD rather than as the nested schema, and split below for
|
|
24094
|
+
// the same reason `lockedFields` is parsed as names: a plain `z.object`
|
|
24095
|
+
// drops an unrecognised key and succeeds, so a pin this build does not know
|
|
24096
|
+
// vanished and nothing anywhere said so. A pin with no lock is a supported
|
|
24097
|
+
// shape — it is a DEFAULT the user may still change — so that silence hit
|
|
24098
|
+
// exactly the file an administrator is most likely to write while a fleet
|
|
24099
|
+
// is mid-upgrade.
|
|
24100
|
+
//
|
|
24101
|
+
// Splitting here rather than calling `.strict()`: strict would REFUSE the
|
|
24102
|
+
// file, which is the outcome the lock half already rejected — an older
|
|
24103
|
+
// build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
|
|
24104
|
+
// value still fails, because the nested schema is re-run over the known
|
|
24105
|
+
// subset and its issues are re-raised on this parse.
|
|
24106
|
+
values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
|
|
23859
24107
|
// Which of those the user may not change. A key here with no matching value
|
|
23860
24108
|
// freezes whatever the user last chose; a value with no lock is a DEFAULT
|
|
23861
24109
|
// the user may still override. The two are separable on purpose.
|
|
23862
|
-
|
|
24110
|
+
//
|
|
24111
|
+
// Parsed as NAMES rather than as the enum, and split below: a name this
|
|
24112
|
+
// build does not know is dropped from the locked set and reported, never a
|
|
24113
|
+
// reason to refuse the file. The same shape reaches an older build whenever
|
|
24114
|
+
// an administrator locks a key a newer build added, and refusing it there
|
|
24115
|
+
// ran that build entirely unmanaged — every pin and lock gone — on exactly
|
|
24116
|
+
// the fleets most likely to carry a version skew. A name outside the enum
|
|
24117
|
+
// is still never HONOURED: the lockable set stays explicit above.
|
|
24118
|
+
lockedFields: external_exports.array(external_exports.string()).default([])
|
|
24119
|
+
}).transform(({ lockedFields, values, ...rest }, ctx) => {
|
|
24120
|
+
const known = [];
|
|
24121
|
+
const unknown2 = [];
|
|
24122
|
+
for (const name of lockedFields) {
|
|
24123
|
+
if (isManagedSettingKey(name)) known.push(name);
|
|
24124
|
+
else unknown2.push(name);
|
|
24125
|
+
}
|
|
24126
|
+
const knownValues = /* @__PURE__ */ Object.create(null);
|
|
24127
|
+
const unknownValues = [];
|
|
24128
|
+
for (const [name, value] of Object.entries(values)) {
|
|
24129
|
+
if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
|
|
24130
|
+
else unknownValues.push(name);
|
|
24131
|
+
}
|
|
24132
|
+
const pinned = ManagedSettingsValues.safeParse(knownValues);
|
|
24133
|
+
if (!pinned.success) {
|
|
24134
|
+
for (const issue2 of pinned.error.issues)
|
|
24135
|
+
ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
|
|
24136
|
+
return external_exports.NEVER;
|
|
24137
|
+
}
|
|
24138
|
+
return {
|
|
24139
|
+
...rest,
|
|
24140
|
+
values: pinned.data,
|
|
24141
|
+
lockedFields: known,
|
|
24142
|
+
...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
|
|
24143
|
+
...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
|
|
24144
|
+
};
|
|
23863
24145
|
}).meta({ id: "ManagedSettings" });
|
|
23864
24146
|
|
|
23865
24147
|
// ../../packages/schema/src/zod/project-files.ts
|
|
@@ -23983,7 +24265,11 @@ var FindingsTimeseriesPoint = external_exports.object({
|
|
|
23983
24265
|
timestamp: external_exports.iso.date(),
|
|
23984
24266
|
critical: external_exports.number().int().nonnegative(),
|
|
23985
24267
|
high: external_exports.number().int().nonnegative(),
|
|
23986
|
-
medium: external_exports.number().int().nonnegative()
|
|
24268
|
+
medium: external_exports.number().int().nonnegative(),
|
|
24269
|
+
// Optional and additive, so a producer written against the earlier
|
|
24270
|
+
// three-series contract keeps validating. A consumer plotting it resolves the
|
|
24271
|
+
// absent case itself — the chart point requires a number.
|
|
24272
|
+
low: external_exports.number().int().nonnegative().optional()
|
|
23987
24273
|
}).meta({ id: "FindingsTimeseriesPoint" });
|
|
23988
24274
|
var FindingsTimeseriesResponse = external_exports.object({
|
|
23989
24275
|
range: TimeRange,
|
|
@@ -24009,6 +24295,10 @@ var ResolvedFeedItem = external_exports.object({
|
|
|
24009
24295
|
findingKey: external_exports.string(),
|
|
24010
24296
|
ruleId: external_exports.string(),
|
|
24011
24297
|
severity: Severity,
|
|
24298
|
+
// Repository slug, and the file path RELATIVE to it. The pair is what
|
|
24299
|
+
// identifies the file: a bare path matches the same name in every repo.
|
|
24300
|
+
// Optional and additive; empty when the event carried no repo.
|
|
24301
|
+
repo: external_exports.string().optional(),
|
|
24012
24302
|
path: external_exports.string(),
|
|
24013
24303
|
// ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
|
|
24014
24304
|
// findings domain). The reader `.toISOString()`s the DB epoch-ms values.
|
|
@@ -24114,7 +24404,23 @@ var SaveSettingsInput = external_exports.object({
|
|
|
24114
24404
|
modelJudgeConsent: ModelJudgeConsentChoice,
|
|
24115
24405
|
historySyncConsent: HistorySyncConsentChoice,
|
|
24116
24406
|
vaultConsent: external_exports.string(),
|
|
24117
|
-
vaultInlineReveal: external_exports.string()
|
|
24407
|
+
vaultInlineReveal: external_exports.string(),
|
|
24408
|
+
// Widened to `string` like its neighbours rather than typed as
|
|
24409
|
+
// `RedactFallback`, on this module's own layering rule: shape here, VALUE at
|
|
24410
|
+
// the call site, so the domain check receives the type it was written for.
|
|
24411
|
+
//
|
|
24412
|
+
// NOT because a narrower schema would reject differently. `parseActionInput`
|
|
24413
|
+
// is a `safeParse` wrapper and throws for no field schema, so either spelling
|
|
24414
|
+
// reaches a recoverable `{ ok: false }` and there is no rejected promise to
|
|
24415
|
+
// trade against. The real cost runs the other way and is the part worth
|
|
24416
|
+
// knowing: a value this schema admits and the domain enum then rejects lands
|
|
24417
|
+
// on the action's shared refusal, which names NO field, where a shape
|
|
24418
|
+
// rejection reaches `malformedInput` and names the schema key.
|
|
24419
|
+
redactFallback: external_exports.string(),
|
|
24420
|
+
// Shape only, the way the enum fields above are strings only: the RANGE is
|
|
24421
|
+
// `BodyRetention`'s and the action checks it there, so there is one place
|
|
24422
|
+
// that decides what a legal horizon is rather than two that can drift.
|
|
24423
|
+
bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
|
|
24118
24424
|
});
|
|
24119
24425
|
var AttachInput = external_exports.object({
|
|
24120
24426
|
endpoint: external_exports.string(),
|
|
@@ -24286,6 +24592,52 @@ function reviewSeverityRank(reasons) {
|
|
|
24286
24592
|
return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
|
|
24287
24593
|
}
|
|
24288
24594
|
|
|
24595
|
+
// ../../packages/schema/src/zod/web-capture.ts
|
|
24596
|
+
var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
|
|
24597
|
+
var WebUsage = external_exports.object({
|
|
24598
|
+
inputTokens: external_exports.number().int().nonnegative().optional(),
|
|
24599
|
+
outputTokens: external_exports.number().int().nonnegative().optional(),
|
|
24600
|
+
cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
|
|
24601
|
+
cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
|
|
24602
|
+
});
|
|
24603
|
+
var WebToolCall = external_exports.object({
|
|
24604
|
+
toolUseId: external_exports.string().min(1),
|
|
24605
|
+
toolName: external_exports.string().min(1),
|
|
24606
|
+
target: external_exports.string().optional(),
|
|
24607
|
+
isError: external_exports.boolean().optional(),
|
|
24608
|
+
inputSize: external_exports.number().int().nonnegative().optional(),
|
|
24609
|
+
outputSize: external_exports.number().int().nonnegative().optional()
|
|
24610
|
+
});
|
|
24611
|
+
var WebExchange = external_exports.object({
|
|
24612
|
+
messageId: external_exports.string().min(1),
|
|
24613
|
+
startedAt: external_exports.iso.datetime(),
|
|
24614
|
+
model: external_exports.string().optional(),
|
|
24615
|
+
usage: WebUsage.optional(),
|
|
24616
|
+
usageSource: WebUsageSource,
|
|
24617
|
+
stopReason: external_exports.string().optional(),
|
|
24618
|
+
conversationId: external_exports.string().optional(),
|
|
24619
|
+
turnIndex: external_exports.number().int().nonnegative().optional(),
|
|
24620
|
+
toolCalls: external_exports.array(WebToolCall).default([]),
|
|
24621
|
+
// Absent when the adapter recovered no text. Capped by the caller at
|
|
24622
|
+
// RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
|
|
24623
|
+
// short capture is never mistaken for a short reply.
|
|
24624
|
+
responseText: external_exports.string().optional(),
|
|
24625
|
+
truncated: external_exports.boolean().default(false)
|
|
24626
|
+
});
|
|
24627
|
+
var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
|
|
24628
|
+
var WebCaptureStatus = external_exports.object({
|
|
24629
|
+
patched: external_exports.boolean(),
|
|
24630
|
+
live: external_exports.boolean(),
|
|
24631
|
+
blind: external_exports.boolean(),
|
|
24632
|
+
sendsSeenDom: external_exports.number().int().nonnegative(),
|
|
24633
|
+
exchangesSeenNet: external_exports.number().int().nonnegative(),
|
|
24634
|
+
parseFailures: external_exports.number().int().nonnegative(),
|
|
24635
|
+
unparsedBodies: external_exports.number().int().nonnegative(),
|
|
24636
|
+
// The adapter-declared JSON key paths that were absent from a real payload —
|
|
24637
|
+
// the earliest signal that a site's contract moved.
|
|
24638
|
+
shapeMisses: external_exports.array(external_exports.string()).default([])
|
|
24639
|
+
});
|
|
24640
|
+
|
|
24289
24641
|
// ../../packages/persistence/src/paths.ts
|
|
24290
24642
|
import {
|
|
24291
24643
|
chmodSync,
|
|
@@ -24478,6 +24830,22 @@ function discardStore(file2, backup) {
|
|
|
24478
24830
|
}
|
|
24479
24831
|
}
|
|
24480
24832
|
|
|
24833
|
+
// ../../packages/persistence/src/internal/sql-functions.ts
|
|
24834
|
+
var utf8 = new TextDecoder();
|
|
24835
|
+
function akaLower(value) {
|
|
24836
|
+
if (value === null) return null;
|
|
24837
|
+
if (typeof value === "string") return value.toLowerCase();
|
|
24838
|
+
if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
|
|
24839
|
+
return utf8.decode(value).toLowerCase();
|
|
24840
|
+
}
|
|
24841
|
+
function registerSqlFunctions(db) {
|
|
24842
|
+
db.function(
|
|
24843
|
+
"aka_lower",
|
|
24844
|
+
{ deterministic: true, directOnly: true, useBigIntArguments: true },
|
|
24845
|
+
akaLower
|
|
24846
|
+
);
|
|
24847
|
+
}
|
|
24848
|
+
|
|
24481
24849
|
// ../../packages/persistence/src/internal/sql-text.ts
|
|
24482
24850
|
function escapeLikePattern(s) {
|
|
24483
24851
|
return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
|
|
@@ -24562,6 +24930,11 @@ function schemaObjectExists(db, kind, name) {
|
|
|
24562
24930
|
function indexExists(db, name) {
|
|
24563
24931
|
return schemaObjectExists(db, "index", name);
|
|
24564
24932
|
}
|
|
24933
|
+
function indexColumns(db, name) {
|
|
24934
|
+
if (!indexExists(db, name)) return [];
|
|
24935
|
+
const columns = db.prepare(`PRAGMA index_info(${name})`).all();
|
|
24936
|
+
return columns.map((c) => c.name).filter((c) => c !== null);
|
|
24937
|
+
}
|
|
24565
24938
|
function columnNames(db, table2, opts) {
|
|
24566
24939
|
const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
|
|
24567
24940
|
const columns = db.prepare(`PRAGMA ${pragma}(${table2})`).all();
|
|
@@ -24623,6 +24996,647 @@ function mapRowsTolerant(rows, map2) {
|
|
|
24623
24996
|
return out;
|
|
24624
24997
|
}
|
|
24625
24998
|
|
|
24999
|
+
// ../../packages/persistence/src/internal/outbox-lane.ts
|
|
25000
|
+
var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
|
|
25001
|
+
var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
25002
|
+
|
|
25003
|
+
// ../../packages/persistence/src/sync-failure.ts
|
|
25004
|
+
var SYNC_FAILURE_REASONS = SyncFailureReason.options;
|
|
25005
|
+
function syncFailureRejectCondition(column = "sync_failure") {
|
|
25006
|
+
const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
|
|
25007
|
+
return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
|
|
25008
|
+
}
|
|
25009
|
+
|
|
25010
|
+
// ../../packages/persistence/src/repositories/history-sync.ts
|
|
25011
|
+
var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
|
|
25012
|
+
var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
25013
|
+
var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
|
|
25014
|
+
var COUNTED_EVENT_TYPES = [
|
|
25015
|
+
...STRUCTURAL_EVENT_TYPES,
|
|
25016
|
+
...OUTBOX_CAPTURE_EVENT_TYPES
|
|
25017
|
+
];
|
|
25018
|
+
var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
25019
|
+
var PARTITION_BUCKETS = `
|
|
25020
|
+
SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
|
|
25021
|
+
SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
|
|
25022
|
+
SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
|
|
25023
|
+
SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
|
|
25024
|
+
AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
|
|
25025
|
+
SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
|
|
25026
|
+
AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
|
|
25027
|
+
-- Spelled as what it INCLUDES rather than what it excludes, so a reason
|
|
25028
|
+
-- added later lands in no bucket and fails the sum assertion, instead
|
|
25029
|
+
-- of silently joining this one.
|
|
25030
|
+
SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
|
|
25031
|
+
AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
|
|
25032
|
+
THEN 1 ELSE 0 END) AS failed,
|
|
25033
|
+
COUNT(*) AS total`;
|
|
25034
|
+
var COUNTED_SCOPE = `
|
|
25035
|
+
WHERE event_type IN (${COUNTED_TYPE_LIST})
|
|
25036
|
+
AND (
|
|
25037
|
+
event_type IN (${TYPE_LIST})
|
|
25038
|
+
OR synced_at IS NOT NULL
|
|
25039
|
+
OR outbox_owed = 1
|
|
25040
|
+
)`;
|
|
25041
|
+
var SKIPPED = -1;
|
|
25042
|
+
var ROW_COLUMNS = `id,
|
|
25043
|
+
parent_id AS parentId,
|
|
25044
|
+
root_session_id AS rootSessionId,
|
|
25045
|
+
event_type AS eventType,
|
|
25046
|
+
host_id AS hostId,
|
|
25047
|
+
harness_id AS harnessId,
|
|
25048
|
+
source_project_id AS sourceProjectId,
|
|
25049
|
+
started_at AS startedAt,
|
|
25050
|
+
ended_at AS endedAt,
|
|
25051
|
+
severity,
|
|
25052
|
+
priority,
|
|
25053
|
+
content,
|
|
25054
|
+
content_hash AS contentHash,
|
|
25055
|
+
attributes`;
|
|
25056
|
+
var SqliteHistorySyncRepository = class {
|
|
25057
|
+
constructor(db) {
|
|
25058
|
+
this.db = db;
|
|
25059
|
+
this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
|
|
25060
|
+
this.sessionsStmt = db.prepare(
|
|
25061
|
+
`SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
|
|
25062
|
+
FROM audit_events
|
|
25063
|
+
WHERE synced_at IS NULL
|
|
25064
|
+
AND event_type IN (${TYPE_LIST})
|
|
25065
|
+
AND started_at < :before
|
|
25066
|
+
GROUP BY sessionId
|
|
25067
|
+
ORDER BY earliest
|
|
25068
|
+
LIMIT :limit`
|
|
25069
|
+
);
|
|
25070
|
+
this.rowsStmt = db.prepare(
|
|
25071
|
+
`SELECT ${ROW_COLUMNS}
|
|
25072
|
+
FROM audit_events
|
|
25073
|
+
WHERE synced_at IS NULL
|
|
25074
|
+
AND event_type IN (${TYPE_LIST})
|
|
25075
|
+
AND started_at < :before
|
|
25076
|
+
AND COALESCE(root_session_id, id) = :sessionId
|
|
25077
|
+
ORDER BY (event_type = 'session') DESC, started_at
|
|
25078
|
+
LIMIT :limit`
|
|
25079
|
+
);
|
|
25080
|
+
this.captureRowsStmt = db.prepare(
|
|
25081
|
+
`SELECT ${ROW_COLUMNS}
|
|
25082
|
+
FROM audit_events
|
|
25083
|
+
WHERE synced_at IS NULL
|
|
25084
|
+
AND sync_claimed_at IS NULL
|
|
25085
|
+
AND outbox_owed = 1
|
|
25086
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})
|
|
25087
|
+
AND started_at < :before
|
|
25088
|
+
ORDER BY started_at
|
|
25089
|
+
LIMIT :limit`
|
|
25090
|
+
);
|
|
25091
|
+
this.markOwedStmt = db.prepare(
|
|
25092
|
+
`UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
|
|
25093
|
+
);
|
|
25094
|
+
this.markCaptureBacklogOwedStmt = db.prepare(
|
|
25095
|
+
`UPDATE audit_events SET outbox_owed = 1
|
|
25096
|
+
WHERE synced_at IS NULL
|
|
25097
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})
|
|
25098
|
+
AND started_at < :before`
|
|
25099
|
+
);
|
|
25100
|
+
this.stampStmt = db.prepare(
|
|
25101
|
+
`UPDATE audit_events
|
|
25102
|
+
SET synced_at = :at,
|
|
25103
|
+
sync_claimed_at = NULL,
|
|
25104
|
+
sync_failed_at = :failedAt,
|
|
25105
|
+
sync_failure = :failure
|
|
25106
|
+
WHERE id = :id`
|
|
25107
|
+
);
|
|
25108
|
+
this.claimRowStmt = db.prepare(
|
|
25109
|
+
`UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
|
|
25110
|
+
);
|
|
25111
|
+
this.releaseRowStmt = db.prepare(
|
|
25112
|
+
`UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
|
|
25113
|
+
);
|
|
25114
|
+
this.releaseStaleClaimsStmt = db.prepare(
|
|
25115
|
+
`UPDATE audit_events SET sync_claimed_at = NULL
|
|
25116
|
+
WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
|
|
25117
|
+
);
|
|
25118
|
+
this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
|
|
25119
|
+
FROM audit_events${COUNTED_SCOPE}`);
|
|
25120
|
+
this.partitionByKindStmt = db.prepare(
|
|
25121
|
+
`SELECT event_type AS kind,${PARTITION_BUCKETS}
|
|
25122
|
+
FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
|
|
25123
|
+
GROUP BY event_type`
|
|
25124
|
+
);
|
|
25125
|
+
this.countsStmt = db.prepare(
|
|
25126
|
+
`SELECT
|
|
25127
|
+
SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
|
|
25128
|
+
SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
|
|
25129
|
+
SUM(CASE WHEN synced_at = ${String(SKIPPED)}
|
|
25130
|
+
AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
|
|
25131
|
+
THEN 1 ELSE 0 END) AS skipped,
|
|
25132
|
+
SUM(CASE WHEN synced_at = ${String(SKIPPED)}
|
|
25133
|
+
AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
|
|
25134
|
+
SUM(CASE WHEN synced_at = ${String(SKIPPED)}
|
|
25135
|
+
AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
|
|
25136
|
+
FROM audit_events
|
|
25137
|
+
WHERE event_type IN (${TYPE_LIST})`
|
|
25138
|
+
);
|
|
25139
|
+
this.captureSkipCountStmt = db.prepare(
|
|
25140
|
+
// EVERY sentinel capture, whatever the reason — deliberately NOT split the
|
|
25141
|
+
// way the structural totals are. The split exists because a refusal is
|
|
25142
|
+
// terminal only against the deployment that gave it, and the structural
|
|
25143
|
+
// re-arm frees it on a change of deployment. The capture lane has no such
|
|
25144
|
+
// escape: re-arming a capture would offer one deployment's undelivered
|
|
25145
|
+
// prompts, with their text, to a deployment that never saw them, which is
|
|
25146
|
+
// exactly what disownCapturesStmt exists to prevent. So on this lane both
|
|
25147
|
+
// reasons mean the same thing — this row will not be sent — and splitting
|
|
25148
|
+
// them would put refused captures in a bucket nothing reads and nothing
|
|
25149
|
+
// frees.
|
|
25150
|
+
`SELECT COUNT(*) AS skipped
|
|
25151
|
+
FROM audit_events
|
|
25152
|
+
WHERE synced_at = ${String(SKIPPED)}
|
|
25153
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})`
|
|
25154
|
+
);
|
|
25155
|
+
this.fingerprintStmt = db.prepare(
|
|
25156
|
+
`SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
|
|
25157
|
+
FROM history_sync WHERE id = 1`
|
|
25158
|
+
);
|
|
25159
|
+
this.setFingerprintStmt = db.prepare(
|
|
25160
|
+
`UPDATE history_sync
|
|
25161
|
+
SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
|
|
25162
|
+
WHERE id = 1`
|
|
25163
|
+
);
|
|
25164
|
+
this.disownCapturesStmt = db.prepare(
|
|
25165
|
+
`UPDATE audit_events SET outbox_owed = NULL
|
|
25166
|
+
WHERE outbox_owed IS NOT NULL
|
|
25167
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})
|
|
25168
|
+
AND started_at < :attachedAt`
|
|
25169
|
+
);
|
|
25170
|
+
this.rearmStmt = db.prepare(
|
|
25171
|
+
`UPDATE audit_events
|
|
25172
|
+
SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
|
|
25173
|
+
WHERE (synced_at > 0
|
|
25174
|
+
OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
|
|
25175
|
+
AND event_type IN (${TYPE_LIST})`
|
|
25176
|
+
);
|
|
25177
|
+
this.claimStmt = db.prepare(
|
|
25178
|
+
`UPDATE history_sync
|
|
25179
|
+
SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
|
|
25180
|
+
WHERE id = 1
|
|
25181
|
+
AND (owner_pid IS NULL
|
|
25182
|
+
OR heartbeat_at IS NULL
|
|
25183
|
+
OR heartbeat_at < :staleBefore
|
|
25184
|
+
OR heartbeat_at > :now)`
|
|
25185
|
+
);
|
|
25186
|
+
this.heartbeatStmt = db.prepare(
|
|
25187
|
+
`UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
|
|
25188
|
+
);
|
|
25189
|
+
this.releaseStmt = db.prepare(
|
|
25190
|
+
`UPDATE history_sync
|
|
25191
|
+
SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
|
|
25192
|
+
WHERE id = 1 AND owner_pid = :pid`
|
|
25193
|
+
);
|
|
25194
|
+
this.closeWindowStmt = db.prepare(
|
|
25195
|
+
`UPDATE audit_events
|
|
25196
|
+
SET synced_at = ${String(SKIPPED)},
|
|
25197
|
+
sync_failed_at = :at,
|
|
25198
|
+
sync_failure = 'detached_undelivered'
|
|
25199
|
+
WHERE synced_at IS NULL
|
|
25200
|
+
AND event_type IN (${TYPE_LIST})
|
|
25201
|
+
AND started_at >= :attachedAt`
|
|
25202
|
+
);
|
|
25203
|
+
this.releaseBoundaryStmt = db.prepare(
|
|
25204
|
+
`UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
|
|
25205
|
+
);
|
|
25206
|
+
this.freezeBoundaryStmt = db.prepare(
|
|
25207
|
+
`UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
|
|
25208
|
+
);
|
|
25209
|
+
this.leaseStmt = db.prepare(
|
|
25210
|
+
`SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
|
|
25211
|
+
acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
|
|
25212
|
+
FROM history_sync WHERE id = 1`
|
|
25213
|
+
);
|
|
25214
|
+
this.inspectionsStmt = db.prepare(
|
|
25215
|
+
`SELECT d.rule_id AS ruleId,
|
|
25216
|
+
d.name AS ruleName,
|
|
25217
|
+
d.version AS ruleVersion,
|
|
25218
|
+
d.category AS category,
|
|
25219
|
+
d.severity AS severity,
|
|
25220
|
+
f.span_start AS spanStart,
|
|
25221
|
+
f.span_end AS spanEnd,
|
|
25222
|
+
f.masked_match AS maskedMatch,
|
|
25223
|
+
f.action_taken AS actionTaken,
|
|
25224
|
+
f.confidence AS confidence
|
|
25225
|
+
FROM inspection_findings f
|
|
25226
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
25227
|
+
WHERE f.audit_event_id = :auditEventId
|
|
25228
|
+
ORDER BY f.span_start, f.id`
|
|
25229
|
+
);
|
|
25230
|
+
}
|
|
25231
|
+
db;
|
|
25232
|
+
ensureRowStmt;
|
|
25233
|
+
sessionsStmt;
|
|
25234
|
+
rowsStmt;
|
|
25235
|
+
stampStmt;
|
|
25236
|
+
countsStmt;
|
|
25237
|
+
fingerprintStmt;
|
|
25238
|
+
setFingerprintStmt;
|
|
25239
|
+
rearmStmt;
|
|
25240
|
+
claimStmt;
|
|
25241
|
+
heartbeatStmt;
|
|
25242
|
+
releaseStmt;
|
|
25243
|
+
leaseStmt;
|
|
25244
|
+
inspectionsStmt;
|
|
25245
|
+
closeWindowStmt;
|
|
25246
|
+
releaseBoundaryStmt;
|
|
25247
|
+
freezeBoundaryStmt;
|
|
25248
|
+
captureRowsStmt;
|
|
25249
|
+
markOwedStmt;
|
|
25250
|
+
markCaptureBacklogOwedStmt;
|
|
25251
|
+
captureSkipCountStmt;
|
|
25252
|
+
disownCapturesStmt;
|
|
25253
|
+
partitionStmt;
|
|
25254
|
+
partitionByKindStmt;
|
|
25255
|
+
claimRowStmt;
|
|
25256
|
+
releaseRowStmt;
|
|
25257
|
+
releaseStaleClaimsStmt;
|
|
25258
|
+
/**
|
|
25259
|
+
* The masked detections recorded against one tool call.
|
|
25260
|
+
*
|
|
25261
|
+
* These travel with the event because a tool call's target is not
|
|
25262
|
+
* re-inspectable from the event alone — unlike a capture, where the text
|
|
25263
|
+
* itself is re-scannable. What crosses is the masked match and the rule that
|
|
25264
|
+
* produced it, never the value.
|
|
25265
|
+
*/
|
|
25266
|
+
inspectionsFor(auditEventId) {
|
|
25267
|
+
return allRows(this.inspectionsStmt, { auditEventId });
|
|
25268
|
+
}
|
|
25269
|
+
/**
|
|
25270
|
+
* Sessions with structural rows still to send, oldest first.
|
|
25271
|
+
*
|
|
25272
|
+
* BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
|
|
25273
|
+
* read. Anything recorded after the machine attached is the live forward
|
|
25274
|
+
* path's to deliver; this drain exists for what was recorded before it, and a
|
|
25275
|
+
* row both paths send is at best a duplicate request and at worst — for a
|
|
25276
|
+
* session root — an overwrite of the inventory ids the live path resolved.
|
|
25277
|
+
*/
|
|
25278
|
+
pendingSessions(limit, before) {
|
|
25279
|
+
return allRows(this.sessionsStmt, { limit, before }).map(
|
|
25280
|
+
(r) => r.sessionId
|
|
25281
|
+
);
|
|
25282
|
+
}
|
|
25283
|
+
/** One session's undelivered structural rows within the backlog, root first. */
|
|
25284
|
+
pendingRows(sessionId, limit, before) {
|
|
25285
|
+
return allRows(this.rowsStmt, { sessionId, limit, before });
|
|
25286
|
+
}
|
|
25287
|
+
/**
|
|
25288
|
+
* Captures this machine still owes the deployment, oldest first.
|
|
25289
|
+
*
|
|
25290
|
+
* Selected by the `outbox_owed` marker the attached forward path writes, not
|
|
25291
|
+
* by a time window — see captureRowsStmt for why a window could not express
|
|
25292
|
+
* this. `before` is the grace window that leaves a just-recorded capture to
|
|
25293
|
+
* the live path.
|
|
25294
|
+
*/
|
|
25295
|
+
pendingCaptureRows(limit, before) {
|
|
25296
|
+
return allRows(this.captureRowsStmt, { limit, before });
|
|
25297
|
+
}
|
|
25298
|
+
/**
|
|
25299
|
+
* Record that a capture is OWED to the deployment.
|
|
25300
|
+
*
|
|
25301
|
+
* Written by the attached forward path when a live send did not confirm
|
|
25302
|
+
* delivery, and read by the drain as the whole of its eligibility test. It is
|
|
25303
|
+
* a fact rather than an inference: the machine was attached, the send did not
|
|
25304
|
+
* land, so the row is owed — which no time window can state, because the same
|
|
25305
|
+
* window that holds the rows a past attachment left owed also holds every
|
|
25306
|
+
* capture recorded while the machine was DETACHED, and those were never
|
|
25307
|
+
* offered to anyone.
|
|
25308
|
+
*
|
|
25309
|
+
* Idempotent, and never un-set: `markSynced` settling the row is what takes it
|
|
25310
|
+
* out of the drain's read.
|
|
25311
|
+
*/
|
|
25312
|
+
markCaptureOwed(id) {
|
|
25313
|
+
this.markOwedStmt.run({ id });
|
|
25314
|
+
}
|
|
25315
|
+
/**
|
|
25316
|
+
* Mark every capture already on disk as owed, as of `before`.
|
|
25317
|
+
*
|
|
25318
|
+
* The consent-time backfill, called once from `aka attach` when a human
|
|
25319
|
+
* grants existing-history consent — never from an ongoing drain pass, and
|
|
25320
|
+
* never inferred from a boundary that could later move. `before` is the
|
|
25321
|
+
* caller's own "now" at the moment consent was granted, so what this marks
|
|
25322
|
+
* is exactly the backlog the consent prompt already counted, not whatever a
|
|
25323
|
+
* later re-attach or key rotation might widen it to.
|
|
25324
|
+
*
|
|
25325
|
+
* Returns how many rows matched, for the caller to log or test against. Not a
|
|
25326
|
+
* count of NEWLY marked rows — a row still unsynced from an earlier call
|
|
25327
|
+
* matches again and is counted again, the same as `UPDATE`'s own `changes`.
|
|
25328
|
+
*/
|
|
25329
|
+
markCaptureBacklogOwed(before) {
|
|
25330
|
+
return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
|
|
25331
|
+
}
|
|
25332
|
+
/**
|
|
25333
|
+
* Record delivery. Called only AFTER the far side has accepted the rows.
|
|
25334
|
+
*
|
|
25335
|
+
* CLEARS any failure reason in the same statement. A row that failed against
|
|
25336
|
+
* one deployment and then landed is delivered, and leaving the reason behind
|
|
25337
|
+
* would leave the store holding two contradictory answers about one row —
|
|
25338
|
+
* with the surface free to render either.
|
|
25339
|
+
*/
|
|
25340
|
+
markSynced(ids, atMs) {
|
|
25341
|
+
this.stampAll(ids, atMs, null);
|
|
25342
|
+
}
|
|
25343
|
+
/**
|
|
25344
|
+
* Record that THIS MACHINE cannot express the row on the wire.
|
|
25345
|
+
*
|
|
25346
|
+
* Reserved for a local defect — a row that cannot be rebuilt into a valid
|
|
25347
|
+
* payload, or a body the client itself refused to send. It fails identically
|
|
25348
|
+
* against every deployment, so it is terminal everywhere and the re-arm leaves
|
|
25349
|
+
* it alone. A row that merely failed to REACH the deployment stays NULL, so it
|
|
25350
|
+
* is retried; marking those would turn one outage into permanent data loss.
|
|
25351
|
+
*/
|
|
25352
|
+
markSkipped(ids, atMs) {
|
|
25353
|
+
this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
|
|
25354
|
+
}
|
|
25355
|
+
/**
|
|
25356
|
+
* Record that THIS DEPLOYMENT refused the row.
|
|
25357
|
+
*
|
|
25358
|
+
* The same sentinel as `markSkipped`, and deliberately so: both stop the row
|
|
25359
|
+
* being re-offered on this lane, and `synced_at` goes on answering whether a
|
|
25360
|
+
* row is outstanding rather than why. What separates them is the reason, and
|
|
25361
|
+
* what the reason buys is the re-arm — a refusal is one deployment's verdict
|
|
25362
|
+
* on one body, so it is terminal only for as long as this machine points at
|
|
25363
|
+
* that deployment, and `rearmFor` clears it when the deployment changes.
|
|
25364
|
+
*
|
|
25365
|
+
* Leaving such a row NULL instead would be worse than the loss it replaces:
|
|
25366
|
+
* these reads carry no cursor, so an unstamped row the deployment refuses is
|
|
25367
|
+
* the head of every subsequent page, and the lane stalls behind it for ever.
|
|
25368
|
+
*/
|
|
25369
|
+
markRefused(ids, atMs) {
|
|
25370
|
+
this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
|
|
25371
|
+
}
|
|
25372
|
+
eachInTransaction(ids, run) {
|
|
25373
|
+
if (ids.length === 0) return;
|
|
25374
|
+
withTransaction(
|
|
25375
|
+
this.db,
|
|
25376
|
+
() => {
|
|
25377
|
+
for (const id of ids) run(id);
|
|
25378
|
+
},
|
|
25379
|
+
"IMMEDIATE"
|
|
25380
|
+
);
|
|
25381
|
+
}
|
|
25382
|
+
stampAll(ids, value, failure, failedAtMs) {
|
|
25383
|
+
if (ids.length === 0) return;
|
|
25384
|
+
const failedAt = failure === null ? null : failedAtMs ?? null;
|
|
25385
|
+
withTransaction(
|
|
25386
|
+
this.db,
|
|
25387
|
+
() => {
|
|
25388
|
+
for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
|
|
25389
|
+
},
|
|
25390
|
+
"IMMEDIATE"
|
|
25391
|
+
);
|
|
25392
|
+
}
|
|
25393
|
+
/**
|
|
25394
|
+
* Claim rows as in-flight.
|
|
25395
|
+
*
|
|
25396
|
+
* Advisory in exactly the sense the lease is: it records that a send is in
|
|
25397
|
+
* progress so a surface can say so, and a lost claim costs a row showing as
|
|
25398
|
+
* queued while it is actually being sent. It is not exclusion — the far side
|
|
25399
|
+
* settles a duplicate on the row id.
|
|
25400
|
+
*/
|
|
25401
|
+
claimRows(ids, atMs) {
|
|
25402
|
+
this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
|
|
25403
|
+
}
|
|
25404
|
+
/** Give back a claim without settling — the send failed, the row is queued again. */
|
|
25405
|
+
releaseRows(ids) {
|
|
25406
|
+
this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
|
|
25407
|
+
}
|
|
25408
|
+
/**
|
|
25409
|
+
* Clear claims older than `staleBefore`, and report how many were cleared.
|
|
25410
|
+
*
|
|
25411
|
+
* A process killed between claiming and settling leaves rows claimed with
|
|
25412
|
+
* nothing left to settle them. Without this they read as "sending" for ever.
|
|
25413
|
+
*/
|
|
25414
|
+
releaseStaleClaims(staleBefore) {
|
|
25415
|
+
return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
|
|
25416
|
+
}
|
|
25417
|
+
/**
|
|
25418
|
+
* Every tracked row in exactly one delivery state.
|
|
25419
|
+
*
|
|
25420
|
+
* Takes no boundary on purpose. The boundary answers "what should the drain
|
|
25421
|
+
* pick up now", which is a different question from "what state is this row
|
|
25422
|
+
* in" — and a machine that has never attached has no boundary to pass, so
|
|
25423
|
+
* requiring one would force a caller to invent one and report the whole store
|
|
25424
|
+
* as queued.
|
|
25425
|
+
*/
|
|
25426
|
+
/**
|
|
25427
|
+
* The same partition, one row per kind that a lane carries.
|
|
25428
|
+
*
|
|
25429
|
+
* A kind with nothing to report is ABSENT rather than a row of zeros: the
|
|
25430
|
+
* scope decides which rows exist at all, so a kind that has never been
|
|
25431
|
+
* recorded — or whose captures nobody ever owed — produces no group. A caller
|
|
25432
|
+
* rendering a fixed list of kinds must therefore treat a missing one as "no
|
|
25433
|
+
* rows", never as "zero sent"; the two look identical in a bar and mean
|
|
25434
|
+
* different things.
|
|
25435
|
+
*/
|
|
25436
|
+
partitionByKind() {
|
|
25437
|
+
return allRows(
|
|
25438
|
+
this.partitionByKindStmt,
|
|
25439
|
+
{}
|
|
25440
|
+
).map((row) => ({
|
|
25441
|
+
kind: row.kind,
|
|
25442
|
+
queued: row.queued ?? 0,
|
|
25443
|
+
inProgress: row.inProgress ?? 0,
|
|
25444
|
+
synced: row.synced ?? 0,
|
|
25445
|
+
failed: row.failed ?? 0,
|
|
25446
|
+
refused: row.refused ?? 0,
|
|
25447
|
+
detached: row.detached ?? 0,
|
|
25448
|
+
total: row.total ?? 0
|
|
25449
|
+
}));
|
|
25450
|
+
}
|
|
25451
|
+
partition() {
|
|
25452
|
+
const row = getRow(this.partitionStmt, {});
|
|
25453
|
+
return {
|
|
25454
|
+
queued: row?.queued ?? 0,
|
|
25455
|
+
inProgress: row?.inProgress ?? 0,
|
|
25456
|
+
synced: row?.synced ?? 0,
|
|
25457
|
+
failed: row?.failed ?? 0,
|
|
25458
|
+
refused: row?.refused ?? 0,
|
|
25459
|
+
detached: row?.detached ?? 0,
|
|
25460
|
+
total: row?.total ?? 0
|
|
25461
|
+
};
|
|
25462
|
+
}
|
|
25463
|
+
/** `pending` counts only what is inside the backlog; sent and skipped are totals. */
|
|
25464
|
+
counts(before) {
|
|
25465
|
+
const row = getRow(this.countsStmt, { before });
|
|
25466
|
+
const captures = getRow(this.captureSkipCountStmt);
|
|
25467
|
+
return {
|
|
25468
|
+
pending: row?.pending ?? 0,
|
|
25469
|
+
sent: row?.sent ?? 0,
|
|
25470
|
+
skipped: row?.skipped ?? 0,
|
|
25471
|
+
refused: row?.refused ?? 0,
|
|
25472
|
+
detached: row?.detached ?? 0,
|
|
25473
|
+
capturesSkipped: captures?.skipped ?? 0
|
|
25474
|
+
};
|
|
25475
|
+
}
|
|
25476
|
+
/**
|
|
25477
|
+
* The deployment the current stamps were made against, and where its backlog
|
|
25478
|
+
* ends.
|
|
25479
|
+
*
|
|
25480
|
+
* READ-ONLY. An absent row reads as an absent deployment, which is what a
|
|
25481
|
+
* machine that has never drained is — and every writer below seeds the row
|
|
25482
|
+
* before it needs one, so nothing depends on this creating it. Keeping the
|
|
25483
|
+
* write off the gate path matters because the gate runs on every pass while a
|
|
25484
|
+
* write has to take the database's write lock.
|
|
25485
|
+
*/
|
|
25486
|
+
deployment() {
|
|
25487
|
+
const row = getRow(
|
|
25488
|
+
this.fingerprintStmt
|
|
25489
|
+
);
|
|
25490
|
+
return {
|
|
25491
|
+
fingerprint: row?.fingerprint ?? void 0,
|
|
25492
|
+
backlogBefore: row?.backlogBefore ?? void 0
|
|
25493
|
+
};
|
|
25494
|
+
}
|
|
25495
|
+
/**
|
|
25496
|
+
* Point the ledger at a different deployment, discarding what it recorded
|
|
25497
|
+
* about the previous one.
|
|
25498
|
+
*
|
|
25499
|
+
* Delivery is a fact about ONE recipient: rows sent to the deployment a
|
|
25500
|
+
* machine has just left are undelivered as far as the new one is concerned.
|
|
25501
|
+
* All four in one transaction, so a crash between them cannot leave stamps
|
|
25502
|
+
* attributed to the wrong deployment, a boundary that belongs to another, or
|
|
25503
|
+
* a disown with no re-mark to follow it.
|
|
25504
|
+
*
|
|
25505
|
+
* The boundary is written HERE and only here, which is what freezes it: a
|
|
25506
|
+
* re-attach to the SAME deployment (a key rotation) leaves the fingerprint
|
|
25507
|
+
* unchanged, so this never runs and the backlog does not widen back over rows
|
|
25508
|
+
* the live path has since delivered.
|
|
25509
|
+
*
|
|
25510
|
+
* `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
|
|
25511
|
+
* granted existing-history consent for the deployment this call is arming —
|
|
25512
|
+
* a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
|
|
25513
|
+
* instant, `backlogBefore` is the ATTACH instant, and the two can be far
|
|
25514
|
+
* apart. Passed only when that grant is valid, since this method has no way
|
|
25515
|
+
* to check consent itself and must not mark a row owed for a machine that
|
|
25516
|
+
* never agreed to it. Applied AFTER the disown above, in the SAME
|
|
25517
|
+
* transaction: what the disown clears is every marker below `backlogBefore`,
|
|
25518
|
+
* which includes this deployment's OWN pre-attach rows — `aka attach` calls
|
|
25519
|
+
* `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
|
|
25520
|
+
* on the cleared side of that bound — and the re-mark in the same
|
|
25521
|
+
* transaction is what puts those rows back. A crash between the two cannot
|
|
25522
|
+
* strand the ledger disowned with nothing re-marked — the transaction either
|
|
25523
|
+
* lands whole or not at all, and a fingerprint mismatch that has not yet
|
|
25524
|
+
* committed re-enters this method on the very next pass. Omit it (the
|
|
25525
|
+
* structural-only tests do) to exercise the disown in isolation.
|
|
25526
|
+
*
|
|
25527
|
+
* The disown is bounded by `backlogBefore`, which is what keeps it from
|
|
25528
|
+
* touching a marker the NEW deployment's OWN live path has already set: B's
|
|
25529
|
+
* live path can mark a capture owed from the moment `aka attach` writes the
|
|
25530
|
+
* descriptor, before the drain's first pass ever reaches this method, and
|
|
25531
|
+
* such a row sits at or after the bound rather than below it. What keeps the
|
|
25532
|
+
* disown from eating THIS SAME CALL's own re-mark is the order, not the
|
|
25533
|
+
* bound — disown runs first, re-mark second, both inside the one
|
|
25534
|
+
* transaction above.
|
|
25535
|
+
*/
|
|
25536
|
+
rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
|
|
25537
|
+
this.ensureRowStmt.run();
|
|
25538
|
+
withTransaction(
|
|
25539
|
+
this.db,
|
|
25540
|
+
() => {
|
|
25541
|
+
const previous = getRow(this.fingerprintStmt)?.fingerprint;
|
|
25542
|
+
this.rearmStmt.run();
|
|
25543
|
+
if (previous !== null && previous !== void 0 && previous !== fingerprint) {
|
|
25544
|
+
this.disownCapturesStmt.run({ attachedAt: backlogBefore });
|
|
25545
|
+
}
|
|
25546
|
+
if (backfillCapturesBefore !== void 0) {
|
|
25547
|
+
this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
|
|
25548
|
+
}
|
|
25549
|
+
this.setFingerprintStmt.run({ fingerprint, backlogBefore });
|
|
25550
|
+
},
|
|
25551
|
+
"IMMEDIATE"
|
|
25552
|
+
);
|
|
25553
|
+
}
|
|
25554
|
+
/**
|
|
25555
|
+
* End the attached period: hand its rows to the live path, and release the
|
|
25556
|
+
* boundary so the next attachment can freeze a new one.
|
|
25557
|
+
*
|
|
25558
|
+
* WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
|
|
25559
|
+
* nothing delivers. The fingerprint is unchanged, so the boundary is never
|
|
25560
|
+
* re-frozen and stays at the FIRST attachment — while nothing forwards at all
|
|
25561
|
+
* during the detached period, because the machine is not attached. Rows
|
|
25562
|
+
* recorded in that window sit after the boundary and before the re-attach, so
|
|
25563
|
+
* neither path takes them, and the pending count reports none outstanding.
|
|
25564
|
+
*
|
|
25565
|
+
* WHAT IT RECORDS, and what it deliberately does not. These rows were the
|
|
25566
|
+
* closing attachment's to deliver and are no longer outstanding — that is what
|
|
25567
|
+
* lets the boundary move. It is NOT a claim that any of them arrived, and the
|
|
25568
|
+
* distinction is not academic: this used to write a delivery TIME, which every
|
|
25569
|
+
* read treats as delivery, so one detach turned a window of undelivered rows
|
|
25570
|
+
* into a window of delivered ones and no surface could tell. It writes the
|
|
25571
|
+
* skip sentinel and a reason of its own instead, so "no longer owed" and
|
|
25572
|
+
* "received" stop being the same fact.
|
|
25573
|
+
*
|
|
25574
|
+
* A change of deployment still frees them (see the re-arm), because the next
|
|
25575
|
+
* deployment has seen none of this machine's history — so the rows reach it
|
|
25576
|
+
* exactly as they did when this wrote a delivery time.
|
|
25577
|
+
*
|
|
25578
|
+
* ONE TRANSACTION, so a crash cannot release the boundary while leaving the
|
|
25579
|
+
* window unstamped — that half-state would re-send the whole attached period
|
|
25580
|
+
* on the next attach, which is the failure the boundary exists to prevent.
|
|
25581
|
+
*/
|
|
25582
|
+
closeAttachedWindow(attachedAtMs, atMs) {
|
|
25583
|
+
this.ensureRowStmt.run();
|
|
25584
|
+
withTransaction(
|
|
25585
|
+
this.db,
|
|
25586
|
+
() => {
|
|
25587
|
+
const row = getRow(this.fingerprintStmt);
|
|
25588
|
+
const from = row?.backlogBefore ?? attachedAtMs;
|
|
25589
|
+
this.closeWindowStmt.run({ at: atMs, attachedAt: from });
|
|
25590
|
+
this.releaseBoundaryStmt.run();
|
|
25591
|
+
},
|
|
25592
|
+
"IMMEDIATE"
|
|
25593
|
+
);
|
|
25594
|
+
}
|
|
25595
|
+
/**
|
|
25596
|
+
* Freeze a boundary for the deployment already on file, KEEPING the stamps.
|
|
25597
|
+
*
|
|
25598
|
+
* The re-attach half of the above. Distinct from `rearmFor`, which is for a
|
|
25599
|
+
* different deployment and therefore discards what was delivered to the old
|
|
25600
|
+
* one: here the recipient is the same, so everything already sent to it stays
|
|
25601
|
+
* sent.
|
|
25602
|
+
*/
|
|
25603
|
+
freezeBoundary(backlogBefore) {
|
|
25604
|
+
this.ensureRowStmt.run();
|
|
25605
|
+
this.freezeBoundaryStmt.run({ backlogBefore });
|
|
25606
|
+
}
|
|
25607
|
+
/** Take the claim, or report that someone live already holds it. */
|
|
25608
|
+
claim(pid, host, nowMs, staleAfterMs) {
|
|
25609
|
+
this.ensureRowStmt.run();
|
|
25610
|
+
let taken = false;
|
|
25611
|
+
withTransaction(
|
|
25612
|
+
this.db,
|
|
25613
|
+
() => {
|
|
25614
|
+
const result = this.claimStmt.run({
|
|
25615
|
+
pid,
|
|
25616
|
+
host,
|
|
25617
|
+
now: nowMs,
|
|
25618
|
+
staleBefore: nowMs - staleAfterMs
|
|
25619
|
+
});
|
|
25620
|
+
taken = result.changes === 1;
|
|
25621
|
+
},
|
|
25622
|
+
"IMMEDIATE"
|
|
25623
|
+
);
|
|
25624
|
+
return taken;
|
|
25625
|
+
}
|
|
25626
|
+
/** Say the holder is still alive. A no-op once the claim has moved on. */
|
|
25627
|
+
heartbeat(pid, nowMs) {
|
|
25628
|
+
this.heartbeatStmt.run({ now: nowMs, pid });
|
|
25629
|
+
}
|
|
25630
|
+
/** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
|
|
25631
|
+
release(pid) {
|
|
25632
|
+
this.releaseStmt.run({ pid });
|
|
25633
|
+
}
|
|
25634
|
+
/** Who holds the claim, if anyone. Read-only, for the same reason as above. */
|
|
25635
|
+
lease() {
|
|
25636
|
+
return getRow(this.leaseStmt);
|
|
25637
|
+
}
|
|
25638
|
+
};
|
|
25639
|
+
|
|
24626
25640
|
// ../../packages/persistence/src/migrations.ts
|
|
24627
25641
|
function describeObject(object2) {
|
|
24628
25642
|
return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
|
|
@@ -24635,7 +25649,7 @@ function createdIndexName(statement) {
|
|
|
24635
25649
|
return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
|
|
24636
25650
|
}
|
|
24637
25651
|
var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
|
|
24638
|
-
function applyMigrations(db, file2) {
|
|
25652
|
+
function applyMigrations(db, file2, options = {}) {
|
|
24639
25653
|
const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
|
|
24640
25654
|
db.exec(
|
|
24641
25655
|
"CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
|
|
@@ -24649,6 +25663,7 @@ function applyMigrations(db, file2) {
|
|
|
24649
25663
|
);
|
|
24650
25664
|
for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
|
|
24651
25665
|
if (applied.has(migration.tag)) continue;
|
|
25666
|
+
if (options.skipTags?.has(migration.tag) === true) continue;
|
|
24652
25667
|
if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
|
|
24653
25668
|
const evidence = evidenceObjects(migration.sql);
|
|
24654
25669
|
const present = evidence.filter((o) => evidenceExists(db, o));
|
|
@@ -25055,10 +26070,62 @@ function ensureSyncedAtColumn(db, table2) {
|
|
|
25055
26070
|
if (!columns.includes("outbox_owed")) {
|
|
25056
26071
|
db.exec(`ALTER TABLE ${table2} ADD COLUMN outbox_owed integer`);
|
|
25057
26072
|
}
|
|
26073
|
+
if (!columns.includes("sync_failed_at")) {
|
|
26074
|
+
db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failed_at integer`);
|
|
26075
|
+
}
|
|
26076
|
+
if (!columns.includes("sync_failure")) {
|
|
26077
|
+
withTransaction(
|
|
26078
|
+
db,
|
|
26079
|
+
() => {
|
|
26080
|
+
db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failure text`);
|
|
26081
|
+
db.exec(
|
|
26082
|
+
`UPDATE ${table2} SET synced_at = NULL
|
|
26083
|
+
WHERE synced_at = -1
|
|
26084
|
+
AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
|
|
26085
|
+
);
|
|
26086
|
+
},
|
|
26087
|
+
"IMMEDIATE"
|
|
26088
|
+
);
|
|
26089
|
+
}
|
|
25058
26090
|
db.exec(
|
|
25059
|
-
`CREATE
|
|
25060
|
-
|
|
26091
|
+
`CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
|
|
26092
|
+
BEFORE UPDATE OF sync_failure ON ${table2}
|
|
26093
|
+
WHEN ${syncFailureRejectCondition()}
|
|
26094
|
+
BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
|
|
25061
26095
|
);
|
|
26096
|
+
const syncIndexColumns = [
|
|
26097
|
+
"event_type",
|
|
26098
|
+
"synced_at",
|
|
26099
|
+
"sync_claimed_at",
|
|
26100
|
+
"started_at",
|
|
26101
|
+
// Appended LAST on purpose. The delivery-state read now projects it, so it
|
|
26102
|
+
// has to be in the index for the read to stay covered — but putting it
|
|
26103
|
+
// ahead of `started_at` would reorder the prefix the structural drain's
|
|
26104
|
+
// reads match on.
|
|
26105
|
+
"sync_failure"
|
|
26106
|
+
// `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
|
|
26107
|
+
//
|
|
26108
|
+
// The delivery-state read tests it — a capture's state depends on whether a
|
|
26109
|
+
// live forward marked it owed — so carrying it here makes that read covering
|
|
26110
|
+
// rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
|
|
26111
|
+
// But a sixth column changes what the planner charges for this index, and
|
|
26112
|
+
// with no ANALYZE statistics it plans from schema shape alone: measured, it
|
|
26113
|
+
// then stops choosing the per-session index for the token rollup and walks
|
|
26114
|
+
// every `llm_call` in the store through the event-type index instead. That
|
|
26115
|
+
// read grows with the store; this one does not.
|
|
26116
|
+
//
|
|
26117
|
+
// 40 ms on the largest store measured, once per render, is a cost worth
|
|
26118
|
+
// paying to leave every other read's plan where it was.
|
|
26119
|
+
];
|
|
26120
|
+
const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
|
|
26121
|
+
const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
|
|
26122
|
+
if (!syncIndexMatches) {
|
|
26123
|
+
db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
|
|
26124
|
+
db.exec(
|
|
26125
|
+
`CREATE INDEX idx_audit_events_sync
|
|
26126
|
+
ON audit_events (${syncIndexColumns.join(", ")})`
|
|
26127
|
+
);
|
|
26128
|
+
}
|
|
25062
26129
|
db.exec(
|
|
25063
26130
|
`CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
|
|
25064
26131
|
ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
|
|
@@ -25280,7 +26347,11 @@ function buildAuditEvent(row) {
|
|
|
25280
26347
|
link: linkParsed?.success ? linkParsed.data : null,
|
|
25281
26348
|
targetId: row.target_id,
|
|
25282
26349
|
internal: intToBool(row.internal),
|
|
25283
|
-
flagged: intToBool(row.flagged)
|
|
26350
|
+
flagged: intToBool(row.flagged),
|
|
26351
|
+
// Only meaningful when the title came out empty — a row whose body was
|
|
26352
|
+
// expired but whose title fell back to `tool_name` still has something to
|
|
26353
|
+
// render, and flagging it would make the view apologise for nothing.
|
|
26354
|
+
bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
|
|
25284
26355
|
};
|
|
25285
26356
|
}
|
|
25286
26357
|
var TIMELINE_COLUMNS = `
|
|
@@ -25288,6 +26359,7 @@ var TIMELINE_COLUMNS = `
|
|
|
25288
26359
|
event_type,
|
|
25289
26360
|
started_at,
|
|
25290
26361
|
coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
|
|
26362
|
+
content_expired_at,
|
|
25291
26363
|
coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
|
|
25292
26364
|
coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
|
|
25293
26365
|
json_extract(attributes, '$.severity') AS severity,
|
|
@@ -25414,7 +26486,8 @@ var SqliteActivityRepository = class {
|
|
|
25414
26486
|
SELECT 1 FROM audit_events d
|
|
25415
26487
|
WHERE d.root_session_id = audit_events.id
|
|
25416
26488
|
AND (d.content LIKE ? ESCAPE '\\'
|
|
25417
|
-
OR json_extract(d.attributes, '$.detail')
|
|
26489
|
+
OR coalesce(json_extract(d.attributes, '$.detail'),
|
|
26490
|
+
json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
|
|
25418
26491
|
);
|
|
25419
26492
|
params.push(pattern, pattern, pattern, pattern, pattern, pattern);
|
|
25420
26493
|
}
|
|
@@ -25952,6 +27025,88 @@ var SqliteAuditEventsRepository = class {
|
|
|
25952
27025
|
}
|
|
25953
27026
|
};
|
|
25954
27027
|
|
|
27028
|
+
// ../../packages/persistence/src/repositories/body-retention.ts
|
|
27029
|
+
var DEFAULT_BATCH_SIZE = 500;
|
|
27030
|
+
var DEFAULT_MAX_ROWS = 5e4;
|
|
27031
|
+
var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
|
|
27032
|
+
var SqliteBodyRetentionRepository = class {
|
|
27033
|
+
constructor(db) {
|
|
27034
|
+
this.db = db;
|
|
27035
|
+
const select = (laneClause) => `
|
|
27036
|
+
SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
|
|
27037
|
+
FROM audit_events
|
|
27038
|
+
WHERE content IS NOT NULL
|
|
27039
|
+
AND started_at < :cutoff
|
|
27040
|
+
AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
|
|
27041
|
+
${laneClause}
|
|
27042
|
+
ORDER BY started_at
|
|
27043
|
+
LIMIT :limit`;
|
|
27044
|
+
this.candidatesStmt = this.db.prepare(select(""));
|
|
27045
|
+
this.candidatesSyncSafeStmt = this.db.prepare(
|
|
27046
|
+
select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
|
|
27047
|
+
);
|
|
27048
|
+
this.heldBySyncStmt = this.db.prepare(`
|
|
27049
|
+
SELECT COUNT(*) AS n
|
|
27050
|
+
FROM audit_events
|
|
27051
|
+
WHERE content IS NOT NULL
|
|
27052
|
+
AND started_at < :cutoff
|
|
27053
|
+
AND event_type IN (${SYNC_LANE_TYPES_SQL})
|
|
27054
|
+
AND synced_at IS NULL`);
|
|
27055
|
+
this.expireStmt = this.db.prepare(
|
|
27056
|
+
`UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
|
|
27057
|
+
);
|
|
27058
|
+
}
|
|
27059
|
+
db;
|
|
27060
|
+
candidatesStmt;
|
|
27061
|
+
candidatesSyncSafeStmt;
|
|
27062
|
+
heldBySyncStmt;
|
|
27063
|
+
expireStmt;
|
|
27064
|
+
/** How many bytes a pass with these options would free, changing nothing. */
|
|
27065
|
+
preview(opts) {
|
|
27066
|
+
const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
|
|
27067
|
+
const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
|
|
27068
|
+
const rows = stmt.all({ cutoff: opts.cutoff, limit });
|
|
27069
|
+
return {
|
|
27070
|
+
rowsExpired: rows.length,
|
|
27071
|
+
bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
|
|
27072
|
+
rowsHeldBySync: this.countHeldBySync(opts)
|
|
27073
|
+
};
|
|
27074
|
+
}
|
|
27075
|
+
/** Clear eligible bodies, in bounded batches. */
|
|
27076
|
+
expire(opts) {
|
|
27077
|
+
const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
|
|
27078
|
+
const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
|
|
27079
|
+
const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
|
|
27080
|
+
let rowsExpired = 0;
|
|
27081
|
+
let bytesFreed = 0;
|
|
27082
|
+
let done = true;
|
|
27083
|
+
while (rowsExpired < maxRows) {
|
|
27084
|
+
const remaining = Math.min(batchSize, maxRows - rowsExpired);
|
|
27085
|
+
const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
|
|
27086
|
+
if (batch.length === 0) break;
|
|
27087
|
+
withTransaction(
|
|
27088
|
+
this.db,
|
|
27089
|
+
() => {
|
|
27090
|
+
for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
|
|
27091
|
+
},
|
|
27092
|
+
"IMMEDIATE"
|
|
27093
|
+
);
|
|
27094
|
+
rowsExpired += batch.length;
|
|
27095
|
+
bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
|
|
27096
|
+
if (batch.length < remaining) break;
|
|
27097
|
+
if (rowsExpired >= maxRows) {
|
|
27098
|
+
done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
|
|
27099
|
+
}
|
|
27100
|
+
}
|
|
27101
|
+
return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
|
|
27102
|
+
}
|
|
27103
|
+
countHeldBySync(opts) {
|
|
27104
|
+
if (opts.sweepSyncLane) return 0;
|
|
27105
|
+
const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
|
|
27106
|
+
return row.n;
|
|
27107
|
+
}
|
|
27108
|
+
};
|
|
27109
|
+
|
|
25955
27110
|
// ../../packages/persistence/src/repositories/classified-data.ts
|
|
25956
27111
|
var SqliteClassifiedDataRepository = class {
|
|
25957
27112
|
constructor(db) {
|
|
@@ -26752,23 +27907,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
|
|
|
26752
27907
|
)`;
|
|
26753
27908
|
|
|
26754
27909
|
// ../../packages/persistence/src/repositories/findings.ts
|
|
26755
|
-
var PREVIEW_INSTANCES_PER_GROUP = 200;
|
|
26756
|
-
var DEFAULT_LOCATIONS_LIMIT = 100;
|
|
26757
|
-
var LOCATION_RULE_IDS_CAP = 20;
|
|
26758
|
-
function compareLocationOrder(a, b) {
|
|
26759
|
-
return compareFindingGroupOrder(
|
|
26760
|
-
{
|
|
26761
|
-
severity: a.maxSeverity,
|
|
26762
|
-
latestDetectedAt: a.latestDetectedAt,
|
|
26763
|
-
id: ""
|
|
26764
|
-
},
|
|
26765
|
-
{
|
|
26766
|
-
severity: b.maxSeverity,
|
|
26767
|
-
latestDetectedAt: b.latestDetectedAt,
|
|
26768
|
-
id: ""
|
|
26769
|
-
}
|
|
26770
|
-
);
|
|
26771
|
-
}
|
|
26772
27910
|
var CONCAT_SEP = ",";
|
|
26773
27911
|
var TUPLE_SEP = "|";
|
|
26774
27912
|
function splitConcat(value) {
|
|
@@ -26797,7 +27935,15 @@ function toFlatFindingRow(r) {
|
|
|
26797
27935
|
...r.tool_name === null ? {} : { toolName: r.tool_name },
|
|
26798
27936
|
eventId: r.event_id,
|
|
26799
27937
|
...r.session_id === null ? {} : { sessionId: r.session_id },
|
|
26800
|
-
status: deriveInstanceStatus(r)
|
|
27938
|
+
status: deriveInstanceStatus(r),
|
|
27939
|
+
delivery: deriveFindingDelivery({
|
|
27940
|
+
kind: r.kind,
|
|
27941
|
+
syncedAt: r.synced_at,
|
|
27942
|
+
syncClaimedAt: r.sync_claimed_at,
|
|
27943
|
+
syncFailedAt: r.sync_failed_at,
|
|
27944
|
+
syncFailure: r.sync_failure,
|
|
27945
|
+
outboxOwed: r.outbox_owed
|
|
27946
|
+
})
|
|
26801
27947
|
};
|
|
26802
27948
|
}
|
|
26803
27949
|
function encodeGroupCursor(group) {
|
|
@@ -26820,13 +27966,51 @@ function decodeGroupCursor(cursor) {
|
|
|
26820
27966
|
return null;
|
|
26821
27967
|
}
|
|
26822
27968
|
function firstAfter(sorted, cursor) {
|
|
26823
|
-
const index = sorted.findIndex((
|
|
27969
|
+
const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
|
|
26824
27970
|
return index === -1 ? sorted.length : index;
|
|
26825
27971
|
}
|
|
26826
27972
|
function findDeepLinked(sorted, page, id) {
|
|
26827
|
-
if (page.some((
|
|
26828
|
-
return sorted.find((
|
|
27973
|
+
if (page.some((t) => t.id === id)) return void 0;
|
|
27974
|
+
return sorted.find((t) => t.id === id);
|
|
27975
|
+
}
|
|
27976
|
+
function encodeLocationCursor(location) {
|
|
27977
|
+
const payload = {
|
|
27978
|
+
sev: location.maxSeverity,
|
|
27979
|
+
t: location.latestDetectedAt,
|
|
27980
|
+
r: location.repo,
|
|
27981
|
+
f: location.file
|
|
27982
|
+
};
|
|
27983
|
+
return Buffer.from(JSON.stringify(payload)).toString("base64url");
|
|
27984
|
+
}
|
|
27985
|
+
function decodeLocationCursor(cursor) {
|
|
27986
|
+
const parsed = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
27987
|
+
if (parsed !== void 0 && typeof parsed.sev === "string" && typeof parsed.t === "string" && typeof parsed.r === "string" && typeof parsed.f === "string") {
|
|
27988
|
+
return { maxSeverity: parsed.sev, latestDetectedAt: parsed.t, repo: parsed.r, file: parsed.f };
|
|
27989
|
+
}
|
|
27990
|
+
return null;
|
|
26829
27991
|
}
|
|
27992
|
+
function firstLocationAfter(sorted, cursor) {
|
|
27993
|
+
const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
|
|
27994
|
+
return index === -1 ? sorted.length : index;
|
|
27995
|
+
}
|
|
27996
|
+
function findDeepLinkedLocation(sorted, page, id) {
|
|
27997
|
+
if (page.some((l) => l.id === id)) return void 0;
|
|
27998
|
+
return sorted.find((l) => l.id === id);
|
|
27999
|
+
}
|
|
28000
|
+
var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
|
|
28001
|
+
d.severity AS severity, f.masked_match AS masked_match,
|
|
28002
|
+
f.action_taken AS action_taken, f.confidence AS confidence,
|
|
28003
|
+
e.started_at AS occurred_at,
|
|
28004
|
+
e.source_tool AS source_tool,
|
|
28005
|
+
e.repo AS repo,
|
|
28006
|
+
e.file_path AS file,
|
|
28007
|
+
e.tool_name AS tool_name,
|
|
28008
|
+
f.audit_event_id AS event_id, e.root_session_id AS session_id,
|
|
28009
|
+
e.event_type AS kind, f.finding_key AS finding_key,
|
|
28010
|
+
${latestResolutionStatusSql("f")} AS latest_status,
|
|
28011
|
+
e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
|
|
28012
|
+
e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
|
|
28013
|
+
e.outbox_owed AS outbox_owed`;
|
|
26830
28014
|
var DAY_MS3 = 864e5;
|
|
26831
28015
|
var SqliteFindingsRepository = class {
|
|
26832
28016
|
constructor(db) {
|
|
@@ -26947,30 +28131,26 @@ var SqliteFindingsRepository = class {
|
|
|
26947
28131
|
);
|
|
26948
28132
|
}
|
|
26949
28133
|
/**
|
|
26950
|
-
*
|
|
26951
|
-
*
|
|
26952
|
-
*
|
|
26953
|
-
*
|
|
26954
|
-
*
|
|
26955
|
-
*
|
|
26956
|
-
*
|
|
26957
|
-
*
|
|
26958
|
-
*
|
|
26959
|
-
*
|
|
26960
|
-
*
|
|
26961
|
-
*
|
|
28134
|
+
* Finding TYPES for the dashboard — one row per rule, scoped to the four
|
|
28135
|
+
* capture kinds (audit_events also holds structural/reconciler/scan rows this
|
|
28136
|
+
* list must never surface), with per-filter-excluded facets, the requested
|
|
28137
|
+
* filters applied, and sorted by severity then recency. Filtering and faceting
|
|
28138
|
+
* run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
|
|
28139
|
+
* full filtered set; `items` is the requested page (default 50), keyset-paged.
|
|
28140
|
+
* Under a `status` filter, `totals.findings` counts only findings whose
|
|
28141
|
+
* derived status was requested.
|
|
28142
|
+
*
|
|
28143
|
+
* ONE read, which materializes no findings: a single aggregate per rule_id,
|
|
28144
|
+
* folding EVERY finding into the numbers a type row and the filters need
|
|
28145
|
+
* (count, severity, category, providers, actions, statuses, latest, search
|
|
28146
|
+
* text). The findings OF a type come from listFindingInstances scoped to
|
|
28147
|
+
* `subtype`, so neither list bounds the other and no per-type cap exists.
|
|
26962
28148
|
*
|
|
26963
|
-
* Two reads, neither of which materializes a row per finding:
|
|
26964
|
-
* 1. one aggregate row per rule_id, folding EVERY instance into the numbers
|
|
26965
|
-
* the group and the filters need (count, providers, actions, statuses,
|
|
26966
|
-
* latest, search text);
|
|
26967
|
-
* 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
|
|
26968
|
-
* populate `instances` for the table's expanded rows.
|
|
26969
28149
|
* The aggregates carry raw DB values and are translated by the same
|
|
26970
|
-
* @akasecurity/schema mappers
|
|
26971
|
-
* rule is ever restated in SQL.
|
|
28150
|
+
* @akasecurity/schema mappers every other path uses, so no enum mapping or
|
|
28151
|
+
* status rule is ever restated in SQL.
|
|
26972
28152
|
*/
|
|
26973
|
-
|
|
28153
|
+
listFindingTypes(query) {
|
|
26974
28154
|
const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
|
|
26975
28155
|
const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
|
|
26976
28156
|
const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
|
|
@@ -26983,12 +28163,7 @@ var SqliteFindingsRepository = class {
|
|
|
26983
28163
|
predicate,
|
|
26984
28164
|
params: sessionParams
|
|
26985
28165
|
});
|
|
26986
|
-
const
|
|
26987
|
-
sessionId: query.sessionId,
|
|
26988
|
-
from: query.from
|
|
26989
|
-
});
|
|
26990
|
-
const groupable = rows.map(toFlatFindingRow);
|
|
26991
|
-
const allGroups = buildFindingGroups(groupable, { aggregates });
|
|
28166
|
+
const allTypes = buildFindingTypes(aggregates);
|
|
26992
28167
|
const filterOpts = {
|
|
26993
28168
|
severity: query.severity,
|
|
26994
28169
|
providers: query.provider,
|
|
@@ -26997,30 +28172,25 @@ var SqliteFindingsRepository = class {
|
|
|
26997
28172
|
subtype: query.subtype,
|
|
26998
28173
|
q: query.q
|
|
26999
28174
|
};
|
|
27000
|
-
const facets = computeFindingFacets(
|
|
27001
|
-
const sorted =
|
|
28175
|
+
const facets = computeFindingFacets(allTypes, filterOpts);
|
|
28176
|
+
const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
|
|
27002
28177
|
const statusFilter = query.status ?? [];
|
|
27003
28178
|
const totals = {
|
|
27004
|
-
findings: sorted.reduce((acc,
|
|
27005
|
-
if (statusFilter.length === 0) return acc +
|
|
27006
|
-
const agg = aggregates.get(
|
|
27007
|
-
return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ??
|
|
28179
|
+
findings: sorted.reduce((acc, t) => {
|
|
28180
|
+
if (statusFilter.length === 0) return acc + t.instanceCount;
|
|
28181
|
+
const agg = aggregates.get(t.id);
|
|
28182
|
+
return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
|
|
27008
28183
|
}, 0),
|
|
27009
|
-
|
|
28184
|
+
types: sorted.length
|
|
27010
28185
|
};
|
|
27011
|
-
const limit = query.limit ??
|
|
28186
|
+
const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
|
|
27012
28187
|
const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
|
|
27013
28188
|
const start = cursor === null ? 0 : firstAfter(sorted, cursor);
|
|
27014
28189
|
const page = sorted.slice(start, start + limit);
|
|
27015
28190
|
const lastOnPage = page.at(-1);
|
|
27016
28191
|
const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
|
|
27017
28192
|
const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
|
|
27018
|
-
const
|
|
27019
|
-
const narrow = (g) => statusSet ? {
|
|
27020
|
-
...g,
|
|
27021
|
-
instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
|
|
27022
|
-
} : g;
|
|
27023
|
-
const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
|
|
28193
|
+
const items = [...page, ...deepLinked ? [deepLinked] : []];
|
|
27024
28194
|
return Promise.resolve({
|
|
27025
28195
|
totals,
|
|
27026
28196
|
facets,
|
|
@@ -27031,7 +28201,7 @@ var SqliteFindingsRepository = class {
|
|
|
27031
28201
|
}
|
|
27032
28202
|
/**
|
|
27033
28203
|
* One row per rule_id, folding EVERY instance of the group into the values
|
|
27034
|
-
*
|
|
28204
|
+
* buildFindingTypes cannot recover from an aggregate. Bounded by the number of
|
|
27035
28205
|
* distinct rule_ids (the installed packs' rules), not by the store's size.
|
|
27036
28206
|
*
|
|
27037
28207
|
* A single scan, folded in two levels: the inner SELECT groups by
|
|
@@ -27085,6 +28255,7 @@ var SqliteFindingsRepository = class {
|
|
|
27085
28255
|
providers: query.provider,
|
|
27086
28256
|
actions: query.action,
|
|
27087
28257
|
statuses: query.status,
|
|
28258
|
+
deliveries: query.deployment,
|
|
27088
28259
|
tools: query.tool,
|
|
27089
28260
|
repo: query.repo,
|
|
27090
28261
|
file: query.file,
|
|
@@ -27125,13 +28296,25 @@ var SqliteFindingsRepository = class {
|
|
|
27125
28296
|
});
|
|
27126
28297
|
}
|
|
27127
28298
|
/**
|
|
27128
|
-
* The same findings folded by
|
|
28299
|
+
* The same findings folded by WHERE they live — one row per (repo, file) pair.
|
|
27129
28300
|
*
|
|
27130
28301
|
* The grouping keys come from the capturing event's attributes, which is what
|
|
27131
|
-
* the local store relates a finding to
|
|
27132
|
-
*
|
|
27133
|
-
* empty-string bucket, which
|
|
27134
|
-
*
|
|
28302
|
+
* the local store relates a finding to; there is no finding↔asset row to group
|
|
28303
|
+
* by instead. A repo or file the event did not record folds into the
|
|
28304
|
+
* empty-string bucket, which is a real location like any other: it is listed,
|
|
28305
|
+
* it is selectable, and its `?loc=` token is as good as any other row's.
|
|
28306
|
+
*
|
|
28307
|
+
* ONE flat list rather than repos nesting files. A rollup can only be paged by
|
|
28308
|
+
* repo, which leaves the file list inside it unbounded — the shape the by-type
|
|
28309
|
+
* list was rebuilt to remove — and two-level pagination inside an
|
|
28310
|
+
* expand/collapse table is what pushed that view to master/detail in the first
|
|
28311
|
+
* place.
|
|
28312
|
+
*
|
|
28313
|
+
* Every filter narrows the FINDINGS and the locations fall out of what
|
|
28314
|
+
* survives, so each row's `instanceCount` is exactly what listFindingInstances
|
|
28315
|
+
* reports for the same filters scoped to that pair. The view depends on it:
|
|
28316
|
+
* one toolbar sits over both panels precisely because a location owns none of
|
|
28317
|
+
* its fields.
|
|
27135
28318
|
*/
|
|
27136
28319
|
listFindingLocations(query) {
|
|
27137
28320
|
const opts = {
|
|
@@ -27140,16 +28323,20 @@ var SqliteFindingsRepository = class {
|
|
|
27140
28323
|
providers: query.provider,
|
|
27141
28324
|
actions: query.action,
|
|
27142
28325
|
statuses: query.status,
|
|
28326
|
+
deliveries: query.deployment,
|
|
27143
28327
|
tools: query.tool,
|
|
27144
28328
|
q: query.q
|
|
27145
28329
|
};
|
|
27146
|
-
const limit = query.limit ??
|
|
28330
|
+
const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
|
|
28331
|
+
const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
|
|
27147
28332
|
const byRepo = /* @__PURE__ */ new Map();
|
|
28333
|
+
const accumulator = createInstanceFacetAccumulator(opts);
|
|
27148
28334
|
let total = 0;
|
|
27149
28335
|
for (const row of this.scanFindingRows({
|
|
27150
28336
|
sessionId: query.sessionId,
|
|
27151
28337
|
from: query.from
|
|
27152
28338
|
})) {
|
|
28339
|
+
accumulator.add(row);
|
|
27153
28340
|
if (!matchesInstanceFilters(row, opts)) continue;
|
|
27154
28341
|
total += 1;
|
|
27155
28342
|
let files = byRepo.get(row.repo);
|
|
@@ -27164,103 +28351,35 @@ var SqliteFindingsRepository = class {
|
|
|
27164
28351
|
}
|
|
27165
28352
|
addToLocation(acc, row);
|
|
27166
28353
|
}
|
|
27167
|
-
|
|
27168
|
-
const
|
|
27169
|
-
|
|
27170
|
-
|
|
27171
|
-
|
|
27172
|
-
|
|
27173
|
-
|
|
27174
|
-
|
|
27175
|
-
|
|
27176
|
-
|
|
27177
|
-
|
|
27178
|
-
|
|
27179
|
-
|
|
27180
|
-
|
|
27181
|
-
|
|
27182
|
-
|
|
27183
|
-
|
|
27184
|
-
|
|
27185
|
-
|
|
27186
|
-
|
|
27187
|
-
|
|
27188
|
-
|
|
27189
|
-
);
|
|
27190
|
-
const statuses = fileRows.map((f) => f.status);
|
|
27191
|
-
const folded = foldGroupStatus(statuses);
|
|
27192
|
-
return {
|
|
27193
|
-
repo,
|
|
27194
|
-
instanceCount: rollup.instanceCount,
|
|
27195
|
-
maxSeverity: rollup.maxSeverity,
|
|
27196
|
-
latestDetectedAt: rollup.latestDetectedAt,
|
|
27197
|
-
...folded === void 0 ? {} : { status: folded },
|
|
27198
|
-
files: fileRows
|
|
27199
|
-
};
|
|
27200
|
-
});
|
|
27201
|
-
repos.sort(compareLocationOrder);
|
|
28354
|
+
const sorted = [];
|
|
28355
|
+
for (const [repo, files] of byRepo) {
|
|
28356
|
+
for (const [file2, acc] of files) {
|
|
28357
|
+
const status = foldGroupStatus(acc.statuses);
|
|
28358
|
+
sorted.push({
|
|
28359
|
+
id: encodeLocationId(repo, file2),
|
|
28360
|
+
repo,
|
|
28361
|
+
file: file2,
|
|
28362
|
+
instanceCount: acc.instanceCount,
|
|
28363
|
+
maxSeverity: acc.maxSeverity,
|
|
28364
|
+
latestDetectedAt: acc.latestDetectedAt,
|
|
28365
|
+
...status === void 0 ? {} : { status },
|
|
28366
|
+
ruleIds: [...acc.ruleIds]
|
|
28367
|
+
});
|
|
28368
|
+
}
|
|
28369
|
+
}
|
|
28370
|
+
sorted.sort(compareLocationOrder);
|
|
28371
|
+
const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
|
|
28372
|
+
const page = sorted.slice(start, start + limit);
|
|
28373
|
+
const lastOnPage = page.at(-1);
|
|
28374
|
+
const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
|
|
28375
|
+
const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
|
|
27202
28376
|
return Promise.resolve({
|
|
27203
|
-
totals: { findings: total,
|
|
27204
|
-
|
|
27205
|
-
|
|
28377
|
+
totals: { findings: total, locations: sorted.length },
|
|
28378
|
+
facets: accumulator.facets(),
|
|
28379
|
+
items: [...page, ...deepLinked ? [deepLinked] : []],
|
|
28380
|
+
nextCursor
|
|
27206
28381
|
});
|
|
27207
28382
|
}
|
|
27208
|
-
/**
|
|
27209
|
-
* Each group's newest instances, for the table's expanded rows.
|
|
27210
|
-
*
|
|
27211
|
-
* ONE index-ordered scan with early termination, and the shape is the point.
|
|
27212
|
-
* The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
|
|
27213
|
-
* started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
|
|
27214
|
-
* through a temp B-tree to keep a bounded preview of each group, and then
|
|
27215
|
-
* sorts the survivors again for the page order. Both sorts grow with the
|
|
27216
|
-
* store while the answer does not.
|
|
27217
|
-
*
|
|
27218
|
-
* Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
|
|
27219
|
-
* (or the session or window index the scope names — see `findingScanSql`),
|
|
27220
|
-
* which is already the order the page wants, and keeps rows per rule until
|
|
27221
|
-
* each rule has as many as it can show. The aggregate the caller already holds
|
|
27222
|
-
* says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
|
|
27223
|
-
* per rule, summed, is the number of rows this scan has to find, and it stops
|
|
27224
|
-
* on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
|
|
27225
|
-
* (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
|
|
27226
|
-
* store with many firing rules widens it. The bound that DOES hold
|
|
27227
|
-
* unconditionally is the sorted form's floor: this scan visits at most as
|
|
27228
|
-
* many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
|
|
27229
|
-
* sorted, and stops the moment every rule has its cap, where the sorted form
|
|
27230
|
-
* sorts the whole scope regardless. The true worst case — the rarest rule's
|
|
27231
|
-
* wanted instances sitting at the tail of the scope — is one pass over
|
|
27232
|
-
* everything in scope with a block sort of the id tie-break only, never a
|
|
27233
|
-
* sort of the scope, which is still that floor.
|
|
27234
|
-
*
|
|
27235
|
-
* A row whose rule the aggregate did not see is skipped: the two statements
|
|
27236
|
-
* run without a shared snapshot, so a capture landing between them can add a
|
|
27237
|
-
* rule here that has no counts there, and the counts are what the group is
|
|
27238
|
-
* built from.
|
|
27239
|
-
*/
|
|
27240
|
-
previewRows(aggregates, scope) {
|
|
27241
|
-
const wanted = /* @__PURE__ */ new Map();
|
|
27242
|
-
let remaining = 0;
|
|
27243
|
-
for (const [ruleId, agg] of aggregates) {
|
|
27244
|
-
const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
|
|
27245
|
-
wanted.set(ruleId, n);
|
|
27246
|
-
remaining += n;
|
|
27247
|
-
}
|
|
27248
|
-
const rows = [];
|
|
27249
|
-
if (remaining === 0) return rows;
|
|
27250
|
-
const { sql, params } = this.findingScanSql(scope);
|
|
27251
|
-
const taken = /* @__PURE__ */ new Map();
|
|
27252
|
-
for (const r of iterateRows(this.db.prepare(sql), params)) {
|
|
27253
|
-
const want = wanted.get(r.rule_id);
|
|
27254
|
-
if (want === void 0) continue;
|
|
27255
|
-
const have = taken.get(r.rule_id) ?? 0;
|
|
27256
|
-
if (have >= want) continue;
|
|
27257
|
-
taken.set(r.rule_id, have + 1);
|
|
27258
|
-
rows.push(r);
|
|
27259
|
-
remaining -= 1;
|
|
27260
|
-
if (remaining === 0) break;
|
|
27261
|
-
}
|
|
27262
|
-
return rows;
|
|
27263
|
-
}
|
|
27264
28383
|
/**
|
|
27265
28384
|
* Every finding in scope as a FlatFindingRow, newest first, streamed.
|
|
27266
28385
|
*
|
|
@@ -27287,6 +28406,33 @@ var SqliteFindingsRepository = class {
|
|
|
27287
28406
|
yield toFlatFindingRow(r);
|
|
27288
28407
|
}
|
|
27289
28408
|
}
|
|
28409
|
+
/**
|
|
28410
|
+
* One finding by its own id, or null when no such row exists.
|
|
28411
|
+
*
|
|
28412
|
+
* A primary-key seek on `inspection_findings`, so its cost does not grow with
|
|
28413
|
+
* the store — and, unlike anything derived from a list page, it resolves a
|
|
28414
|
+
* finding of ANY age. That is what the Findings page's one-shot `?finding=`
|
|
28415
|
+
* deep link needs: the id it carries may name a finding thousands of rows
|
|
28416
|
+
* older than anything a first page holds.
|
|
28417
|
+
*
|
|
28418
|
+
* Deliberately UNFILTERED — no capture-kind, session or time predicate. It
|
|
28419
|
+
* RESOLVES an id; whether that row would survive the list's current filters is
|
|
28420
|
+
* a different question, and hiding the target because a filter excludes it is
|
|
28421
|
+
* worse than showing it.
|
|
28422
|
+
*
|
|
28423
|
+
* `groupId` on the result IS the rule id, so this one read answers both "which
|
|
28424
|
+
* type should the list select?" and "what does the drawer show?".
|
|
28425
|
+
*/
|
|
28426
|
+
findingInstance(id) {
|
|
28427
|
+
const row = this.db.prepare(
|
|
28428
|
+
`SELECT ${FINDING_ROW_COLUMNS_SQL}
|
|
28429
|
+
FROM inspection_findings f
|
|
28430
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
28431
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
28432
|
+
WHERE f.id = ?`
|
|
28433
|
+
).get(id);
|
|
28434
|
+
return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
|
|
28435
|
+
}
|
|
27290
28436
|
/**
|
|
27291
28437
|
* The one statement both instance-level scans run: every finding in scope,
|
|
27292
28438
|
* joined to its event and definition, newest first.
|
|
@@ -27320,17 +28466,7 @@ var SqliteFindingsRepository = class {
|
|
|
27320
28466
|
conditions.push("e.started_at >= ?");
|
|
27321
28467
|
params.push(isoToEpochMillis(scope.from));
|
|
27322
28468
|
}
|
|
27323
|
-
const sql = `SELECT
|
|
27324
|
-
d.severity AS severity, f.masked_match AS masked_match,
|
|
27325
|
-
f.action_taken AS action_taken, f.confidence AS confidence,
|
|
27326
|
-
e.started_at AS occurred_at,
|
|
27327
|
-
e.source_tool AS source_tool,
|
|
27328
|
-
e.repo AS repo,
|
|
27329
|
-
e.file_path AS file,
|
|
27330
|
-
e.tool_name AS tool_name,
|
|
27331
|
-
f.audit_event_id AS event_id, e.root_session_id AS session_id,
|
|
27332
|
-
e.event_type AS kind, f.finding_key AS finding_key,
|
|
27333
|
-
${latestResolutionStatusSql("f")} AS latest_status
|
|
28469
|
+
const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
|
|
27334
28470
|
FROM audit_events e
|
|
27335
28471
|
CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
|
|
27336
28472
|
CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
@@ -27344,6 +28480,26 @@ var SqliteFindingsRepository = class {
|
|
|
27344
28480
|
group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
|
|
27345
28481
|
const rows = this.db.prepare(
|
|
27346
28482
|
`SELECT rule_id,
|
|
28483
|
+
-- BARE columns beside max(latest_at), which is deliberate and
|
|
28484
|
+
-- is SQLite's documented behaviour: with a single min()/max()
|
|
28485
|
+
-- in an aggregate query, every bare column takes its value from
|
|
28486
|
+
-- the row that produced the extremum. So these are the severity
|
|
28487
|
+
-- and category of the definition whose finding is NEWEST, which
|
|
28488
|
+
-- is what the row-based build they replaced read off its first
|
|
28489
|
+
-- (newest-first) row.
|
|
28490
|
+
--
|
|
28491
|
+
-- min() is WRONG here and was the defect: inspection_definitions
|
|
28492
|
+
-- holds one row per rule VERSION (see its writer \u2014 a version bump
|
|
28493
|
+
-- mints a new row), so a rule whose severity moved between
|
|
28494
|
+
-- versions has several, and min() picks the ALPHABETICALLY
|
|
28495
|
+
-- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
|
|
28496
|
+
-- That is arbitrary in direction, and it feeds the badge, the
|
|
28497
|
+
-- filter, the facet counts and the primary sort key.
|
|
28498
|
+
--
|
|
28499
|
+
-- Adding a second min()/max() aggregate here would make these
|
|
28500
|
+
-- bare columns ambiguous again; keep max(latest_at) the only one.
|
|
28501
|
+
severity,
|
|
28502
|
+
category,
|
|
27347
28503
|
sum(tuple_count) AS instance_count,
|
|
27348
28504
|
max(latest_at) AS latest_at,
|
|
27349
28505
|
group_concat(source_tools) AS source_tools,
|
|
@@ -27354,6 +28510,14 @@ var SqliteFindingsRepository = class {
|
|
|
27354
28510
|
group_concat(tool_names) AS tool_names
|
|
27355
28511
|
FROM (
|
|
27356
28512
|
SELECT d.rule_id AS rule_id,
|
|
28513
|
+
-- Severity and category are columns of the DEFINITION, and
|
|
28514
|
+
-- a rule can have SEVERAL definitions (one per version), so
|
|
28515
|
+
-- these are grouped on below and resolved to the newest
|
|
28516
|
+
-- firing version by the outer query's bare-column select.
|
|
28517
|
+
-- They ride the aggregate because the type build has no rows
|
|
28518
|
+
-- to read them off \u2014 see buildFindingTypes.
|
|
28519
|
+
d.severity AS severity,
|
|
28520
|
+
d.category AS category,
|
|
27357
28521
|
e.event_type || '${TUPLE_SEP}' ||
|
|
27358
28522
|
(CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
|
|
27359
28523
|
coalesce(latest.status, '') AS status_tuple,
|
|
@@ -27368,7 +28532,7 @@ var SqliteFindingsRepository = class {
|
|
|
27368
28532
|
LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
|
|
27369
28533
|
ON latest.finding_key = f.finding_key
|
|
27370
28534
|
${scope.predicate}
|
|
27371
|
-
GROUP BY d.rule_id, status_tuple
|
|
28535
|
+
GROUP BY d.rule_id, d.severity, d.category, status_tuple
|
|
27372
28536
|
)
|
|
27373
28537
|
GROUP BY rule_id`
|
|
27374
28538
|
).all(scope.params);
|
|
@@ -27377,6 +28541,8 @@ var SqliteFindingsRepository = class {
|
|
|
27377
28541
|
r.rule_id,
|
|
27378
28542
|
{
|
|
27379
28543
|
instanceCount: r.instance_count,
|
|
28544
|
+
severity: r.severity,
|
|
28545
|
+
category: r.category,
|
|
27380
28546
|
sourceTools: splitConcat(r.source_tools),
|
|
27381
28547
|
actionsTaken: splitConcat(r.actions_taken),
|
|
27382
28548
|
statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
|
|
@@ -27393,7 +28559,7 @@ var SqliteFindingsRepository = class {
|
|
|
27393
28559
|
latestDetectedAt: epochMillisToIso(r.latest_at),
|
|
27394
28560
|
// Free text only — joined and substring-matched, so group_concat's
|
|
27395
28561
|
// commas need no unpicking (a repo/path containing one still matches).
|
|
27396
|
-
// Left undefined (not '') when unfetched, so
|
|
28562
|
+
// Left undefined (not '') when unfetched, so buildFindingTypes can
|
|
27397
28563
|
// tell "no q this request" from "a group with no repo/file at all"
|
|
27398
28564
|
// and skip priming a haystack nothing will read.
|
|
27399
28565
|
...withSearchText ? {
|
|
@@ -27421,7 +28587,9 @@ var SqliteFindingsRepository = class {
|
|
|
27421
28587
|
)
|
|
27422
28588
|
);
|
|
27423
28589
|
for (const row of grouped) {
|
|
27424
|
-
if (
|
|
28590
|
+
if (Object.hasOwn(byAction, row.action_taken)) {
|
|
28591
|
+
byAction[row.action_taken] = row.c;
|
|
28592
|
+
}
|
|
27425
28593
|
}
|
|
27426
28594
|
const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
|
|
27427
28595
|
const sevRows = allRows(
|
|
@@ -27438,7 +28606,9 @@ var SqliteFindingsRepository = class {
|
|
|
27438
28606
|
)
|
|
27439
28607
|
);
|
|
27440
28608
|
for (const row of sevRows) {
|
|
27441
|
-
if (
|
|
28609
|
+
if (Object.hasOwn(bySeverity, row.severity)) {
|
|
28610
|
+
bySeverity[row.severity] = row.c;
|
|
28611
|
+
}
|
|
27442
28612
|
}
|
|
27443
28613
|
const categories = ENFORCEABLE_CATEGORIES;
|
|
27444
28614
|
const enabledRows = allRows(
|
|
@@ -27487,469 +28657,6 @@ function isoDay(ms) {
|
|
|
27487
28657
|
return new Date(ms).toISOString().slice(0, 10);
|
|
27488
28658
|
}
|
|
27489
28659
|
|
|
27490
|
-
// ../../packages/persistence/src/repositories/history-sync.ts
|
|
27491
|
-
var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
|
|
27492
|
-
var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
27493
|
-
var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
|
|
27494
|
-
var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
27495
|
-
var SKIPPED = -1;
|
|
27496
|
-
var ROW_COLUMNS = `id,
|
|
27497
|
-
parent_id AS parentId,
|
|
27498
|
-
root_session_id AS rootSessionId,
|
|
27499
|
-
event_type AS eventType,
|
|
27500
|
-
host_id AS hostId,
|
|
27501
|
-
harness_id AS harnessId,
|
|
27502
|
-
source_project_id AS sourceProjectId,
|
|
27503
|
-
started_at AS startedAt,
|
|
27504
|
-
ended_at AS endedAt,
|
|
27505
|
-
severity,
|
|
27506
|
-
priority,
|
|
27507
|
-
content,
|
|
27508
|
-
content_hash AS contentHash,
|
|
27509
|
-
attributes`;
|
|
27510
|
-
var SqliteHistorySyncRepository = class {
|
|
27511
|
-
constructor(db) {
|
|
27512
|
-
this.db = db;
|
|
27513
|
-
this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
|
|
27514
|
-
this.sessionsStmt = db.prepare(
|
|
27515
|
-
`SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
|
|
27516
|
-
FROM audit_events
|
|
27517
|
-
WHERE synced_at IS NULL
|
|
27518
|
-
AND event_type IN (${TYPE_LIST})
|
|
27519
|
-
AND started_at < :before
|
|
27520
|
-
GROUP BY sessionId
|
|
27521
|
-
ORDER BY earliest
|
|
27522
|
-
LIMIT :limit`
|
|
27523
|
-
);
|
|
27524
|
-
this.rowsStmt = db.prepare(
|
|
27525
|
-
`SELECT ${ROW_COLUMNS}
|
|
27526
|
-
FROM audit_events
|
|
27527
|
-
WHERE synced_at IS NULL
|
|
27528
|
-
AND event_type IN (${TYPE_LIST})
|
|
27529
|
-
AND started_at < :before
|
|
27530
|
-
AND COALESCE(root_session_id, id) = :sessionId
|
|
27531
|
-
ORDER BY (event_type = 'session') DESC, started_at
|
|
27532
|
-
LIMIT :limit`
|
|
27533
|
-
);
|
|
27534
|
-
this.captureRowsStmt = db.prepare(
|
|
27535
|
-
`SELECT ${ROW_COLUMNS}
|
|
27536
|
-
FROM audit_events
|
|
27537
|
-
WHERE synced_at IS NULL
|
|
27538
|
-
AND sync_claimed_at IS NULL
|
|
27539
|
-
AND outbox_owed = 1
|
|
27540
|
-
AND event_type IN (${CAPTURE_TYPE_LIST})
|
|
27541
|
-
AND started_at < :before
|
|
27542
|
-
ORDER BY started_at
|
|
27543
|
-
LIMIT :limit`
|
|
27544
|
-
);
|
|
27545
|
-
this.markOwedStmt = db.prepare(
|
|
27546
|
-
`UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
|
|
27547
|
-
);
|
|
27548
|
-
this.stampStmt = db.prepare(
|
|
27549
|
-
`UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
|
|
27550
|
-
);
|
|
27551
|
-
this.claimRowStmt = db.prepare(
|
|
27552
|
-
`UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
|
|
27553
|
-
);
|
|
27554
|
-
this.releaseRowStmt = db.prepare(
|
|
27555
|
-
`UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
|
|
27556
|
-
);
|
|
27557
|
-
this.releaseStaleClaimsStmt = db.prepare(
|
|
27558
|
-
`UPDATE audit_events SET sync_claimed_at = NULL
|
|
27559
|
-
WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
|
|
27560
|
-
);
|
|
27561
|
-
this.partitionStmt = db.prepare(
|
|
27562
|
-
`SELECT
|
|
27563
|
-
SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
|
|
27564
|
-
SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
|
|
27565
|
-
SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
|
|
27566
|
-
SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
|
|
27567
|
-
COUNT(*) AS total
|
|
27568
|
-
FROM audit_events
|
|
27569
|
-
WHERE event_type IN (${TYPE_LIST})`
|
|
27570
|
-
);
|
|
27571
|
-
this.countsStmt = db.prepare(
|
|
27572
|
-
`SELECT
|
|
27573
|
-
SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
|
|
27574
|
-
SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
|
|
27575
|
-
SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
|
|
27576
|
-
FROM audit_events
|
|
27577
|
-
WHERE event_type IN (${TYPE_LIST})`
|
|
27578
|
-
);
|
|
27579
|
-
this.captureSkipCountStmt = db.prepare(
|
|
27580
|
-
`SELECT COUNT(*) AS skipped
|
|
27581
|
-
FROM audit_events
|
|
27582
|
-
WHERE synced_at = ${String(SKIPPED)}
|
|
27583
|
-
AND event_type IN (${CAPTURE_TYPE_LIST})`
|
|
27584
|
-
);
|
|
27585
|
-
this.fingerprintStmt = db.prepare(
|
|
27586
|
-
`SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
|
|
27587
|
-
FROM history_sync WHERE id = 1`
|
|
27588
|
-
);
|
|
27589
|
-
this.setFingerprintStmt = db.prepare(
|
|
27590
|
-
`UPDATE history_sync
|
|
27591
|
-
SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
|
|
27592
|
-
WHERE id = 1`
|
|
27593
|
-
);
|
|
27594
|
-
this.disownCapturesStmt = db.prepare(
|
|
27595
|
-
`UPDATE audit_events SET outbox_owed = NULL
|
|
27596
|
-
WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
|
|
27597
|
-
);
|
|
27598
|
-
this.rearmStmt = db.prepare(
|
|
27599
|
-
`UPDATE audit_events SET synced_at = NULL
|
|
27600
|
-
WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
|
|
27601
|
-
);
|
|
27602
|
-
this.claimStmt = db.prepare(
|
|
27603
|
-
`UPDATE history_sync
|
|
27604
|
-
SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
|
|
27605
|
-
WHERE id = 1
|
|
27606
|
-
AND (owner_pid IS NULL
|
|
27607
|
-
OR heartbeat_at IS NULL
|
|
27608
|
-
OR heartbeat_at < :staleBefore
|
|
27609
|
-
OR heartbeat_at > :now)`
|
|
27610
|
-
);
|
|
27611
|
-
this.heartbeatStmt = db.prepare(
|
|
27612
|
-
`UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
|
|
27613
|
-
);
|
|
27614
|
-
this.releaseStmt = db.prepare(
|
|
27615
|
-
`UPDATE history_sync
|
|
27616
|
-
SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
|
|
27617
|
-
WHERE id = 1 AND owner_pid = :pid`
|
|
27618
|
-
);
|
|
27619
|
-
this.closeWindowStmt = db.prepare(
|
|
27620
|
-
`UPDATE audit_events SET synced_at = :at
|
|
27621
|
-
WHERE synced_at IS NULL
|
|
27622
|
-
AND event_type IN (${TYPE_LIST})
|
|
27623
|
-
AND started_at >= :attachedAt`
|
|
27624
|
-
);
|
|
27625
|
-
this.releaseBoundaryStmt = db.prepare(
|
|
27626
|
-
`UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
|
|
27627
|
-
);
|
|
27628
|
-
this.freezeBoundaryStmt = db.prepare(
|
|
27629
|
-
`UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
|
|
27630
|
-
);
|
|
27631
|
-
this.leaseStmt = db.prepare(
|
|
27632
|
-
`SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
|
|
27633
|
-
acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
|
|
27634
|
-
FROM history_sync WHERE id = 1`
|
|
27635
|
-
);
|
|
27636
|
-
this.inspectionsStmt = db.prepare(
|
|
27637
|
-
`SELECT d.rule_id AS ruleId,
|
|
27638
|
-
d.name AS ruleName,
|
|
27639
|
-
d.version AS ruleVersion,
|
|
27640
|
-
d.category AS category,
|
|
27641
|
-
d.severity AS severity,
|
|
27642
|
-
f.span_start AS spanStart,
|
|
27643
|
-
f.span_end AS spanEnd,
|
|
27644
|
-
f.masked_match AS maskedMatch,
|
|
27645
|
-
f.action_taken AS actionTaken,
|
|
27646
|
-
f.confidence AS confidence
|
|
27647
|
-
FROM inspection_findings f
|
|
27648
|
-
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
27649
|
-
WHERE f.audit_event_id = :auditEventId
|
|
27650
|
-
ORDER BY f.span_start, f.id`
|
|
27651
|
-
);
|
|
27652
|
-
}
|
|
27653
|
-
db;
|
|
27654
|
-
ensureRowStmt;
|
|
27655
|
-
sessionsStmt;
|
|
27656
|
-
rowsStmt;
|
|
27657
|
-
stampStmt;
|
|
27658
|
-
countsStmt;
|
|
27659
|
-
fingerprintStmt;
|
|
27660
|
-
setFingerprintStmt;
|
|
27661
|
-
rearmStmt;
|
|
27662
|
-
claimStmt;
|
|
27663
|
-
heartbeatStmt;
|
|
27664
|
-
releaseStmt;
|
|
27665
|
-
leaseStmt;
|
|
27666
|
-
inspectionsStmt;
|
|
27667
|
-
closeWindowStmt;
|
|
27668
|
-
releaseBoundaryStmt;
|
|
27669
|
-
freezeBoundaryStmt;
|
|
27670
|
-
captureRowsStmt;
|
|
27671
|
-
markOwedStmt;
|
|
27672
|
-
captureSkipCountStmt;
|
|
27673
|
-
disownCapturesStmt;
|
|
27674
|
-
partitionStmt;
|
|
27675
|
-
claimRowStmt;
|
|
27676
|
-
releaseRowStmt;
|
|
27677
|
-
releaseStaleClaimsStmt;
|
|
27678
|
-
/**
|
|
27679
|
-
* The masked detections recorded against one tool call.
|
|
27680
|
-
*
|
|
27681
|
-
* These travel with the event because a tool call's target is not
|
|
27682
|
-
* re-inspectable from the event alone — unlike a capture, where the text
|
|
27683
|
-
* itself is re-scannable. What crosses is the masked match and the rule that
|
|
27684
|
-
* produced it, never the value.
|
|
27685
|
-
*/
|
|
27686
|
-
inspectionsFor(auditEventId) {
|
|
27687
|
-
return allRows(this.inspectionsStmt, { auditEventId });
|
|
27688
|
-
}
|
|
27689
|
-
/**
|
|
27690
|
-
* Sessions with structural rows still to send, oldest first.
|
|
27691
|
-
*
|
|
27692
|
-
* BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
|
|
27693
|
-
* read. Anything recorded after the machine attached is the live forward
|
|
27694
|
-
* path's to deliver; this drain exists for what was recorded before it, and a
|
|
27695
|
-
* row both paths send is at best a duplicate request and at worst — for a
|
|
27696
|
-
* session root — an overwrite of the inventory ids the live path resolved.
|
|
27697
|
-
*/
|
|
27698
|
-
pendingSessions(limit, before) {
|
|
27699
|
-
return allRows(this.sessionsStmt, { limit, before }).map(
|
|
27700
|
-
(r) => r.sessionId
|
|
27701
|
-
);
|
|
27702
|
-
}
|
|
27703
|
-
/** One session's undelivered structural rows within the backlog, root first. */
|
|
27704
|
-
pendingRows(sessionId, limit, before) {
|
|
27705
|
-
return allRows(this.rowsStmt, { sessionId, limit, before });
|
|
27706
|
-
}
|
|
27707
|
-
/**
|
|
27708
|
-
* Captures this machine still owes the deployment, oldest first.
|
|
27709
|
-
*
|
|
27710
|
-
* Selected by the `outbox_owed` marker the attached forward path writes, not
|
|
27711
|
-
* by a time window — see captureRowsStmt for why a window could not express
|
|
27712
|
-
* this. `before` is the grace window that leaves a just-recorded capture to
|
|
27713
|
-
* the live path.
|
|
27714
|
-
*/
|
|
27715
|
-
pendingCaptureRows(limit, before) {
|
|
27716
|
-
return allRows(this.captureRowsStmt, { limit, before });
|
|
27717
|
-
}
|
|
27718
|
-
/**
|
|
27719
|
-
* Record that a capture is OWED to the deployment.
|
|
27720
|
-
*
|
|
27721
|
-
* Written by the attached forward path when a live send did not confirm
|
|
27722
|
-
* delivery, and read by the drain as the whole of its eligibility test. It is
|
|
27723
|
-
* a fact rather than an inference: the machine was attached, the send did not
|
|
27724
|
-
* land, so the row is owed — which no time window can state, because the same
|
|
27725
|
-
* window that holds the rows a past attachment left owed also holds every
|
|
27726
|
-
* capture recorded while the machine was DETACHED, and those were never
|
|
27727
|
-
* offered to anyone.
|
|
27728
|
-
*
|
|
27729
|
-
* Idempotent, and never un-set: `markSynced` settling the row is what takes it
|
|
27730
|
-
* out of the drain's read.
|
|
27731
|
-
*/
|
|
27732
|
-
markCaptureOwed(id) {
|
|
27733
|
-
this.markOwedStmt.run({ id });
|
|
27734
|
-
}
|
|
27735
|
-
/** Record delivery. Called only AFTER the far side has accepted the rows. */
|
|
27736
|
-
markSynced(ids, atMs) {
|
|
27737
|
-
this.stampAll(ids, atMs);
|
|
27738
|
-
}
|
|
27739
|
-
/**
|
|
27740
|
-
* Record that a row will never be sent.
|
|
27741
|
-
*
|
|
27742
|
-
* Reserved for a local defect — a row that cannot be rebuilt into a valid
|
|
27743
|
-
* payload. A row that merely failed to reach the deployment stays NULL, so it
|
|
27744
|
-
* is retried; marking those would turn one outage into permanent data loss.
|
|
27745
|
-
*/
|
|
27746
|
-
markSkipped(ids) {
|
|
27747
|
-
this.stampAll(ids, SKIPPED);
|
|
27748
|
-
}
|
|
27749
|
-
eachInTransaction(ids, run) {
|
|
27750
|
-
if (ids.length === 0) return;
|
|
27751
|
-
withTransaction(
|
|
27752
|
-
this.db,
|
|
27753
|
-
() => {
|
|
27754
|
-
for (const id of ids) run(id);
|
|
27755
|
-
},
|
|
27756
|
-
"IMMEDIATE"
|
|
27757
|
-
);
|
|
27758
|
-
}
|
|
27759
|
-
stampAll(ids, value) {
|
|
27760
|
-
if (ids.length === 0) return;
|
|
27761
|
-
withTransaction(
|
|
27762
|
-
this.db,
|
|
27763
|
-
() => {
|
|
27764
|
-
for (const id of ids) this.stampStmt.run({ at: value, id });
|
|
27765
|
-
},
|
|
27766
|
-
"IMMEDIATE"
|
|
27767
|
-
);
|
|
27768
|
-
}
|
|
27769
|
-
/**
|
|
27770
|
-
* Claim rows as in-flight.
|
|
27771
|
-
*
|
|
27772
|
-
* Advisory in exactly the sense the lease is: it records that a send is in
|
|
27773
|
-
* progress so a surface can say so, and a lost claim costs a row showing as
|
|
27774
|
-
* queued while it is actually being sent. It is not exclusion — the far side
|
|
27775
|
-
* settles a duplicate on the row id.
|
|
27776
|
-
*/
|
|
27777
|
-
claimRows(ids, atMs) {
|
|
27778
|
-
this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
|
|
27779
|
-
}
|
|
27780
|
-
/** Give back a claim without settling — the send failed, the row is queued again. */
|
|
27781
|
-
releaseRows(ids) {
|
|
27782
|
-
this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
|
|
27783
|
-
}
|
|
27784
|
-
/**
|
|
27785
|
-
* Clear claims older than `staleBefore`, and report how many were cleared.
|
|
27786
|
-
*
|
|
27787
|
-
* A process killed between claiming and settling leaves rows claimed with
|
|
27788
|
-
* nothing left to settle them. Without this they read as "sending" for ever.
|
|
27789
|
-
*/
|
|
27790
|
-
releaseStaleClaims(staleBefore) {
|
|
27791
|
-
return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
|
|
27792
|
-
}
|
|
27793
|
-
/**
|
|
27794
|
-
* Every tracked row in exactly one delivery state.
|
|
27795
|
-
*
|
|
27796
|
-
* Takes no boundary on purpose. The boundary answers "what should the drain
|
|
27797
|
-
* pick up now", which is a different question from "what state is this row
|
|
27798
|
-
* in" — and a machine that has never attached has no boundary to pass, so
|
|
27799
|
-
* requiring one would force a caller to invent one and report the whole store
|
|
27800
|
-
* as queued.
|
|
27801
|
-
*/
|
|
27802
|
-
partition() {
|
|
27803
|
-
const row = getRow(this.partitionStmt, {});
|
|
27804
|
-
return {
|
|
27805
|
-
queued: row?.queued ?? 0,
|
|
27806
|
-
inProgress: row?.inProgress ?? 0,
|
|
27807
|
-
synced: row?.synced ?? 0,
|
|
27808
|
-
failed: row?.failed ?? 0,
|
|
27809
|
-
total: row?.total ?? 0
|
|
27810
|
-
};
|
|
27811
|
-
}
|
|
27812
|
-
/** `pending` counts only what is inside the backlog; sent and skipped are totals. */
|
|
27813
|
-
counts(before) {
|
|
27814
|
-
const row = getRow(
|
|
27815
|
-
this.countsStmt,
|
|
27816
|
-
{ before }
|
|
27817
|
-
);
|
|
27818
|
-
const captures = getRow(this.captureSkipCountStmt);
|
|
27819
|
-
return {
|
|
27820
|
-
pending: row?.pending ?? 0,
|
|
27821
|
-
sent: row?.sent ?? 0,
|
|
27822
|
-
skipped: row?.skipped ?? 0,
|
|
27823
|
-
capturesSkipped: captures?.skipped ?? 0
|
|
27824
|
-
};
|
|
27825
|
-
}
|
|
27826
|
-
/**
|
|
27827
|
-
* The deployment the current stamps were made against, and where its backlog
|
|
27828
|
-
* ends.
|
|
27829
|
-
*
|
|
27830
|
-
* READ-ONLY. An absent row reads as an absent deployment, which is what a
|
|
27831
|
-
* machine that has never drained is — and every writer below seeds the row
|
|
27832
|
-
* before it needs one, so nothing depends on this creating it. Keeping the
|
|
27833
|
-
* write off the gate path matters because the gate runs on every pass while a
|
|
27834
|
-
* write has to take the database's write lock.
|
|
27835
|
-
*/
|
|
27836
|
-
deployment() {
|
|
27837
|
-
const row = getRow(
|
|
27838
|
-
this.fingerprintStmt
|
|
27839
|
-
);
|
|
27840
|
-
return {
|
|
27841
|
-
fingerprint: row?.fingerprint ?? void 0,
|
|
27842
|
-
backlogBefore: row?.backlogBefore ?? void 0
|
|
27843
|
-
};
|
|
27844
|
-
}
|
|
27845
|
-
/**
|
|
27846
|
-
* Point the ledger at a different deployment, discarding what it recorded
|
|
27847
|
-
* about the previous one.
|
|
27848
|
-
*
|
|
27849
|
-
* Delivery is a fact about ONE recipient: rows sent to the deployment a
|
|
27850
|
-
* machine has just left are undelivered as far as the new one is concerned.
|
|
27851
|
-
* All three in one transaction, so a crash between them cannot leave stamps
|
|
27852
|
-
* attributed to the wrong deployment, or a boundary that belongs to another.
|
|
27853
|
-
*
|
|
27854
|
-
* The boundary is written HERE and only here, which is what freezes it: a
|
|
27855
|
-
* re-attach to the SAME deployment (a key rotation) leaves the fingerprint
|
|
27856
|
-
* unchanged, so this never runs and the backlog does not widen back over rows
|
|
27857
|
-
* the live path has since delivered.
|
|
27858
|
-
*/
|
|
27859
|
-
rearmFor(fingerprint, backlogBefore) {
|
|
27860
|
-
this.ensureRowStmt.run();
|
|
27861
|
-
withTransaction(
|
|
27862
|
-
this.db,
|
|
27863
|
-
() => {
|
|
27864
|
-
const previous = getRow(this.fingerprintStmt)?.fingerprint;
|
|
27865
|
-
this.rearmStmt.run();
|
|
27866
|
-
if (previous !== null && previous !== void 0 && previous !== fingerprint) {
|
|
27867
|
-
this.disownCapturesStmt.run();
|
|
27868
|
-
}
|
|
27869
|
-
this.setFingerprintStmt.run({ fingerprint, backlogBefore });
|
|
27870
|
-
},
|
|
27871
|
-
"IMMEDIATE"
|
|
27872
|
-
);
|
|
27873
|
-
}
|
|
27874
|
-
/**
|
|
27875
|
-
* End the attached period: hand its rows to the live path, and release the
|
|
27876
|
-
* boundary so the next attachment can freeze a new one.
|
|
27877
|
-
*
|
|
27878
|
-
* WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
|
|
27879
|
-
* nothing delivers. The fingerprint is unchanged, so the boundary is never
|
|
27880
|
-
* re-frozen and stays at the FIRST attachment — while nothing forwards at all
|
|
27881
|
-
* during the detached period, because the machine is not attached. Rows
|
|
27882
|
-
* recorded in that window sit after the boundary and before the re-attach, so
|
|
27883
|
-
* neither path takes them, and the pending count reports none outstanding.
|
|
27884
|
-
*
|
|
27885
|
-
* Stamping the attached window is not a claim that every one of those rows
|
|
27886
|
-
* reached the deployment — the live path drops on failure and says so
|
|
27887
|
-
* elsewhere. It records that they were ITS to deliver, which is exactly the
|
|
27888
|
-
* status quo: they sit outside the frozen boundary today and are equally never
|
|
27889
|
-
* re-sent. Making it explicit is what lets the boundary move.
|
|
27890
|
-
*
|
|
27891
|
-
* ONE TRANSACTION, so a crash cannot release the boundary while leaving the
|
|
27892
|
-
* window unstamped — that half-state would re-send the whole attached period
|
|
27893
|
-
* on the next attach, which is the failure the boundary exists to prevent.
|
|
27894
|
-
*/
|
|
27895
|
-
closeAttachedWindow(attachedAtMs, atMs) {
|
|
27896
|
-
this.ensureRowStmt.run();
|
|
27897
|
-
withTransaction(
|
|
27898
|
-
this.db,
|
|
27899
|
-
() => {
|
|
27900
|
-
const row = getRow(this.fingerprintStmt);
|
|
27901
|
-
const from = row?.backlogBefore ?? attachedAtMs;
|
|
27902
|
-
this.closeWindowStmt.run({ at: atMs, attachedAt: from });
|
|
27903
|
-
this.releaseBoundaryStmt.run();
|
|
27904
|
-
},
|
|
27905
|
-
"IMMEDIATE"
|
|
27906
|
-
);
|
|
27907
|
-
}
|
|
27908
|
-
/**
|
|
27909
|
-
* Freeze a boundary for the deployment already on file, KEEPING the stamps.
|
|
27910
|
-
*
|
|
27911
|
-
* The re-attach half of the above. Distinct from `rearmFor`, which is for a
|
|
27912
|
-
* different deployment and therefore discards what was delivered to the old
|
|
27913
|
-
* one: here the recipient is the same, so everything already sent to it stays
|
|
27914
|
-
* sent.
|
|
27915
|
-
*/
|
|
27916
|
-
freezeBoundary(backlogBefore) {
|
|
27917
|
-
this.ensureRowStmt.run();
|
|
27918
|
-
this.freezeBoundaryStmt.run({ backlogBefore });
|
|
27919
|
-
}
|
|
27920
|
-
/** Take the claim, or report that someone live already holds it. */
|
|
27921
|
-
claim(pid, host, nowMs, staleAfterMs) {
|
|
27922
|
-
this.ensureRowStmt.run();
|
|
27923
|
-
let taken = false;
|
|
27924
|
-
withTransaction(
|
|
27925
|
-
this.db,
|
|
27926
|
-
() => {
|
|
27927
|
-
const result = this.claimStmt.run({
|
|
27928
|
-
pid,
|
|
27929
|
-
host,
|
|
27930
|
-
now: nowMs,
|
|
27931
|
-
staleBefore: nowMs - staleAfterMs
|
|
27932
|
-
});
|
|
27933
|
-
taken = result.changes === 1;
|
|
27934
|
-
},
|
|
27935
|
-
"IMMEDIATE"
|
|
27936
|
-
);
|
|
27937
|
-
return taken;
|
|
27938
|
-
}
|
|
27939
|
-
/** Say the holder is still alive. A no-op once the claim has moved on. */
|
|
27940
|
-
heartbeat(pid, nowMs) {
|
|
27941
|
-
this.heartbeatStmt.run({ now: nowMs, pid });
|
|
27942
|
-
}
|
|
27943
|
-
/** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
|
|
27944
|
-
release(pid) {
|
|
27945
|
-
this.releaseStmt.run({ pid });
|
|
27946
|
-
}
|
|
27947
|
-
/** Who holds the claim, if anyone. Read-only, for the same reason as above. */
|
|
27948
|
-
lease() {
|
|
27949
|
-
return getRow(this.leaseStmt);
|
|
27950
|
-
}
|
|
27951
|
-
};
|
|
27952
|
-
|
|
27953
28660
|
// ../../packages/persistence/src/repositories/inspection-definitions.ts
|
|
27954
28661
|
var SqliteInspectionDefinitionsRepository = class {
|
|
27955
28662
|
constructor(db) {
|
|
@@ -28137,7 +28844,8 @@ function managedSettingsPaths(platform2 = process.platform) {
|
|
|
28137
28844
|
}
|
|
28138
28845
|
return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
|
|
28139
28846
|
}
|
|
28140
|
-
|
|
28847
|
+
var testOnlyManagedPaths = null;
|
|
28848
|
+
function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
|
|
28141
28849
|
for (const path of paths) {
|
|
28142
28850
|
let text;
|
|
28143
28851
|
try {
|
|
@@ -28172,6 +28880,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
|
|
|
28172
28880
|
if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
|
|
28173
28881
|
if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
|
|
28174
28882
|
if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
|
|
28883
|
+
if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
|
|
28175
28884
|
if (values.vaultConsent !== void 0) {
|
|
28176
28885
|
merged.vaultConsent = values.vaultConsent ? (
|
|
28177
28886
|
// Keep an existing valid grant so its acknowledgedAt survives; mint one
|
|
@@ -30617,7 +31326,7 @@ function toUtcDateString(ms) {
|
|
|
30617
31326
|
return new Date(ms).toISOString().slice(0, 10);
|
|
30618
31327
|
}
|
|
30619
31328
|
function isTimeseriesSeverity(s) {
|
|
30620
|
-
return s === "critical" || s === "high" || s === "medium";
|
|
31329
|
+
return s === "critical" || s === "high" || s === "medium" || s === "low";
|
|
30621
31330
|
}
|
|
30622
31331
|
var SqliteSecurityRepository = class {
|
|
30623
31332
|
constructor(db, now = () => Date.now()) {
|
|
@@ -30679,7 +31388,7 @@ var SqliteSecurityRepository = class {
|
|
|
30679
31388
|
ELSE 0
|
|
30680
31389
|
END) AS open_at_rest
|
|
30681
31390
|
FROM inspection_findings f
|
|
30682
|
-
JOIN audit_events e ON e.id = f.audit_event_id
|
|
31391
|
+
JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
|
|
30683
31392
|
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
30684
31393
|
LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
|
|
30685
31394
|
ON latest.finding_key = f.finding_key
|
|
@@ -30746,12 +31455,16 @@ var SqliteSecurityRepository = class {
|
|
|
30746
31455
|
const now = this.now();
|
|
30747
31456
|
const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
|
|
30748
31457
|
const rows = this.findingsInRange(windowStart, now);
|
|
30749
|
-
const points = Array.from(
|
|
30750
|
-
|
|
30751
|
-
|
|
30752
|
-
|
|
30753
|
-
|
|
30754
|
-
|
|
31458
|
+
const points = Array.from(
|
|
31459
|
+
{ length: numBuckets },
|
|
31460
|
+
(_, i) => ({
|
|
31461
|
+
timestamp: toUtcDateString(windowStart + i * bucketMs),
|
|
31462
|
+
critical: 0,
|
|
31463
|
+
high: 0,
|
|
31464
|
+
medium: 0,
|
|
31465
|
+
low: 0
|
|
31466
|
+
})
|
|
31467
|
+
);
|
|
30755
31468
|
for (const r of rows) {
|
|
30756
31469
|
const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
|
|
30757
31470
|
const bucket = points[idx];
|
|
@@ -30901,7 +31614,7 @@ var SqliteSecurityRepository = class {
|
|
|
30901
31614
|
this.db.prepare(
|
|
30902
31615
|
`SELECT e.repo AS repo, count(*) AS c
|
|
30903
31616
|
FROM inspection_findings f
|
|
30904
|
-
JOIN audit_events e ON e.id = f.audit_event_id
|
|
31617
|
+
JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
|
|
30905
31618
|
WHERE e.started_at >= :from AND e.started_at < :to
|
|
30906
31619
|
AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
|
|
30907
31620
|
AND e.repo IS NOT NULL
|
|
@@ -30969,6 +31682,7 @@ var SqliteSecurityRepository = class {
|
|
|
30969
31682
|
`SELECT f.finding_key AS finding_key,
|
|
30970
31683
|
d.rule_id AS rule_id,
|
|
30971
31684
|
d.severity AS severity,
|
|
31685
|
+
e.repo AS repo,
|
|
30972
31686
|
e.file_path AS path,
|
|
30973
31687
|
COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
|
|
30974
31688
|
latest.resolved_at AS latest_resolved_at
|
|
@@ -30988,6 +31702,7 @@ var SqliteSecurityRepository = class {
|
|
|
30988
31702
|
const items = rows.map((r) => ({
|
|
30989
31703
|
findingKey: r.finding_key,
|
|
30990
31704
|
ruleId: r.rule_id,
|
|
31705
|
+
repo: r.repo ?? "",
|
|
30991
31706
|
severity: r.severity,
|
|
30992
31707
|
path: r.path ?? "",
|
|
30993
31708
|
resolvedAt: new Date(r.latest_resolved_at).toISOString(),
|
|
@@ -30997,15 +31712,68 @@ var SqliteSecurityRepository = class {
|
|
|
30997
31712
|
}));
|
|
30998
31713
|
return Promise.resolve({ items });
|
|
30999
31714
|
}
|
|
31715
|
+
/**
|
|
31716
|
+
* Per-rule tallies of the findings that are still OPEN, whole-store.
|
|
31717
|
+
*
|
|
31718
|
+
* Scoped by status rather than by time, because the card this feeds is a to-do
|
|
31719
|
+
* list: a secret committed three weeks ago and never rotated is still the most
|
|
31720
|
+
* important thing to fix, and any window hides it. It carried a "newest N
|
|
31721
|
+
* findings" cap and then a range; the first meant a different span on every
|
|
31722
|
+
* machine, and the second reported "no recommendations" over live exposure.
|
|
31723
|
+
*
|
|
31724
|
+
* `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
|
|
31725
|
+
* so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
|
|
31726
|
+
* is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
|
|
31727
|
+
* dismissal is a judgement, not a remediation) and drops untracked legacy rows.
|
|
31728
|
+
* The two answer different questions and only this one has to match a link.
|
|
31729
|
+
*
|
|
31730
|
+
* Aggregated in SQL: the result is O(distinct rule × category × severity), so a
|
|
31731
|
+
* whole-store scope costs a grouped scan rather than a row per finding.
|
|
31732
|
+
*/
|
|
31733
|
+
recommendationInputs() {
|
|
31734
|
+
const rows = allRows(
|
|
31735
|
+
this.db.prepare(
|
|
31736
|
+
`SELECT d.rule_id AS rule_id,
|
|
31737
|
+
d.category AS category,
|
|
31738
|
+
d.severity AS severity,
|
|
31739
|
+
COUNT(*) AS count
|
|
31740
|
+
FROM inspection_findings f
|
|
31741
|
+
JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
|
|
31742
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
31743
|
+
LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
|
|
31744
|
+
ON latest.finding_key = f.finding_key
|
|
31745
|
+
WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
|
|
31746
|
+
AND e.event_type = 'code_change'
|
|
31747
|
+
AND (
|
|
31748
|
+
f.finding_key IS NULL
|
|
31749
|
+
OR latest.status IS NULL
|
|
31750
|
+
OR latest.status NOT IN ('resolved', 'dismissed')
|
|
31751
|
+
)
|
|
31752
|
+
GROUP BY d.rule_id, d.category, d.severity`
|
|
31753
|
+
)
|
|
31754
|
+
);
|
|
31755
|
+
return Promise.resolve(
|
|
31756
|
+
rows.map((r) => ({
|
|
31757
|
+
ruleId: r.rule_id,
|
|
31758
|
+
category: r.category,
|
|
31759
|
+
severity: r.severity,
|
|
31760
|
+
count: r.count
|
|
31761
|
+
}))
|
|
31762
|
+
);
|
|
31763
|
+
}
|
|
31000
31764
|
// Findings whose parent event occurred in [fromMs, toMs), with the parent's
|
|
31001
31765
|
// epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
|
|
31002
31766
|
// numeric and the JS aggregations bucket/split on ms directly.
|
|
31003
31767
|
findingsInRange(fromMs, toMs) {
|
|
31004
31768
|
const rows = allRows(
|
|
31005
31769
|
this.db.prepare(
|
|
31006
|
-
`
|
|
31770
|
+
// `rule_id`/`category` cost nothing extra: inspection_definitions is already
|
|
31771
|
+
// joined for `severity`, so they are two more columns off a row this read
|
|
31772
|
+
// already fetches. They feed the recommended-actions rollup.
|
|
31773
|
+
`SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
|
|
31774
|
+
d.rule_id AS rule_id, d.category AS category
|
|
31007
31775
|
FROM inspection_findings f
|
|
31008
|
-
JOIN audit_events e ON e.id = f.audit_event_id
|
|
31776
|
+
JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
|
|
31009
31777
|
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
31010
31778
|
WHERE e.started_at >= :from AND e.started_at < :to
|
|
31011
31779
|
AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
|
|
@@ -31016,7 +31784,9 @@ var SqliteSecurityRepository = class {
|
|
|
31016
31784
|
return rows.map((r) => ({
|
|
31017
31785
|
occurredAt: r.occurred_at,
|
|
31018
31786
|
severity: r.severity,
|
|
31019
|
-
actionTaken: r.action_taken
|
|
31787
|
+
actionTaken: r.action_taken,
|
|
31788
|
+
ruleId: r.rule_id,
|
|
31789
|
+
category: r.category
|
|
31020
31790
|
}));
|
|
31021
31791
|
}
|
|
31022
31792
|
};
|
|
@@ -31844,6 +32614,7 @@ function openWithPragmas(file2) {
|
|
|
31844
32614
|
db.exec("PRAGMA journal_mode = WAL");
|
|
31845
32615
|
db.exec("PRAGMA busy_timeout = 2000");
|
|
31846
32616
|
db.exec("PRAGMA foreign_keys = ON");
|
|
32617
|
+
registerSqlFunctions(db);
|
|
31847
32618
|
} catch (err) {
|
|
31848
32619
|
closeQuietly(db);
|
|
31849
32620
|
throw err;
|
|
@@ -31873,7 +32644,7 @@ function backupLegacyStore(db, file2) {
|
|
|
31873
32644
|
discardStore(file2, backup);
|
|
31874
32645
|
return backup;
|
|
31875
32646
|
}
|
|
31876
|
-
function openAndInitialize(file2, base) {
|
|
32647
|
+
function openAndInitialize(file2, base, skipTags) {
|
|
31877
32648
|
let db = openWithPragmas(file2);
|
|
31878
32649
|
try {
|
|
31879
32650
|
if (isForeignSqliteLineage(db)) {
|
|
@@ -31883,7 +32654,7 @@ function openAndInitialize(file2, base) {
|
|
|
31883
32654
|
`Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
|
|
31884
32655
|
);
|
|
31885
32656
|
}
|
|
31886
|
-
applyMigrations(db, file2);
|
|
32657
|
+
applyMigrations(db, file2, { skipTags });
|
|
31887
32658
|
tightenPerms(file2);
|
|
31888
32659
|
const policies = new SqlitePoliciesRepository(db);
|
|
31889
32660
|
const installedPacks = new SqliteInstalledPacksRepository(db, base);
|
|
@@ -31898,6 +32669,7 @@ function openAndInitialize(file2, base) {
|
|
|
31898
32669
|
exceptions: new SqliteExceptionsRepository(db),
|
|
31899
32670
|
resolutions: new SqliteResolutionsRepository(db),
|
|
31900
32671
|
ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
|
|
32672
|
+
bodyRetention: new SqliteBodyRetentionRepository(db),
|
|
31901
32673
|
security: new SqliteSecurityRepository(db),
|
|
31902
32674
|
detections: new SqliteDetectionsRepository(db),
|
|
31903
32675
|
shares: new SqliteSharesRepository(db),
|
|
@@ -31920,7 +32692,8 @@ function openAndInitialize(file2, base) {
|
|
|
31920
32692
|
throw err;
|
|
31921
32693
|
}
|
|
31922
32694
|
}
|
|
31923
|
-
|
|
32695
|
+
var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
|
|
32696
|
+
function openLocalDatabase(dir, options = {}) {
|
|
31924
32697
|
ensureDataDirSync(dir);
|
|
31925
32698
|
const file2 = join7(dir, DB_FILENAME);
|
|
31926
32699
|
reapStalePartials(file2);
|
|
@@ -31932,6 +32705,7 @@ function openLocalDatabase(dir) {
|
|
|
31932
32705
|
installedPacks,
|
|
31933
32706
|
scanLedger,
|
|
31934
32707
|
historySync,
|
|
32708
|
+
bodyRetention,
|
|
31935
32709
|
secretVault,
|
|
31936
32710
|
exceptions,
|
|
31937
32711
|
resolutions,
|
|
@@ -31955,7 +32729,8 @@ function openLocalDatabase(dir) {
|
|
|
31955
32729
|
// `dir` is always `<base>/data` — every caller resolves it through
|
|
31956
32730
|
// `dataDir()` — so its parent is the `~/.aka` base the layout splits into
|
|
31957
32731
|
// settings/ and data/, and the pack-policy floor needs both halves.
|
|
31958
|
-
dirname2(dir)
|
|
32732
|
+
dirname2(dir),
|
|
32733
|
+
options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
|
|
31959
32734
|
);
|
|
31960
32735
|
function captureRowId(event) {
|
|
31961
32736
|
return captureId(
|
|
@@ -32148,6 +32923,7 @@ function openLocalDatabase(dir) {
|
|
|
32148
32923
|
installedPacks,
|
|
32149
32924
|
scanLedger,
|
|
32150
32925
|
historySync,
|
|
32926
|
+
bodyRetention,
|
|
32151
32927
|
secretVault,
|
|
32152
32928
|
exceptions,
|
|
32153
32929
|
resolutions,
|
|
@@ -32186,8 +32962,12 @@ function openLocalDatabase(dir) {
|
|
|
32186
32962
|
};
|
|
32187
32963
|
}
|
|
32188
32964
|
|
|
32189
|
-
// ../../packages/persistence/src/
|
|
32965
|
+
// ../../packages/persistence/src/egress-wire.ts
|
|
32190
32966
|
import { createHash as createHash3 } from "crypto";
|
|
32967
|
+
var SLASH = "/".charCodeAt(0);
|
|
32968
|
+
|
|
32969
|
+
// ../../packages/persistence/src/finding-key.ts
|
|
32970
|
+
import { createHash as createHash4 } from "crypto";
|
|
32191
32971
|
|
|
32192
32972
|
// ../../packages/persistence/src/fingerprint.ts
|
|
32193
32973
|
import { createHmac, randomBytes } from "crypto";
|
|
@@ -32195,14 +32975,26 @@ import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
|
|
|
32195
32975
|
import { join as join8 } from "path";
|
|
32196
32976
|
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
32197
32977
|
|
|
32198
|
-
// ../../packages/persistence/src/
|
|
32199
|
-
import {
|
|
32978
|
+
// ../../packages/persistence/src/forward-health.ts
|
|
32979
|
+
import { readFileSync as readFileSync7 } from "fs";
|
|
32200
32980
|
import { join as join9 } from "path";
|
|
32981
|
+
|
|
32982
|
+
// ../../packages/persistence/src/history-backfill.ts
|
|
32983
|
+
import { existsSync as existsSync4 } from "fs";
|
|
32984
|
+
import { join as join10 } from "path";
|
|
32985
|
+
|
|
32986
|
+
// ../../packages/persistence/src/history-preview.ts
|
|
32987
|
+
import { existsSync as existsSync5 } from "fs";
|
|
32988
|
+
import { join as join11 } from "path";
|
|
32201
32989
|
import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
|
|
32202
32990
|
|
|
32991
|
+
// ../../packages/persistence/src/history-sync-state.ts
|
|
32992
|
+
import { readFileSync as readFileSync8 } from "fs";
|
|
32993
|
+
import { join as join12 } from "path";
|
|
32994
|
+
|
|
32203
32995
|
// ../../packages/persistence/src/store-symlinks.ts
|
|
32204
|
-
import { existsSync as
|
|
32205
|
-
import { dirname as dirname3, join as
|
|
32996
|
+
import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
|
|
32997
|
+
import { dirname as dirname3, join as join13, resolve } from "path";
|
|
32206
32998
|
|
|
32207
32999
|
// ../../packages/persistence/src/vault/crypto.ts
|
|
32208
33000
|
import {
|
|
@@ -32216,19 +33008,19 @@ import {
|
|
|
32216
33008
|
// ../../packages/persistence/src/vault/key-provider.ts
|
|
32217
33009
|
import { execFileSync } from "child_process";
|
|
32218
33010
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
32219
|
-
import { chmodSync as chmodSync3, readFileSync as
|
|
32220
|
-
import { join as
|
|
33011
|
+
import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
|
|
33012
|
+
import { join as join14 } from "path";
|
|
32221
33013
|
|
|
32222
33014
|
// ../../packages/persistence/src/vault/vault.ts
|
|
32223
33015
|
import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
|
|
32224
33016
|
|
|
32225
33017
|
// ../../packages/persistence/src/warn-era-cap.ts
|
|
32226
|
-
import { existsSync as
|
|
32227
|
-
import { join as
|
|
33018
|
+
import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
|
|
33019
|
+
import { join as join15 } from "path";
|
|
32228
33020
|
|
|
32229
33021
|
// ../../packages/plugin-sdk/src/config.ts
|
|
32230
|
-
import { existsSync as
|
|
32231
|
-
import { join as
|
|
33022
|
+
import { existsSync as existsSync8 } from "fs";
|
|
33023
|
+
import { join as join16 } from "path";
|
|
32232
33024
|
|
|
32233
33025
|
// ../../packages/plugin-sdk/src/provider-env.ts
|
|
32234
33026
|
var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
|
|
@@ -32282,8 +33074,8 @@ function resolveProvider() {
|
|
|
32282
33074
|
function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
|
|
32283
33075
|
try {
|
|
32284
33076
|
ensureLayoutDirSync(base);
|
|
32285
|
-
const settingsFile =
|
|
32286
|
-
if (
|
|
33077
|
+
const settingsFile = join16(settingsDir(base), "settings.json");
|
|
33078
|
+
if (existsSync8(settingsFile)) tightenFile(settingsFile);
|
|
32287
33079
|
} catch {
|
|
32288
33080
|
}
|
|
32289
33081
|
migrateLegacyLayout(base);
|
|
@@ -32306,9 +33098,9 @@ function resolveProviderSafe(resolveProviderFn) {
|
|
|
32306
33098
|
}
|
|
32307
33099
|
|
|
32308
33100
|
// ../../packages/plugin-sdk/src/config-inventory.ts
|
|
32309
|
-
import { readdirSync as readdirSync2, readFileSync as
|
|
33101
|
+
import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
|
|
32310
33102
|
import { homedir as homedir2 } from "os";
|
|
32311
|
-
import { basename as basename3, join as
|
|
33103
|
+
import { basename as basename3, join as join18 } from "path";
|
|
32312
33104
|
|
|
32313
33105
|
// ../../packages/detections/src/egress/registry.ts
|
|
32314
33106
|
var EXTRACTOR_VERSION = "1";
|
|
@@ -35343,24 +36135,20 @@ function maskText(text) {
|
|
|
35343
36135
|
}
|
|
35344
36136
|
|
|
35345
36137
|
// ../../packages/plugin-sdk/src/repo.ts
|
|
35346
|
-
import { existsSync as
|
|
35347
|
-
import { basename as basename2, dirname as dirname4, isAbsolute, join as
|
|
36138
|
+
import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
|
|
36139
|
+
import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
|
|
35348
36140
|
|
|
35349
36141
|
// ../../packages/plugin-sdk/src/events.ts
|
|
35350
|
-
import { createHash as
|
|
36142
|
+
import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
|
|
35351
36143
|
|
|
35352
36144
|
// ../../packages/plugin-sdk/src/isolated-scan.ts
|
|
35353
|
-
import { existsSync as
|
|
36145
|
+
import { existsSync as existsSync10 } from "fs";
|
|
35354
36146
|
import { fileURLToPath } from "url";
|
|
35355
36147
|
import { Worker } from "worker_threads";
|
|
35356
36148
|
|
|
35357
|
-
// ../../packages/plugin-sdk/src/
|
|
35358
|
-
|
|
35359
|
-
import {
|
|
35360
|
-
import { join as join16 } from "path";
|
|
35361
|
-
|
|
35362
|
-
// ../../packages/plugin-sdk/src/inventory-resolver.ts
|
|
35363
|
-
import { arch, hostname as hostname4, platform, release } from "os";
|
|
36149
|
+
// ../../packages/plugin-sdk/src/host-floor.ts
|
|
36150
|
+
import { readFileSync as readFileSync13 } from "fs";
|
|
36151
|
+
import { join as join20 } from "path";
|
|
35364
36152
|
|
|
35365
36153
|
// ../../packages/plugin-sdk/src/model-governance.ts
|
|
35366
36154
|
import {
|
|
@@ -35368,16 +36156,42 @@ import {
|
|
|
35368
36156
|
fstatSync,
|
|
35369
36157
|
mkdirSync as mkdirSync2,
|
|
35370
36158
|
openSync as openSync2,
|
|
35371
|
-
readFileSync as
|
|
36159
|
+
readFileSync as readFileSync12,
|
|
35372
36160
|
readSync,
|
|
35373
36161
|
writeFileSync as writeFileSync5
|
|
35374
36162
|
} from "fs";
|
|
35375
|
-
import { join as
|
|
36163
|
+
import { join as join19 } from "path";
|
|
35376
36164
|
var TAIL_BYTES = 256 * 1024;
|
|
35377
36165
|
|
|
36166
|
+
// ../../packages/plugin-sdk/src/host-floor.ts
|
|
36167
|
+
var HOST_FEATURE = {
|
|
36168
|
+
ModelSwitch: "model-switch",
|
|
36169
|
+
VaultPointerDisplay: "vault-pointer-display"
|
|
36170
|
+
};
|
|
36171
|
+
var HOST_FLOORS = {
|
|
36172
|
+
[HOST_FEATURE.ModelSwitch]: {
|
|
36173
|
+
label: "model-switch protection",
|
|
36174
|
+
hookEvents: ["PreModelSwitch", "PostModelSwitch"],
|
|
36175
|
+
since: "2.1.251"
|
|
36176
|
+
},
|
|
36177
|
+
[HOST_FEATURE.VaultPointerDisplay]: {
|
|
36178
|
+
label: "vault pointer display",
|
|
36179
|
+
hookEvents: ["MessageDisplay"],
|
|
36180
|
+
since: "2.1.152"
|
|
36181
|
+
}
|
|
36182
|
+
};
|
|
36183
|
+
|
|
36184
|
+
// ../../packages/plugin-sdk/src/ignore-layers.ts
|
|
36185
|
+
var import_ignore = __toESM(require_ignore(), 1);
|
|
36186
|
+
import { readFileSync as readFileSync14 } from "fs";
|
|
36187
|
+
import { join as join21 } from "path";
|
|
36188
|
+
|
|
36189
|
+
// ../../packages/plugin-sdk/src/inventory-resolver.ts
|
|
36190
|
+
import { arch, hostname as hostname4, platform, release } from "os";
|
|
36191
|
+
|
|
35378
36192
|
// ../../packages/plugin-sdk/src/nudge.ts
|
|
35379
|
-
import { mkdirSync as mkdirSync3, readFileSync as
|
|
35380
|
-
import { join as
|
|
36193
|
+
import { mkdirSync as mkdirSync3, readFileSync as readFileSync15, writeFileSync as writeFileSync6 } from "fs";
|
|
36194
|
+
import { join as join22 } from "path";
|
|
35381
36195
|
|
|
35382
36196
|
// ../../packages/plugin-sdk/src/paths.ts
|
|
35383
36197
|
import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
|
|
@@ -35394,8 +36208,8 @@ function applyCategoryPosture(posture, repo, mode = "fill-gaps") {
|
|
|
35394
36208
|
}
|
|
35395
36209
|
|
|
35396
36210
|
// ../../packages/plugin-sdk/src/project-files.ts
|
|
35397
|
-
import { existsSync as
|
|
35398
|
-
import { basename as basename5, join as
|
|
36211
|
+
import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
|
|
36212
|
+
import { basename as basename5, join as join23 } from "path";
|
|
35399
36213
|
|
|
35400
36214
|
// ../../packages/plugin-sdk/src/provider-env-antigravity.ts
|
|
35401
36215
|
var optionalBaseUrl2 = external_exports.preprocess((v) => {
|
|
@@ -35513,11 +36327,11 @@ async function applySetupTriageSuppressions(entries, writer, opts) {
|
|
|
35513
36327
|
|
|
35514
36328
|
// ../../packages/plugin-sdk/src/throttle.ts
|
|
35515
36329
|
import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
|
|
35516
|
-
import { join as
|
|
36330
|
+
import { join as join24 } from "path";
|
|
35517
36331
|
|
|
35518
36332
|
// ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
|
|
35519
36333
|
import { writeFileSync as writeFileSync8 } from "fs";
|
|
35520
|
-
import { join as
|
|
36334
|
+
import { join as join25 } from "path";
|
|
35521
36335
|
|
|
35522
36336
|
// ../../packages/setup-wizard/src/triage/dedupe.ts
|
|
35523
36337
|
function dedupeKey(hit) {
|
|
@@ -35572,12 +36386,12 @@ function deriveFalsePositivePatterns(hits, rec, plan) {
|
|
|
35572
36386
|
}
|
|
35573
36387
|
|
|
35574
36388
|
// ../../packages/setup-wizard/src/triage/gate-display.ts
|
|
35575
|
-
function findContext(entry,
|
|
35576
|
-
const byFingerprint =
|
|
36389
|
+
function findContext(entry, join29) {
|
|
36390
|
+
const byFingerprint = join29.find(
|
|
35577
36391
|
(j) => j.valueFingerprint !== void 0 && j.valueFingerprint === entry.valueFingerprint
|
|
35578
36392
|
);
|
|
35579
36393
|
if (byFingerprint) return byFingerprint.maskedContext;
|
|
35580
|
-
const byRuleAndMask =
|
|
36394
|
+
const byRuleAndMask = join29.find(
|
|
35581
36395
|
(j) => j.ruleId === entry.ruleId && j.maskedMatch === entry.maskedValue
|
|
35582
36396
|
);
|
|
35583
36397
|
return byRuleAndMask?.maskedContext;
|
|
@@ -35648,13 +36462,13 @@ function renderShowcase(showcase) {
|
|
|
35648
36462
|
|
|
35649
36463
|
${blocks.join("\n\n")}`;
|
|
35650
36464
|
}
|
|
35651
|
-
function renderSuppressionGate(entries,
|
|
36465
|
+
function renderSuppressionGate(entries, join29) {
|
|
35652
36466
|
if (entries.length === 0) {
|
|
35653
36467
|
return "No false-positive suppressions to confirm \u2014 nothing will be written.";
|
|
35654
36468
|
}
|
|
35655
36469
|
const header = entries.length === 1 ? "This looks like a false positive \u2014 take a look before I suppress it:" : `These ${String(entries.length)} look like false positives \u2014 take a look before I suppress them:`;
|
|
35656
36470
|
const blocks = entries.map((entry, i) => {
|
|
35657
|
-
const context = findContext(entry,
|
|
36471
|
+
const context = findContext(entry, join29);
|
|
35658
36472
|
const lines = [
|
|
35659
36473
|
`${String(i + 1)}. ${entry.ruleId} [${entry.category}]`,
|
|
35660
36474
|
` value: ${entry.maskedValue}`,
|
|
@@ -35740,9 +36554,9 @@ function mergeRecommendations(verdicts) {
|
|
|
35740
36554
|
}
|
|
35741
36555
|
|
|
35742
36556
|
// ../../packages/setup-wizard/src/triage/plan-file.ts
|
|
35743
|
-
import { mkdtempSync, readFileSync as
|
|
36557
|
+
import { mkdtempSync, readFileSync as readFileSync16, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
|
|
35744
36558
|
import { tmpdir } from "os";
|
|
35745
|
-
import { basename as basename6, dirname as dirname6, join as
|
|
36559
|
+
import { basename as basename6, dirname as dirname6, join as join26 } from "path";
|
|
35746
36560
|
var SuppressionEntrySchema = external_exports.object({
|
|
35747
36561
|
ruleId: external_exports.string(),
|
|
35748
36562
|
category: DetectionCategory,
|
|
@@ -35797,13 +36611,13 @@ function serializePlan(plan, current) {
|
|
|
35797
36611
|
function writePlanFile(plan, current, rawValues, deps = {}) {
|
|
35798
36612
|
const serialized = serializePlan(plan, current);
|
|
35799
36613
|
assertRawFree(serialized, rawValues);
|
|
35800
|
-
const dir = (deps.mkTempDir ?? (() => mkdtempSync(
|
|
35801
|
-
const path =
|
|
36614
|
+
const dir = (deps.mkTempDir ?? (() => mkdtempSync(join26(tmpdir(), "aka-plan-"))))();
|
|
36615
|
+
const path = join26(dir, "setup-plan.json");
|
|
35802
36616
|
writeFileSync9(path, serialized, { encoding: "utf8", mode: 384 });
|
|
35803
36617
|
return path;
|
|
35804
36618
|
}
|
|
35805
36619
|
function readPlanFile(path) {
|
|
35806
|
-
const text =
|
|
36620
|
+
const text = readFileSync16(path, "utf8");
|
|
35807
36621
|
const json2 = JSON.parse(text);
|
|
35808
36622
|
return PersistedPlanSchema.parse(json2);
|
|
35809
36623
|
}
|
|
@@ -35877,8 +36691,8 @@ function buildJoinEntries(hits) {
|
|
|
35877
36691
|
}
|
|
35878
36692
|
|
|
35879
36693
|
// ../../packages/setup-wizard/src/triage/resolve.ts
|
|
35880
|
-
function resolveSuppressions(rec,
|
|
35881
|
-
const byId = new Map(
|
|
36694
|
+
function resolveSuppressions(rec, join29) {
|
|
36695
|
+
const byId = new Map(join29.map((e) => [e.id, e]));
|
|
35882
36696
|
const entries = [];
|
|
35883
36697
|
const skipped = [];
|
|
35884
36698
|
for (const cat of rec.perCategory) {
|
|
@@ -35980,7 +36794,7 @@ function parseTriageStream(text) {
|
|
|
35980
36794
|
return { hits, status: "complete" };
|
|
35981
36795
|
}
|
|
35982
36796
|
function planTriageWriteback(hits, rec) {
|
|
35983
|
-
const
|
|
36797
|
+
const join29 = buildJoinEntries(hits);
|
|
35984
36798
|
const rawValues = hits.map((h) => h.rawMatch);
|
|
35985
36799
|
const skipped = [];
|
|
35986
36800
|
const posture = {};
|
|
@@ -36020,7 +36834,7 @@ function planTriageWriteback(hits, rec) {
|
|
|
36020
36834
|
}
|
|
36021
36835
|
const { entries, skipped: resolveSkips } = resolveSuppressions(
|
|
36022
36836
|
{ perCategory: safeCategories, notes: rec.notes },
|
|
36023
|
-
|
|
36837
|
+
join29
|
|
36024
36838
|
);
|
|
36025
36839
|
skipped.push(...resolveSkips);
|
|
36026
36840
|
let notes = rec.notes;
|
|
@@ -36030,7 +36844,7 @@ function planTriageWriteback(hits, rec) {
|
|
|
36030
36844
|
if (err instanceof RawEgressError) notes = SCRUBBED_NOTES;
|
|
36031
36845
|
else throw err;
|
|
36032
36846
|
}
|
|
36033
|
-
return { entries, posture, showcase, join:
|
|
36847
|
+
return { entries, posture, showcase, join: join29, notes, skipped };
|
|
36034
36848
|
}
|
|
36035
36849
|
function recommendedPosture(evidence) {
|
|
36036
36850
|
return { ...severityFloorPosture(), ...evidence };
|
|
@@ -36299,9 +37113,9 @@ function parseRecommendation(text) {
|
|
|
36299
37113
|
|
|
36300
37114
|
// src/triage/judge.ts
|
|
36301
37115
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
36302
|
-
import { mkdtempSync as mkdtempSync2, readFileSync as
|
|
37116
|
+
import { mkdtempSync as mkdtempSync2, readFileSync as readFileSync17, rmSync as rmSync8 } from "fs";
|
|
36303
37117
|
import { tmpdir as tmpdir2 } from "os";
|
|
36304
|
-
import { dirname as dirname7, join as
|
|
37118
|
+
import { dirname as dirname7, join as join27 } from "path";
|
|
36305
37119
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
36306
37120
|
|
|
36307
37121
|
// ../../packages/plugin-sdk/src/bare-command.ts
|
|
@@ -36413,7 +37227,7 @@ function planBareCommand(command, args, deps = {}) {
|
|
|
36413
37227
|
|
|
36414
37228
|
// src/triage/judge.ts
|
|
36415
37229
|
var TRIAGE_DIR = dirname7(fileURLToPath2(import.meta.url));
|
|
36416
|
-
var DEFAULT_RUBRIC_PATH =
|
|
37230
|
+
var DEFAULT_RUBRIC_PATH = join27(
|
|
36417
37231
|
TRIAGE_DIR,
|
|
36418
37232
|
"..",
|
|
36419
37233
|
"..",
|
|
@@ -36450,7 +37264,7 @@ function judgeEnv(platform2 = process.platform) {
|
|
|
36450
37264
|
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1"
|
|
36451
37265
|
};
|
|
36452
37266
|
if (platform2 === "darwin") {
|
|
36453
|
-
env.CLAUDE_CONFIG_DIR = mkdtempSync2(
|
|
37267
|
+
env.CLAUDE_CONFIG_DIR = mkdtempSync2(join27(tmpdir2(), "aka-judge-cfg-"));
|
|
36454
37268
|
}
|
|
36455
37269
|
return env;
|
|
36456
37270
|
}
|
|
@@ -36485,7 +37299,7 @@ function runJudge(hits, deps) {
|
|
|
36485
37299
|
if (typeof deps.spawn !== "function") {
|
|
36486
37300
|
throw new TypeError("runJudge requires deps.spawn \u2014 there is no live-spawn fallback");
|
|
36487
37301
|
}
|
|
36488
|
-
const rubric = deps.loadRubric?.() ??
|
|
37302
|
+
const rubric = deps.loadRubric?.() ?? readFileSync17(DEFAULT_RUBRIC_PATH, "utf8");
|
|
36489
37303
|
const hitsJsonl = hits.map((h) => JSON.stringify(toJudgePayload(h))).join("\n");
|
|
36490
37304
|
const fullPrompt = `${rubric}
|
|
36491
37305
|
|
|
@@ -36755,10 +37569,10 @@ function resolveCreatedBy() {
|
|
|
36755
37569
|
}
|
|
36756
37570
|
function loadRubric() {
|
|
36757
37571
|
const here = dirname8(fileURLToPath4(import.meta.url));
|
|
36758
|
-
const shipped =
|
|
36759
|
-
if (
|
|
36760
|
-
return
|
|
36761
|
-
|
|
37572
|
+
const shipped = join28(here, "triage-rubric.md");
|
|
37573
|
+
if (existsSync12(shipped)) return readFileSync18(shipped, "utf8");
|
|
37574
|
+
return readFileSync18(
|
|
37575
|
+
join28(here, "..", "..", "..", "packages", "setup-wizard", "assets", "triage-rubric.md"),
|
|
36762
37576
|
"utf8"
|
|
36763
37577
|
);
|
|
36764
37578
|
}
|
|
@@ -36768,7 +37582,7 @@ async function main() {
|
|
|
36768
37582
|
argv,
|
|
36769
37583
|
// fd 0 = stdin; the wizard pipes `backfill.js --triage` into this on preview.
|
|
36770
37584
|
// Called only on the preview path — the confirm path never reads a stream.
|
|
36771
|
-
readStream: (streamPath) => streamPath !== void 0 ?
|
|
37585
|
+
readStream: (streamPath) => streamPath !== void 0 ? readFileSync18(streamPath, "utf8") : readFileSync18(0, "utf8"),
|
|
36772
37586
|
runJudge: (hits) => runJudge(hits, { spawn: spawnClaude, loadRubric }),
|
|
36773
37587
|
// The distinct model-judge egress consent, read from settings.json. When it
|
|
36774
37588
|
// is absent or stale the preview skips the judge instead of sending findings
|