@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 SLASH3 = "/";
|
|
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(SLASH3).filter(Boolean);
|
|
426
426
|
slices.pop();
|
|
427
427
|
if (slices.length) {
|
|
428
428
|
const parent = this._t(
|
|
429
|
-
slices.join(
|
|
429
|
+
slices.join(SLASH3) + SLASH3,
|
|
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(SLASH3).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(SLASH3) + SLASH3,
|
|
453
453
|
cache,
|
|
454
454
|
checkUnignored,
|
|
455
455
|
slices
|
|
@@ -492,8 +492,8 @@ var require_ignore = __commonJS({
|
|
|
492
492
|
});
|
|
493
493
|
|
|
494
494
|
// ../../packages/plugin-sdk/src/config.ts
|
|
495
|
-
import { existsSync as
|
|
496
|
-
import { join as
|
|
495
|
+
import { existsSync as existsSync8 } from "fs";
|
|
496
|
+
import { join as join16 } from "path";
|
|
497
497
|
|
|
498
498
|
// ../../packages/persistence/src/attached-derived.ts
|
|
499
499
|
import { rmSync } from "fs";
|
|
@@ -506,6 +506,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.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(),
|
|
@@ -22101,6 +22239,14 @@ var ControlPlaneErrorBody = external_exports.object({
|
|
|
22101
22239
|
message: external_exports.string().optional()
|
|
22102
22240
|
}).optional()
|
|
22103
22241
|
});
|
|
22242
|
+
var RemoteFailureKind = external_exports.enum([
|
|
22243
|
+
"unauthorized",
|
|
22244
|
+
"forbidden",
|
|
22245
|
+
"route-absent",
|
|
22246
|
+
"invalid-request",
|
|
22247
|
+
"rejected",
|
|
22248
|
+
"unreachable"
|
|
22249
|
+
]);
|
|
22104
22250
|
var AttachDeviceRequest = external_exports.object({
|
|
22105
22251
|
// This machine's own continuity id, so re-attaching ROTATES the credential
|
|
22106
22252
|
// on one machine record instead of producing a second one. Client-minted
|
|
@@ -22636,6 +22782,12 @@ var EventMetadata = external_exports.object({
|
|
|
22636
22782
|
// to 'allow' — the enforcement audit trail's link back to the grant that
|
|
22637
22783
|
// authorized the bypass. Absent on captures where no exception applied.
|
|
22638
22784
|
exceptionIds: external_exports.array(external_exports.guid()).optional(),
|
|
22785
|
+
// The assistant message this capture belongs to, and the conversation it sits
|
|
22786
|
+
// in — set by the browser extension's network capture so a stored `response`
|
|
22787
|
+
// row can be joined to the `llm_call` leaf describing the same turn. Absent
|
|
22788
|
+
// on every other capture path, which has no such id.
|
|
22789
|
+
messageId: external_exports.string().optional(),
|
|
22790
|
+
conversationId: external_exports.string().optional(),
|
|
22639
22791
|
// How long THIS capture's inspection blocked its caller, in whole
|
|
22640
22792
|
// milliseconds — the plugin's own added latency, NOT the LLM call it sat in
|
|
22641
22793
|
// front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
|
|
@@ -22648,7 +22800,37 @@ var EventMetadata = external_exports.object({
|
|
|
22648
22800
|
// Absent is also what every pre-measurement client writes, and what a
|
|
22649
22801
|
// clock failure degrades to — a reader must treat absence as "not measured"
|
|
22650
22802
|
// and never as a zero, which would read as "inspection is free".
|
|
22651
|
-
inspectionMs: external_exports.number().int().nonnegative().optional()
|
|
22803
|
+
inspectionMs: external_exports.number().int().nonnegative().optional(),
|
|
22804
|
+
// What a `redact` this capture COULD NOT CARRY OUT became instead — the
|
|
22805
|
+
// workspace's `redactFallback`, applied because the field could not be
|
|
22806
|
+
// masked in place (a shell command, a URL, or any argument on a host whose
|
|
22807
|
+
// hook contract offers no rewrite channel).
|
|
22808
|
+
//
|
|
22809
|
+
// It exists because the action alone cannot say why. A finding recorded as
|
|
22810
|
+
// `warn` reads identically whether its detection was ASSIGNED Warn or was
|
|
22811
|
+
// assigned Redact on a field that could not take one — and those are
|
|
22812
|
+
// different facts about the same row: the first is a policy the user chose,
|
|
22813
|
+
// the second is a masking the host could not perform. Absent means no
|
|
22814
|
+
// degrade happened, which is every ordinary capture.
|
|
22815
|
+
//
|
|
22816
|
+
// TWO LIMITS a reader of a stored row has to know, because the grain here
|
|
22817
|
+
// is the CAPTURE while `actionTaken` is per FINDING:
|
|
22818
|
+
//
|
|
22819
|
+
// - It does not say WHICH finding degraded. A capture carrying a degraded
|
|
22820
|
+
// `redact` alongside a finding ASSIGNED the same action stores both
|
|
22821
|
+
// identically and one reason for the pair; attributing it to both
|
|
22822
|
+
// describes the assigned one wrongly, and to neither loses the degrade.
|
|
22823
|
+
// - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
|
|
22824
|
+
// became, not the reason the capture ended as it did — a capture denied
|
|
22825
|
+
// by some other finding's own Block policy still carries `block` here,
|
|
22826
|
+
// and clearing the workspace's fallback would not have let it through.
|
|
22827
|
+
// Gate on the value against what a fallback can produce; never read the
|
|
22828
|
+
// field's presence as "this was the fallback's doing".
|
|
22829
|
+
//
|
|
22830
|
+
// Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
|
|
22831
|
+
// Closing either means moving the reason onto the finding row, which
|
|
22832
|
+
// already carries its own action.
|
|
22833
|
+
redactDegradedTo: ActionTaken.optional()
|
|
22652
22834
|
}).meta({ id: "EventMetadata" });
|
|
22653
22835
|
var Event = external_exports.object({
|
|
22654
22836
|
id: external_exports.guid(),
|
|
@@ -22758,7 +22940,32 @@ var RotateKeyInput = external_exports.object({
|
|
|
22758
22940
|
confirmation: external_exports.string()
|
|
22759
22941
|
});
|
|
22760
22942
|
|
|
22943
|
+
// ../../packages/schema/src/zod/finding-delivery.ts
|
|
22944
|
+
var KNOWN_REASONS = SyncFailureReason.options;
|
|
22945
|
+
function knownReason(value) {
|
|
22946
|
+
return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
|
|
22947
|
+
}
|
|
22948
|
+
function deriveFindingDelivery(row) {
|
|
22949
|
+
if (row.kind === "code_change") return { state: "local_scan" };
|
|
22950
|
+
if (row.syncedAt !== null && row.syncedAt > 0) {
|
|
22951
|
+
return { state: "sent", at: epochMillisToIso(row.syncedAt) };
|
|
22952
|
+
}
|
|
22953
|
+
if (row.syncedAt !== null) {
|
|
22954
|
+
const reason = knownReason(row.syncFailure);
|
|
22955
|
+
return {
|
|
22956
|
+
state: "not_sent",
|
|
22957
|
+
...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
|
|
22958
|
+
...reason === void 0 ? {} : { reason }
|
|
22959
|
+
};
|
|
22960
|
+
}
|
|
22961
|
+
if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
|
|
22962
|
+
return { state: "never_offered" };
|
|
22963
|
+
}
|
|
22964
|
+
|
|
22761
22965
|
// ../../packages/schema/src/zod/findings-group-build.ts
|
|
22966
|
+
function lookupOwn(map2, key) {
|
|
22967
|
+
return Object.hasOwn(map2, key) ? map2[key] : void 0;
|
|
22968
|
+
}
|
|
22762
22969
|
function toApiAction(dbVal) {
|
|
22763
22970
|
const map2 = {
|
|
22764
22971
|
log: "monitored",
|
|
@@ -22767,7 +22974,7 @@ function toApiAction(dbVal) {
|
|
|
22767
22974
|
warn: "warned",
|
|
22768
22975
|
allow: "allowed"
|
|
22769
22976
|
};
|
|
22770
|
-
return map2
|
|
22977
|
+
return lookupOwn(map2, dbVal) ?? "allowed";
|
|
22771
22978
|
}
|
|
22772
22979
|
function toApiCategory(dbVal) {
|
|
22773
22980
|
if (dbVal === "code_context") return "source_code";
|
|
@@ -22775,13 +22982,18 @@ function toApiCategory(dbVal) {
|
|
|
22775
22982
|
return parsed2.success ? parsed2.data : "custom";
|
|
22776
22983
|
}
|
|
22777
22984
|
function toApiProvider(sourceTool) {
|
|
22778
|
-
return TOOL_TO_HARNESS
|
|
22985
|
+
return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
|
|
22779
22986
|
}
|
|
22780
|
-
var
|
|
22987
|
+
var FINDING_STATUS_PRECEDENCE = [
|
|
22988
|
+
"open",
|
|
22989
|
+
"handled",
|
|
22990
|
+
"dismissed",
|
|
22991
|
+
"resolved"
|
|
22992
|
+
];
|
|
22781
22993
|
function foldGroupStatus(instanceStatuses) {
|
|
22782
22994
|
const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
|
|
22783
22995
|
if (statuses.size === 0) return void 0;
|
|
22784
|
-
for (const candidate of
|
|
22996
|
+
for (const candidate of FINDING_STATUS_PRECEDENCE) {
|
|
22785
22997
|
if (statuses.has(candidate)) return candidate;
|
|
22786
22998
|
}
|
|
22787
22999
|
return void 0;
|
|
@@ -22794,139 +23006,62 @@ function deriveFindingStatus(row) {
|
|
|
22794
23006
|
if (row.latestResolutionStatus === "dismissed") return "dismissed";
|
|
22795
23007
|
return "open";
|
|
22796
23008
|
}
|
|
22797
|
-
function distinctUsers(instances) {
|
|
22798
|
-
const seen = /* @__PURE__ */ new Set();
|
|
22799
|
-
const users = [];
|
|
22800
|
-
for (const i of instances) {
|
|
22801
|
-
if (i.user === void 0 || seen.has(i.user.id)) continue;
|
|
22802
|
-
seen.add(i.user.id);
|
|
22803
|
-
users.push(i.user);
|
|
22804
|
-
}
|
|
22805
|
-
return users;
|
|
22806
|
-
}
|
|
22807
23009
|
function sortUsers(users) {
|
|
22808
23010
|
return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
|
|
22809
23011
|
}
|
|
22810
|
-
function
|
|
22811
|
-
const overrides = opts.overrides;
|
|
23012
|
+
function buildFindingTypes(aggregates, opts = {}) {
|
|
22812
23013
|
const packNames = opts.packNames;
|
|
22813
|
-
const
|
|
22814
|
-
const
|
|
22815
|
-
|
|
22816
|
-
const
|
|
22817
|
-
|
|
22818
|
-
else byRuleId.set(row.ruleId, [row]);
|
|
22819
|
-
}
|
|
22820
|
-
const groups = [];
|
|
22821
|
-
for (const [ruleId, ruleRows] of byRuleId) {
|
|
22822
|
-
const instances = ruleRows.map((r) => {
|
|
22823
|
-
const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
|
|
22824
|
-
return {
|
|
22825
|
-
id: r.id,
|
|
22826
|
-
provider: toApiProvider(r.sourceTool),
|
|
22827
|
-
repo: r.repo,
|
|
22828
|
-
file: r.file,
|
|
22829
|
-
...r.toolName === void 0 ? {} : { toolName: r.toolName },
|
|
22830
|
-
...r.eventId === void 0 ? {} : { eventId: r.eventId },
|
|
22831
|
-
...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
|
|
22832
|
-
...r.user === void 0 ? {} : { user: r.user },
|
|
22833
|
-
action: toApiAction(effectiveDbAction),
|
|
22834
|
-
detectedAt: r.occurredAt,
|
|
22835
|
-
confidence: r.confidence,
|
|
22836
|
-
status: r.status
|
|
22837
|
-
};
|
|
22838
|
-
});
|
|
22839
|
-
const agg = aggregates?.get(ruleId);
|
|
22840
|
-
const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
|
|
22841
|
-
const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
|
|
22842
|
-
(max, r) => r.occurredAt > max ? r.occurredAt : max,
|
|
22843
|
-
ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
|
|
22844
|
-
);
|
|
22845
|
-
const seenProviders = /* @__PURE__ */ new Set();
|
|
22846
|
-
const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
|
|
22847
|
-
if (seenProviders.has(p)) return false;
|
|
22848
|
-
seenProviders.add(p);
|
|
22849
|
-
return true;
|
|
22850
|
-
});
|
|
22851
|
-
const actionSet = new Set(
|
|
22852
|
-
agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
|
|
22853
|
-
);
|
|
23014
|
+
const types = [];
|
|
23015
|
+
for (const [ruleId, agg] of aggregates) {
|
|
23016
|
+
const users = sortUsers(agg.users ?? []);
|
|
23017
|
+
const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
|
|
23018
|
+
const actionSet = new Set(agg.actionsTaken.map(toApiAction));
|
|
22854
23019
|
const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
|
|
22855
|
-
const
|
|
22856
|
-
const
|
|
22857
|
-
id: ruleId,
|
|
22858
|
-
name: packNames?.get(ruleId) ?? null
|
|
22859
|
-
};
|
|
22860
|
-
const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
|
|
22861
|
-
const policy = { id: `category:${apiCategory}`, name: apiCategory };
|
|
22862
|
-
const match = {
|
|
22863
|
-
maskedValue: ruleRows[0]?.maskedMatch ?? "",
|
|
22864
|
-
contextPrefix: ""
|
|
22865
|
-
// empty (pending privacy review)
|
|
22866
|
-
};
|
|
22867
|
-
const status = foldGroupStatus(
|
|
22868
|
-
agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
|
|
22869
|
-
);
|
|
22870
|
-
const group = {
|
|
23020
|
+
const apiCategory = toApiCategory(agg.category ?? "custom");
|
|
23021
|
+
const type = {
|
|
22871
23022
|
id: ruleId,
|
|
22872
23023
|
category: apiCategory,
|
|
22873
23024
|
subtype: ruleId,
|
|
22874
23025
|
// human label comes with pack metadata later
|
|
22875
|
-
severity,
|
|
22876
|
-
|
|
22877
|
-
|
|
22878
|
-
|
|
22879
|
-
instanceCount: agg?.instanceCount ?? instances.length,
|
|
23026
|
+
severity: agg.severity ?? "low",
|
|
23027
|
+
detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
|
|
23028
|
+
policy: { id: `category:${apiCategory}`, name: apiCategory },
|
|
23029
|
+
instanceCount: agg.instanceCount,
|
|
22880
23030
|
providers,
|
|
22881
23031
|
aggregateAction,
|
|
22882
|
-
latestDetectedAt,
|
|
22883
|
-
|
|
22884
|
-
status,
|
|
23032
|
+
latestDetectedAt: agg.latestDetectedAt,
|
|
23033
|
+
status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
|
|
22885
23034
|
...users.length > 0 ? { users } : {}
|
|
22886
23035
|
};
|
|
22887
|
-
|
|
22888
|
-
|
|
22889
|
-
|
|
22890
|
-
haystackCache.set(group, buildHaystack(group, agg.searchText));
|
|
22891
|
-
}
|
|
23036
|
+
actionsCache.set(type, [...actionSet]);
|
|
23037
|
+
if (agg.searchText !== void 0) {
|
|
23038
|
+
haystackCache.set(type, buildHaystack(type, agg.searchText));
|
|
22892
23039
|
}
|
|
22893
|
-
|
|
23040
|
+
types.push(type);
|
|
22894
23041
|
}
|
|
22895
|
-
return
|
|
23042
|
+
return types;
|
|
22896
23043
|
}
|
|
22897
23044
|
var haystackCache = /* @__PURE__ */ new WeakMap();
|
|
22898
|
-
function buildHaystack(
|
|
23045
|
+
function buildHaystack(t, extra) {
|
|
22899
23046
|
return [
|
|
22900
|
-
|
|
22901
|
-
|
|
22902
|
-
|
|
22903
|
-
|
|
22904
|
-
|
|
22905
|
-
...g.instances.map((i) => i.repo),
|
|
22906
|
-
...g.instances.map((i) => i.file),
|
|
22907
|
-
...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
|
|
22908
|
-
...g.instances.map((i) => i.id),
|
|
22909
|
-
// The people: the whole group's list when the store folded one, plus the
|
|
22910
|
-
// preview's own — the two overlap, and a haystack does not mind.
|
|
22911
|
-
...(g.users ?? []).map((u) => u.name),
|
|
22912
|
-
...g.instances.map((i) => i.user?.name ?? ""),
|
|
23047
|
+
t.subtype,
|
|
23048
|
+
t.category,
|
|
23049
|
+
t.policy.name,
|
|
23050
|
+
t.id,
|
|
23051
|
+
...(t.users ?? []).map((u) => u.name),
|
|
22913
23052
|
...extra === void 0 ? [] : [extra]
|
|
22914
23053
|
].join(" ").toLowerCase();
|
|
22915
23054
|
}
|
|
22916
|
-
function
|
|
22917
|
-
const cached2 = haystackCache.get(
|
|
23055
|
+
function typeHaystack(t) {
|
|
23056
|
+
const cached2 = haystackCache.get(t);
|
|
22918
23057
|
if (cached2 !== void 0) return cached2;
|
|
22919
|
-
const haystack = buildHaystack(
|
|
22920
|
-
haystackCache.set(
|
|
23058
|
+
const haystack = buildHaystack(t);
|
|
23059
|
+
haystackCache.set(t, haystack);
|
|
22921
23060
|
return haystack;
|
|
22922
23061
|
}
|
|
22923
23062
|
var actionsCache = /* @__PURE__ */ new WeakMap();
|
|
22924
|
-
function
|
|
22925
|
-
|
|
22926
|
-
if (cached2 !== void 0) return cached2;
|
|
22927
|
-
const actions = [...new Set(g.instances.map((i) => i.action))];
|
|
22928
|
-
actionsCache.set(g, actions);
|
|
22929
|
-
return actions;
|
|
23063
|
+
function typeActions(t) {
|
|
23064
|
+
return actionsCache.get(t) ?? [];
|
|
22930
23065
|
}
|
|
22931
23066
|
function countInstancesByStatus(statusInputs, statuses) {
|
|
22932
23067
|
const statusSet = new Set(statuses);
|
|
@@ -22937,8 +23072,8 @@ function countInstancesByStatus(statusInputs, statuses) {
|
|
|
22937
23072
|
}
|
|
22938
23073
|
return sum;
|
|
22939
23074
|
}
|
|
22940
|
-
function applyFindingFilters(
|
|
22941
|
-
let filtered =
|
|
23075
|
+
function applyFindingFilters(types, opts) {
|
|
23076
|
+
let filtered = types;
|
|
22942
23077
|
if (opts.severity && opts.severity.length > 0) {
|
|
22943
23078
|
const sevSet = new Set(opts.severity);
|
|
22944
23079
|
filtered = filtered.filter((g) => sevSet.has(g.severity));
|
|
@@ -22949,7 +23084,7 @@ function applyFindingFilters(groups, opts) {
|
|
|
22949
23084
|
}
|
|
22950
23085
|
if (opts.actions && opts.actions.length > 0) {
|
|
22951
23086
|
const actionSet = new Set(opts.actions);
|
|
22952
|
-
filtered = filtered.filter((
|
|
23087
|
+
filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
|
|
22953
23088
|
}
|
|
22954
23089
|
if (opts.subtype && opts.subtype.length > 0) {
|
|
22955
23090
|
const subtypeSet = new Set(opts.subtype);
|
|
@@ -22961,26 +23096,31 @@ function applyFindingFilters(groups, opts) {
|
|
|
22961
23096
|
}
|
|
22962
23097
|
if (opts.q) {
|
|
22963
23098
|
const q = opts.q.toLowerCase();
|
|
22964
|
-
filtered = filtered.filter((
|
|
23099
|
+
filtered = filtered.filter((t) => typeHaystack(t).includes(q));
|
|
22965
23100
|
}
|
|
22966
23101
|
return filtered;
|
|
22967
23102
|
}
|
|
22968
|
-
|
|
22969
|
-
|
|
23103
|
+
function rankByOrder(members2) {
|
|
23104
|
+
return Object.fromEntries(members2.map((member, index) => [member, index]));
|
|
23105
|
+
}
|
|
23106
|
+
var SEVERITY_RANK = rankByOrder(Severity.options);
|
|
23107
|
+
function severityRank(severity) {
|
|
23108
|
+
return lookupOwn(SEVERITY_RANK, severity);
|
|
23109
|
+
}
|
|
22970
23110
|
function compareFindingGroupOrder(a, b) {
|
|
22971
|
-
const rankA =
|
|
22972
|
-
const rankB =
|
|
23111
|
+
const rankA = severityRank(a.severity) ?? -1;
|
|
23112
|
+
const rankB = severityRank(b.severity) ?? -1;
|
|
22973
23113
|
const severityDiff = rankA - rankB;
|
|
22974
23114
|
if (severityDiff !== 0) return severityDiff;
|
|
22975
23115
|
const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
|
|
22976
23116
|
if (recencyDiff !== 0) return recencyDiff;
|
|
22977
23117
|
return a.id.localeCompare(b.id);
|
|
22978
23118
|
}
|
|
22979
|
-
function
|
|
22980
|
-
return [...
|
|
23119
|
+
function sortFindingTypes(types) {
|
|
23120
|
+
return [...types].sort(compareFindingGroupOrder);
|
|
22981
23121
|
}
|
|
22982
|
-
function computeFindingFacets(
|
|
22983
|
-
const forSeverity = applyFindingFilters(
|
|
23122
|
+
function computeFindingFacets(allTypes, opts) {
|
|
23123
|
+
const forSeverity = applyFindingFilters(allTypes, {
|
|
22984
23124
|
providers: opts.providers,
|
|
22985
23125
|
actions: opts.actions,
|
|
22986
23126
|
statuses: opts.statuses,
|
|
@@ -22991,7 +23131,7 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
22991
23131
|
for (const g of forSeverity) {
|
|
22992
23132
|
severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
|
|
22993
23133
|
}
|
|
22994
|
-
const forProvider = applyFindingFilters(
|
|
23134
|
+
const forProvider = applyFindingFilters(allTypes, {
|
|
22995
23135
|
actions: opts.actions,
|
|
22996
23136
|
statuses: opts.statuses,
|
|
22997
23137
|
q: opts.q,
|
|
@@ -23002,7 +23142,7 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
23002
23142
|
for (const g of forProvider) {
|
|
23003
23143
|
for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
|
|
23004
23144
|
}
|
|
23005
|
-
const forAction = applyFindingFilters(
|
|
23145
|
+
const forAction = applyFindingFilters(allTypes, {
|
|
23006
23146
|
providers: opts.providers,
|
|
23007
23147
|
statuses: opts.statuses,
|
|
23008
23148
|
q: opts.q,
|
|
@@ -23011,9 +23151,9 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
23011
23151
|
});
|
|
23012
23152
|
const actionMap = /* @__PURE__ */ new Map();
|
|
23013
23153
|
for (const g of forAction) {
|
|
23014
|
-
for (const a of
|
|
23154
|
+
for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
|
|
23015
23155
|
}
|
|
23016
|
-
const forSubtype = applyFindingFilters(
|
|
23156
|
+
const forSubtype = applyFindingFilters(allTypes, {
|
|
23017
23157
|
providers: opts.providers,
|
|
23018
23158
|
actions: opts.actions,
|
|
23019
23159
|
statuses: opts.statuses,
|
|
@@ -23022,7 +23162,7 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
23022
23162
|
});
|
|
23023
23163
|
const subtypeMap = /* @__PURE__ */ new Map();
|
|
23024
23164
|
for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
|
|
23025
|
-
const forStatus = applyFindingFilters(
|
|
23165
|
+
const forStatus = applyFindingFilters(allTypes, {
|
|
23026
23166
|
providers: opts.providers,
|
|
23027
23167
|
actions: opts.actions,
|
|
23028
23168
|
q: opts.q,
|
|
@@ -23044,6 +23184,20 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
23044
23184
|
}
|
|
23045
23185
|
|
|
23046
23186
|
// ../../packages/schema/src/zod/findings-flat-build.ts
|
|
23187
|
+
function compareCodePoints(a, b) {
|
|
23188
|
+
const aIter = a[Symbol.iterator]();
|
|
23189
|
+
const bIter = b[Symbol.iterator]();
|
|
23190
|
+
for (; ; ) {
|
|
23191
|
+
const aNext = aIter.next();
|
|
23192
|
+
const bNext = bIter.next();
|
|
23193
|
+
if (aNext.done && bNext.done) return 0;
|
|
23194
|
+
if (aNext.done) return -1;
|
|
23195
|
+
if (bNext.done) return 1;
|
|
23196
|
+
const aPoint = aNext.value.codePointAt(0) ?? 0;
|
|
23197
|
+
const bPoint = bNext.value.codePointAt(0) ?? 0;
|
|
23198
|
+
if (aPoint !== bPoint) return aPoint - bPoint;
|
|
23199
|
+
}
|
|
23200
|
+
}
|
|
23047
23201
|
function rowHaystack(row) {
|
|
23048
23202
|
return [
|
|
23049
23203
|
row.ruleId,
|
|
@@ -23068,12 +23222,24 @@ function matchesDimension(row, opts, dimension) {
|
|
|
23068
23222
|
return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
|
|
23069
23223
|
case "statuses":
|
|
23070
23224
|
return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
|
|
23225
|
+
case "deliveries":
|
|
23226
|
+
return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
|
|
23071
23227
|
case "tools":
|
|
23072
23228
|
return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
|
|
23229
|
+
// An EMPTY value is a real filter here, not an absent one. The location
|
|
23230
|
+
// list buckets a finding whose event recorded no repo — or no file — under
|
|
23231
|
+
// the empty string, and selecting that bucket has to narrow the panel to
|
|
23232
|
+
// exactly it. Only `undefined` means "no filter"; a caller that wants every
|
|
23233
|
+
// row omits the key, which every call site already does.
|
|
23234
|
+
//
|
|
23235
|
+
// Reading '' as unset is what this replaced, and it failed in the one place
|
|
23236
|
+
// it mattered: the no-repo/no-file bucket is often the largest in a real
|
|
23237
|
+
// store, and its panel dropped both predicates and returned the WHOLE scope
|
|
23238
|
+
// — a row reading 3 findings beside a panel listing every finding there is.
|
|
23073
23239
|
case "repo":
|
|
23074
|
-
return opts.repo === void 0 ||
|
|
23240
|
+
return opts.repo === void 0 || row.repo === opts.repo;
|
|
23075
23241
|
case "file":
|
|
23076
|
-
return opts.file === void 0 ||
|
|
23242
|
+
return opts.file === void 0 || row.file === opts.file;
|
|
23077
23243
|
case "q":
|
|
23078
23244
|
return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
|
|
23079
23245
|
}
|
|
@@ -23084,6 +23250,7 @@ var DIMENSIONS = [
|
|
|
23084
23250
|
"providers",
|
|
23085
23251
|
"actions",
|
|
23086
23252
|
"statuses",
|
|
23253
|
+
"deliveries",
|
|
23087
23254
|
"tools",
|
|
23088
23255
|
"repo",
|
|
23089
23256
|
"file",
|
|
@@ -23097,10 +23264,19 @@ function matchesInstanceFilters(row, opts, except) {
|
|
|
23097
23264
|
return true;
|
|
23098
23265
|
}
|
|
23099
23266
|
function toItems(counts) {
|
|
23100
|
-
return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
|
|
23267
|
+
return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
|
|
23268
|
+
(a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
|
|
23269
|
+
// NFD spelling of the same text) as equal, so a count tie between
|
|
23270
|
+
// them would otherwise be ordered by whichever the Map iteration
|
|
23271
|
+
// produced. compareCodePoints breaks that tie deterministically, which
|
|
23272
|
+
// makes this a TOTAL order — not one that agrees with SQL collation,
|
|
23273
|
+
// which it need not: foldFacetTuples runs this same sort over grouped
|
|
23274
|
+
// tuples, so both paths order facets identically by construction.
|
|
23275
|
+
compareCodePoints(a.value, b.value)
|
|
23276
|
+
);
|
|
23101
23277
|
}
|
|
23102
|
-
function bump(counts, value) {
|
|
23103
|
-
counts.set(value, (counts.get(value) ?? 0) +
|
|
23278
|
+
function bump(counts, value, by = 1) {
|
|
23279
|
+
counts.set(value, (counts.get(value) ?? 0) + by);
|
|
23104
23280
|
}
|
|
23105
23281
|
function createInstanceFacetAccumulator(opts) {
|
|
23106
23282
|
const severity = /* @__PURE__ */ new Map();
|
|
@@ -23109,6 +23285,7 @@ function createInstanceFacetAccumulator(opts) {
|
|
|
23109
23285
|
const action = /* @__PURE__ */ new Map();
|
|
23110
23286
|
const status = /* @__PURE__ */ new Map();
|
|
23111
23287
|
const tool = /* @__PURE__ */ new Map();
|
|
23288
|
+
const deployment = /* @__PURE__ */ new Map();
|
|
23112
23289
|
return {
|
|
23113
23290
|
add(row) {
|
|
23114
23291
|
if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
|
|
@@ -23123,6 +23300,9 @@ function createInstanceFacetAccumulator(opts) {
|
|
|
23123
23300
|
if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
|
|
23124
23301
|
bump(tool, row.toolName);
|
|
23125
23302
|
}
|
|
23303
|
+
if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
|
|
23304
|
+
bump(deployment, row.delivery.state);
|
|
23305
|
+
}
|
|
23126
23306
|
},
|
|
23127
23307
|
facets: () => ({
|
|
23128
23308
|
severity: toItems(severity),
|
|
@@ -23130,7 +23310,8 @@ function createInstanceFacetAccumulator(opts) {
|
|
|
23130
23310
|
provider: toItems(provider),
|
|
23131
23311
|
action: toItems(action),
|
|
23132
23312
|
status: toItems(status),
|
|
23133
|
-
tool: toItems(tool)
|
|
23313
|
+
tool: toItems(tool),
|
|
23314
|
+
deployment: toItems(deployment)
|
|
23134
23315
|
})
|
|
23135
23316
|
};
|
|
23136
23317
|
}
|
|
@@ -23144,6 +23325,7 @@ function toInstanceDetail(row) {
|
|
|
23144
23325
|
...row.toolName === void 0 ? {} : { toolName: row.toolName },
|
|
23145
23326
|
eventId: row.eventId,
|
|
23146
23327
|
...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
|
|
23328
|
+
...row.delivery === void 0 ? {} : { delivery: row.delivery },
|
|
23147
23329
|
...row.user === void 0 ? {} : { user: row.user },
|
|
23148
23330
|
action: toApiAction(row.actionTaken),
|
|
23149
23331
|
detectedAt: row.occurredAt,
|
|
@@ -23158,12 +23340,6 @@ function toInstanceDetail(row) {
|
|
|
23158
23340
|
policy: { id: `category:${category}`, name: category }
|
|
23159
23341
|
};
|
|
23160
23342
|
}
|
|
23161
|
-
var SEVERITY_ORDER2 = {
|
|
23162
|
-
critical: 0,
|
|
23163
|
-
high: 1,
|
|
23164
|
-
medium: 2,
|
|
23165
|
-
low: 3
|
|
23166
|
-
};
|
|
23167
23343
|
function newLocationAccumulator() {
|
|
23168
23344
|
return {
|
|
23169
23345
|
instanceCount: 0,
|
|
@@ -23178,7 +23354,7 @@ function newLocationAccumulator() {
|
|
|
23178
23354
|
}
|
|
23179
23355
|
function addToLocation(acc, row) {
|
|
23180
23356
|
acc.instanceCount += 1;
|
|
23181
|
-
const rank =
|
|
23357
|
+
const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
|
|
23182
23358
|
if (rank < acc.maxSeverityRank) {
|
|
23183
23359
|
acc.maxSeverityRank = rank;
|
|
23184
23360
|
acc.maxSeverity = row.severity;
|
|
@@ -23187,6 +23363,23 @@ function addToLocation(acc, row) {
|
|
|
23187
23363
|
acc.statuses.push(row.status);
|
|
23188
23364
|
acc.ruleIds.add(row.ruleId);
|
|
23189
23365
|
}
|
|
23366
|
+
function compareLocationOrder(a, b) {
|
|
23367
|
+
const rankA = severityRank(a.maxSeverity) ?? -1;
|
|
23368
|
+
const rankB = severityRank(b.maxSeverity) ?? -1;
|
|
23369
|
+
if (rankA !== rankB) return rankA - rankB;
|
|
23370
|
+
if (a.latestDetectedAt !== b.latestDetectedAt) {
|
|
23371
|
+
return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
|
|
23372
|
+
}
|
|
23373
|
+
const repoDiff = compareCodePoints(a.repo, b.repo);
|
|
23374
|
+
if (repoDiff !== 0) return repoDiff;
|
|
23375
|
+
return compareCodePoints(a.file, b.file);
|
|
23376
|
+
}
|
|
23377
|
+
function encodeLocationId(repo, file2) {
|
|
23378
|
+
return `${encodePart(repo)}/${encodePart(file2)}`;
|
|
23379
|
+
}
|
|
23380
|
+
function encodePart(value) {
|
|
23381
|
+
return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
|
|
23382
|
+
}
|
|
23190
23383
|
|
|
23191
23384
|
// ../../packages/schema/src/zod/installed-pack.ts
|
|
23192
23385
|
var InstalledPack = external_exports.object({
|
|
@@ -23254,6 +23447,11 @@ var Policy = external_exports.object({
|
|
|
23254
23447
|
// test `prohibitedModels` passes and `reversibleRuleIds` fails.
|
|
23255
23448
|
provenance: PolicyProvenance.optional()
|
|
23256
23449
|
}).meta({ id: "Policy" });
|
|
23450
|
+
var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
|
|
23451
|
+
var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
|
|
23452
|
+
var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
|
|
23453
|
+
id: "RedactFallback"
|
|
23454
|
+
});
|
|
23257
23455
|
var PolicyBundle = external_exports.object({
|
|
23258
23456
|
version: external_exports.string(),
|
|
23259
23457
|
policies: external_exports.array(Policy),
|
|
@@ -23301,6 +23499,16 @@ var PolicyBundle = external_exports.object({
|
|
|
23301
23499
|
// control plane), so no name resolution stands between the decision and the
|
|
23302
23500
|
// comparison.
|
|
23303
23501
|
prohibitedModels: external_exports.array(external_exports.string()).optional(),
|
|
23502
|
+
// What a resolved `redact` becomes on a field the host cannot rewrite, as
|
|
23503
|
+
// the ORGANIZATION would have it. Merged raise-only against the device's own
|
|
23504
|
+
// `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
|
|
23505
|
+
// a control plane can tighten a machine and never loosen one — the same
|
|
23506
|
+
// direction `mergeRaiseOnly` enforces for policies.
|
|
23507
|
+
//
|
|
23508
|
+
// Optional so an older backend, and an older on-disk cache, still parses;
|
|
23509
|
+
// absent leaves the device's own setting in force, which is the behaviour
|
|
23510
|
+
// that predates the field and the safe direction to default.
|
|
23511
|
+
redactFallback: RedactFallback.optional(),
|
|
23304
23512
|
customKeywords: external_exports.array(external_exports.string()),
|
|
23305
23513
|
fetchedAt: external_exports.iso.datetime()
|
|
23306
23514
|
}).meta({ id: "PolicyBundle" });
|
|
@@ -23330,11 +23538,6 @@ function severityFloorPolicy(category) {
|
|
|
23330
23538
|
const peak = CATEGORY_PEAK_SEVERITY[category];
|
|
23331
23539
|
return peak === "critical" || peak === "high" ? "warn" : "monitor";
|
|
23332
23540
|
}
|
|
23333
|
-
var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
|
|
23334
|
-
var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
|
|
23335
|
-
var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
|
|
23336
|
-
id: "RedactFallback"
|
|
23337
|
-
});
|
|
23338
23541
|
var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
|
|
23339
23542
|
var BUILTIN_POLICY_SPECS = {
|
|
23340
23543
|
monitor: {
|
|
@@ -23390,6 +23593,11 @@ function isActionAtLeast(action, floor) {
|
|
|
23390
23593
|
function strongerAction(a, b) {
|
|
23391
23594
|
return actionRank(a) >= actionRank(b) ? a : b;
|
|
23392
23595
|
}
|
|
23596
|
+
function strongerRedactFallback(local, remote) {
|
|
23597
|
+
if (remote === void 0) return local;
|
|
23598
|
+
const localAction = builtinPolicyToAction(local);
|
|
23599
|
+
return localAction === strongerAction(localAction, builtinPolicyToAction(remote)) ? local : remote;
|
|
23600
|
+
}
|
|
23393
23601
|
function weakestBuiltinAtLeast(floor) {
|
|
23394
23602
|
return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
|
|
23395
23603
|
}
|
|
@@ -23637,7 +23845,7 @@ function isVaultConsentValid(consent) {
|
|
|
23637
23845
|
}
|
|
23638
23846
|
|
|
23639
23847
|
// ../../packages/schema/src/zod/local.ts
|
|
23640
|
-
var WORKSPACE_SETTINGS_SPEC_VERSION =
|
|
23848
|
+
var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
|
|
23641
23849
|
var MODEL_JUDGE_PAYLOAD_VERSION = 1;
|
|
23642
23850
|
var RunMode = external_exports.enum(["standalone", "attached"]);
|
|
23643
23851
|
var ControlPlaneConnection = external_exports.object({
|
|
@@ -23657,6 +23865,15 @@ var HistorySyncConsent = external_exports.object({
|
|
|
23657
23865
|
payloadVersion: external_exports.number().int().positive(),
|
|
23658
23866
|
endpoint: external_exports.string()
|
|
23659
23867
|
});
|
|
23868
|
+
var BODY_RETENTION_DEFAULT_DAYS = 30;
|
|
23869
|
+
var BodyRetention = external_exports.object({
|
|
23870
|
+
enabled: external_exports.boolean().default(false),
|
|
23871
|
+
// Never 0, and the ceiling is a fat-finger guard rather than a policy
|
|
23872
|
+
// limit — `enabled` is the real gate. A low value cannot reach a row the
|
|
23873
|
+
// sync ledger still owes: the sweep's age filter only ever NARROWS a
|
|
23874
|
+
// candidate set that is already bounded by "delivered, or never owed".
|
|
23875
|
+
retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
|
|
23876
|
+
}).meta({ id: "BodyRetention" });
|
|
23660
23877
|
var WorkspaceSettings = external_exports.object({
|
|
23661
23878
|
specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
|
|
23662
23879
|
runMode: RunMode.default("standalone"),
|
|
@@ -23700,12 +23917,18 @@ var WorkspaceSettings = external_exports.object({
|
|
|
23700
23917
|
// covers the current payload and must be re-granted.
|
|
23701
23918
|
modelJudgeConsent: ModelJudgeConsent.optional(),
|
|
23702
23919
|
// 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()
|
|
23920
|
+
// with the payload shape and the endpoint they agreed to. Since payload v3
|
|
23921
|
+
// that covers the pre-attach backlog AND undelivered captures alike, and both
|
|
23922
|
+
// carry prompt/reply/tool-output text in `content`; the key name predates
|
|
23923
|
+
// both widenings. Absent until granted, and a grant for a different endpoint
|
|
23924
|
+
// or an older payload no longer counts.
|
|
23925
|
+
historySyncConsent: HistorySyncConsent.optional(),
|
|
23926
|
+
// Local body expiry (see BodyRetention). Off until switched on; expiring a
|
|
23927
|
+
// body never removes the row or its findings.
|
|
23928
|
+
bodyRetention: BodyRetention.default({
|
|
23929
|
+
enabled: false,
|
|
23930
|
+
retainDays: BODY_RETENTION_DEFAULT_DAYS
|
|
23931
|
+
})
|
|
23709
23932
|
});
|
|
23710
23933
|
function defaultWorkspaceSettings() {
|
|
23711
23934
|
return WorkspaceSettings.parse({});
|
|
@@ -23800,12 +24023,15 @@ function toCaptureAttributes(event) {
|
|
|
23800
24023
|
...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
|
|
23801
24024
|
...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
|
|
23802
24025
|
...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
|
|
24026
|
+
...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
|
|
23803
24027
|
// `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
|
|
23804
24028
|
// has ever populated either), but every legacy metadata key still rides
|
|
23805
24029
|
// the bag rather than being silently dropped — CaptureAttributes'
|
|
23806
24030
|
// `.catchall(z.unknown())` carries the long tail.
|
|
23807
24031
|
...metadata?.model !== void 0 ? { model: metadata.model } : {},
|
|
23808
|
-
...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
|
|
24032
|
+
...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
|
|
24033
|
+
...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
|
|
24034
|
+
...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
|
|
23809
24035
|
};
|
|
23810
24036
|
}
|
|
23811
24037
|
function captureDefinitionVersion(finding) {
|
|
@@ -23833,10 +24059,22 @@ var ManagedSettingKey = external_exports.enum([
|
|
|
23833
24059
|
"vaultInlineReveal",
|
|
23834
24060
|
"modelJudgeConsent",
|
|
23835
24061
|
"dataSharesInPlace",
|
|
23836
|
-
"redactFallback"
|
|
24062
|
+
"redactFallback",
|
|
24063
|
+
// Pins the toggle and the day count together — see BodyRetention on why the
|
|
24064
|
+
// two are one unit. An administrator mandating a window wants the count
|
|
24065
|
+
// enforced with it, not one a user can widen while the toggle stays on.
|
|
24066
|
+
"bodyRetention"
|
|
23837
24067
|
]).meta({ id: "ManagedSettingKey" });
|
|
24068
|
+
function isManagedSettingKey(value) {
|
|
24069
|
+
return ManagedSettingKey.safeParse(value).success;
|
|
24070
|
+
}
|
|
23838
24071
|
var ManagedSettingsValues = external_exports.object({
|
|
23839
24072
|
runMode: external_exports.enum(["standalone", "attached"]).optional(),
|
|
24073
|
+
// `controlPlane` and `bodyRetention` are the two nested values, and both are
|
|
24074
|
+
// plain, non-strict objects: a key under either that this build does not know
|
|
24075
|
+
// is stripped and nothing reports it. The unknown-value split in
|
|
24076
|
+
// ManagedSettings below classifies top-level names only, so it stops at
|
|
24077
|
+
// these boundaries.
|
|
23840
24078
|
controlPlane: external_exports.object({
|
|
23841
24079
|
endpoint: external_exports.string().min(1),
|
|
23842
24080
|
label: external_exports.string().min(1).optional()
|
|
@@ -23847,7 +24085,8 @@ var ManagedSettingsValues = external_exports.object({
|
|
|
23847
24085
|
vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
|
|
23848
24086
|
modelJudgeConsent: external_exports.boolean().optional(),
|
|
23849
24087
|
dataSharesInPlace: external_exports.boolean().optional(),
|
|
23850
|
-
redactFallback: RedactFallback.optional()
|
|
24088
|
+
redactFallback: RedactFallback.optional(),
|
|
24089
|
+
bodyRetention: BodyRetention.optional()
|
|
23851
24090
|
}).meta({ id: "ManagedSettingsValues" });
|
|
23852
24091
|
var ManagedSettings = external_exports.object({
|
|
23853
24092
|
specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
|
|
@@ -23855,11 +24094,59 @@ var ManagedSettings = external_exports.object({
|
|
|
23855
24094
|
// decision from a bug. Absent renders as a generic "your organization".
|
|
23856
24095
|
organization: external_exports.string().min(1).optional(),
|
|
23857
24096
|
// What the administrator pinned.
|
|
23858
|
-
|
|
24097
|
+
//
|
|
24098
|
+
// Parsed as a RECORD rather than as the nested schema, and split below for
|
|
24099
|
+
// the same reason `lockedFields` is parsed as names: a plain `z.object`
|
|
24100
|
+
// drops an unrecognised key and succeeds, so a pin this build does not know
|
|
24101
|
+
// vanished and nothing anywhere said so. A pin with no lock is a supported
|
|
24102
|
+
// shape — it is a DEFAULT the user may still change — so that silence hit
|
|
24103
|
+
// exactly the file an administrator is most likely to write while a fleet
|
|
24104
|
+
// is mid-upgrade.
|
|
24105
|
+
//
|
|
24106
|
+
// Splitting here rather than calling `.strict()`: strict would REFUSE the
|
|
24107
|
+
// file, which is the outcome the lock half already rejected — an older
|
|
24108
|
+
// build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
|
|
24109
|
+
// value still fails, because the nested schema is re-run over the known
|
|
24110
|
+
// subset and its issues are re-raised on this parse.
|
|
24111
|
+
values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
|
|
23859
24112
|
// Which of those the user may not change. A key here with no matching value
|
|
23860
24113
|
// freezes whatever the user last chose; a value with no lock is a DEFAULT
|
|
23861
24114
|
// the user may still override. The two are separable on purpose.
|
|
23862
|
-
|
|
24115
|
+
//
|
|
24116
|
+
// Parsed as NAMES rather than as the enum, and split below: a name this
|
|
24117
|
+
// build does not know is dropped from the locked set and reported, never a
|
|
24118
|
+
// reason to refuse the file. The same shape reaches an older build whenever
|
|
24119
|
+
// an administrator locks a key a newer build added, and refusing it there
|
|
24120
|
+
// ran that build entirely unmanaged — every pin and lock gone — on exactly
|
|
24121
|
+
// the fleets most likely to carry a version skew. A name outside the enum
|
|
24122
|
+
// is still never HONOURED: the lockable set stays explicit above.
|
|
24123
|
+
lockedFields: external_exports.array(external_exports.string()).default([])
|
|
24124
|
+
}).transform(({ lockedFields, values, ...rest }, ctx) => {
|
|
24125
|
+
const known = [];
|
|
24126
|
+
const unknown2 = [];
|
|
24127
|
+
for (const name of lockedFields) {
|
|
24128
|
+
if (isManagedSettingKey(name)) known.push(name);
|
|
24129
|
+
else unknown2.push(name);
|
|
24130
|
+
}
|
|
24131
|
+
const knownValues = /* @__PURE__ */ Object.create(null);
|
|
24132
|
+
const unknownValues = [];
|
|
24133
|
+
for (const [name, value] of Object.entries(values)) {
|
|
24134
|
+
if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
|
|
24135
|
+
else unknownValues.push(name);
|
|
24136
|
+
}
|
|
24137
|
+
const pinned = ManagedSettingsValues.safeParse(knownValues);
|
|
24138
|
+
if (!pinned.success) {
|
|
24139
|
+
for (const issue2 of pinned.error.issues)
|
|
24140
|
+
ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
|
|
24141
|
+
return external_exports.NEVER;
|
|
24142
|
+
}
|
|
24143
|
+
return {
|
|
24144
|
+
...rest,
|
|
24145
|
+
values: pinned.data,
|
|
24146
|
+
lockedFields: known,
|
|
24147
|
+
...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
|
|
24148
|
+
...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
|
|
24149
|
+
};
|
|
23863
24150
|
}).meta({ id: "ManagedSettings" });
|
|
23864
24151
|
|
|
23865
24152
|
// ../../packages/schema/src/zod/project-files.ts
|
|
@@ -23983,7 +24270,11 @@ var FindingsTimeseriesPoint = external_exports.object({
|
|
|
23983
24270
|
timestamp: external_exports.iso.date(),
|
|
23984
24271
|
critical: external_exports.number().int().nonnegative(),
|
|
23985
24272
|
high: external_exports.number().int().nonnegative(),
|
|
23986
|
-
medium: external_exports.number().int().nonnegative()
|
|
24273
|
+
medium: external_exports.number().int().nonnegative(),
|
|
24274
|
+
// Optional and additive, so a producer written against the earlier
|
|
24275
|
+
// three-series contract keeps validating. A consumer plotting it resolves the
|
|
24276
|
+
// absent case itself — the chart point requires a number.
|
|
24277
|
+
low: external_exports.number().int().nonnegative().optional()
|
|
23987
24278
|
}).meta({ id: "FindingsTimeseriesPoint" });
|
|
23988
24279
|
var FindingsTimeseriesResponse = external_exports.object({
|
|
23989
24280
|
range: TimeRange,
|
|
@@ -24009,6 +24300,10 @@ var ResolvedFeedItem = external_exports.object({
|
|
|
24009
24300
|
findingKey: external_exports.string(),
|
|
24010
24301
|
ruleId: external_exports.string(),
|
|
24011
24302
|
severity: Severity,
|
|
24303
|
+
// Repository slug, and the file path RELATIVE to it. The pair is what
|
|
24304
|
+
// identifies the file: a bare path matches the same name in every repo.
|
|
24305
|
+
// Optional and additive; empty when the event carried no repo.
|
|
24306
|
+
repo: external_exports.string().optional(),
|
|
24012
24307
|
path: external_exports.string(),
|
|
24013
24308
|
// ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
|
|
24014
24309
|
// findings domain). The reader `.toISOString()`s the DB epoch-ms values.
|
|
@@ -24114,7 +24409,23 @@ var SaveSettingsInput = external_exports.object({
|
|
|
24114
24409
|
modelJudgeConsent: ModelJudgeConsentChoice,
|
|
24115
24410
|
historySyncConsent: HistorySyncConsentChoice,
|
|
24116
24411
|
vaultConsent: external_exports.string(),
|
|
24117
|
-
vaultInlineReveal: external_exports.string()
|
|
24412
|
+
vaultInlineReveal: external_exports.string(),
|
|
24413
|
+
// Widened to `string` like its neighbours rather than typed as
|
|
24414
|
+
// `RedactFallback`, on this module's own layering rule: shape here, VALUE at
|
|
24415
|
+
// the call site, so the domain check receives the type it was written for.
|
|
24416
|
+
//
|
|
24417
|
+
// NOT because a narrower schema would reject differently. `parseActionInput`
|
|
24418
|
+
// is a `safeParse` wrapper and throws for no field schema, so either spelling
|
|
24419
|
+
// reaches a recoverable `{ ok: false }` and there is no rejected promise to
|
|
24420
|
+
// trade against. The real cost runs the other way and is the part worth
|
|
24421
|
+
// knowing: a value this schema admits and the domain enum then rejects lands
|
|
24422
|
+
// on the action's shared refusal, which names NO field, where a shape
|
|
24423
|
+
// rejection reaches `malformedInput` and names the schema key.
|
|
24424
|
+
redactFallback: external_exports.string(),
|
|
24425
|
+
// Shape only, the way the enum fields above are strings only: the RANGE is
|
|
24426
|
+
// `BodyRetention`'s and the action checks it there, so there is one place
|
|
24427
|
+
// that decides what a legal horizon is rather than two that can drift.
|
|
24428
|
+
bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
|
|
24118
24429
|
});
|
|
24119
24430
|
var AttachInput = external_exports.object({
|
|
24120
24431
|
endpoint: external_exports.string(),
|
|
@@ -24286,6 +24597,52 @@ function reviewSeverityRank(reasons) {
|
|
|
24286
24597
|
return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
|
|
24287
24598
|
}
|
|
24288
24599
|
|
|
24600
|
+
// ../../packages/schema/src/zod/web-capture.ts
|
|
24601
|
+
var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
|
|
24602
|
+
var WebUsage = external_exports.object({
|
|
24603
|
+
inputTokens: external_exports.number().int().nonnegative().optional(),
|
|
24604
|
+
outputTokens: external_exports.number().int().nonnegative().optional(),
|
|
24605
|
+
cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
|
|
24606
|
+
cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
|
|
24607
|
+
});
|
|
24608
|
+
var WebToolCall = external_exports.object({
|
|
24609
|
+
toolUseId: external_exports.string().min(1),
|
|
24610
|
+
toolName: external_exports.string().min(1),
|
|
24611
|
+
target: external_exports.string().optional(),
|
|
24612
|
+
isError: external_exports.boolean().optional(),
|
|
24613
|
+
inputSize: external_exports.number().int().nonnegative().optional(),
|
|
24614
|
+
outputSize: external_exports.number().int().nonnegative().optional()
|
|
24615
|
+
});
|
|
24616
|
+
var WebExchange = external_exports.object({
|
|
24617
|
+
messageId: external_exports.string().min(1),
|
|
24618
|
+
startedAt: external_exports.iso.datetime(),
|
|
24619
|
+
model: external_exports.string().optional(),
|
|
24620
|
+
usage: WebUsage.optional(),
|
|
24621
|
+
usageSource: WebUsageSource,
|
|
24622
|
+
stopReason: external_exports.string().optional(),
|
|
24623
|
+
conversationId: external_exports.string().optional(),
|
|
24624
|
+
turnIndex: external_exports.number().int().nonnegative().optional(),
|
|
24625
|
+
toolCalls: external_exports.array(WebToolCall).default([]),
|
|
24626
|
+
// Absent when the adapter recovered no text. Capped by the caller at
|
|
24627
|
+
// RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
|
|
24628
|
+
// short capture is never mistaken for a short reply.
|
|
24629
|
+
responseText: external_exports.string().optional(),
|
|
24630
|
+
truncated: external_exports.boolean().default(false)
|
|
24631
|
+
});
|
|
24632
|
+
var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
|
|
24633
|
+
var WebCaptureStatus = external_exports.object({
|
|
24634
|
+
patched: external_exports.boolean(),
|
|
24635
|
+
live: external_exports.boolean(),
|
|
24636
|
+
blind: external_exports.boolean(),
|
|
24637
|
+
sendsSeenDom: external_exports.number().int().nonnegative(),
|
|
24638
|
+
exchangesSeenNet: external_exports.number().int().nonnegative(),
|
|
24639
|
+
parseFailures: external_exports.number().int().nonnegative(),
|
|
24640
|
+
unparsedBodies: external_exports.number().int().nonnegative(),
|
|
24641
|
+
// The adapter-declared JSON key paths that were absent from a real payload —
|
|
24642
|
+
// the earliest signal that a site's contract moved.
|
|
24643
|
+
shapeMisses: external_exports.array(external_exports.string()).default([])
|
|
24644
|
+
});
|
|
24645
|
+
|
|
24289
24646
|
// ../../packages/persistence/src/paths.ts
|
|
24290
24647
|
import {
|
|
24291
24648
|
chmodSync,
|
|
@@ -24646,6 +25003,22 @@ function discardStore(file2, backup) {
|
|
|
24646
25003
|
}
|
|
24647
25004
|
}
|
|
24648
25005
|
|
|
25006
|
+
// ../../packages/persistence/src/internal/sql-functions.ts
|
|
25007
|
+
var utf8 = new TextDecoder();
|
|
25008
|
+
function akaLower(value) {
|
|
25009
|
+
if (value === null) return null;
|
|
25010
|
+
if (typeof value === "string") return value.toLowerCase();
|
|
25011
|
+
if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
|
|
25012
|
+
return utf8.decode(value).toLowerCase();
|
|
25013
|
+
}
|
|
25014
|
+
function registerSqlFunctions(db) {
|
|
25015
|
+
db.function(
|
|
25016
|
+
"aka_lower",
|
|
25017
|
+
{ deterministic: true, directOnly: true, useBigIntArguments: true },
|
|
25018
|
+
akaLower
|
|
25019
|
+
);
|
|
25020
|
+
}
|
|
25021
|
+
|
|
24649
25022
|
// ../../packages/persistence/src/internal/sql-text.ts
|
|
24650
25023
|
function escapeLikePattern(s) {
|
|
24651
25024
|
return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
|
|
@@ -24730,6 +25103,11 @@ function schemaObjectExists(db, kind, name) {
|
|
|
24730
25103
|
function indexExists(db, name) {
|
|
24731
25104
|
return schemaObjectExists(db, "index", name);
|
|
24732
25105
|
}
|
|
25106
|
+
function indexColumns(db, name) {
|
|
25107
|
+
if (!indexExists(db, name)) return [];
|
|
25108
|
+
const columns = db.prepare(`PRAGMA index_info(${name})`).all();
|
|
25109
|
+
return columns.map((c) => c.name).filter((c) => c !== null);
|
|
25110
|
+
}
|
|
24733
25111
|
function columnNames(db, table, opts) {
|
|
24734
25112
|
const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
|
|
24735
25113
|
const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
|
|
@@ -24791,140 +25169,782 @@ function mapRowsTolerant(rows, map2) {
|
|
|
24791
25169
|
return out;
|
|
24792
25170
|
}
|
|
24793
25171
|
|
|
24794
|
-
// ../../packages/persistence/src/
|
|
24795
|
-
|
|
24796
|
-
|
|
24797
|
-
|
|
24798
|
-
|
|
24799
|
-
|
|
24800
|
-
|
|
24801
|
-
|
|
24802
|
-
|
|
24803
|
-
return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
|
|
25172
|
+
// ../../packages/persistence/src/internal/outbox-lane.ts
|
|
25173
|
+
var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
|
|
25174
|
+
var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
25175
|
+
|
|
25176
|
+
// ../../packages/persistence/src/sync-failure.ts
|
|
25177
|
+
var SYNC_FAILURE_REASONS = SyncFailureReason.options;
|
|
25178
|
+
function syncFailureRejectCondition(column = "sync_failure") {
|
|
25179
|
+
const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
|
|
25180
|
+
return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
|
|
24804
25181
|
}
|
|
24805
|
-
|
|
24806
|
-
|
|
24807
|
-
|
|
24808
|
-
|
|
24809
|
-
|
|
24810
|
-
|
|
24811
|
-
|
|
24812
|
-
|
|
24813
|
-
|
|
24814
|
-
|
|
24815
|
-
|
|
24816
|
-
|
|
24817
|
-
|
|
24818
|
-
|
|
24819
|
-
|
|
24820
|
-
|
|
24821
|
-
|
|
24822
|
-
|
|
24823
|
-
|
|
24824
|
-
|
|
24825
|
-
|
|
24826
|
-
|
|
24827
|
-
|
|
24828
|
-
|
|
24829
|
-
|
|
24830
|
-
|
|
24831
|
-
|
|
24832
|
-
|
|
24833
|
-
|
|
24834
|
-
|
|
24835
|
-
|
|
24836
|
-
|
|
24837
|
-
|
|
24838
|
-
|
|
24839
|
-
|
|
24840
|
-
|
|
24841
|
-
|
|
24842
|
-
|
|
24843
|
-
|
|
24844
|
-
|
|
24845
|
-
|
|
24846
|
-
|
|
24847
|
-
|
|
24848
|
-
|
|
24849
|
-
|
|
24850
|
-
|
|
24851
|
-
|
|
24852
|
-
|
|
24853
|
-
|
|
24854
|
-
|
|
24855
|
-
|
|
24856
|
-
|
|
24857
|
-
)
|
|
24858
|
-
|
|
24859
|
-
|
|
24860
|
-
|
|
25182
|
+
|
|
25183
|
+
// ../../packages/persistence/src/repositories/history-sync.ts
|
|
25184
|
+
var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
|
|
25185
|
+
var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
25186
|
+
var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
|
|
25187
|
+
var COUNTED_EVENT_TYPES = [
|
|
25188
|
+
...STRUCTURAL_EVENT_TYPES,
|
|
25189
|
+
...OUTBOX_CAPTURE_EVENT_TYPES
|
|
25190
|
+
];
|
|
25191
|
+
var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
25192
|
+
var PARTITION_BUCKETS = `
|
|
25193
|
+
SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
|
|
25194
|
+
SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
|
|
25195
|
+
SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
|
|
25196
|
+
SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
|
|
25197
|
+
AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
|
|
25198
|
+
SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
|
|
25199
|
+
AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
|
|
25200
|
+
-- Spelled as what it INCLUDES rather than what it excludes, so a reason
|
|
25201
|
+
-- added later lands in no bucket and fails the sum assertion, instead
|
|
25202
|
+
-- of silently joining this one.
|
|
25203
|
+
SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
|
|
25204
|
+
AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
|
|
25205
|
+
THEN 1 ELSE 0 END) AS failed,
|
|
25206
|
+
COUNT(*) AS total`;
|
|
25207
|
+
var COUNTED_SCOPE = `
|
|
25208
|
+
WHERE event_type IN (${COUNTED_TYPE_LIST})
|
|
25209
|
+
AND (
|
|
25210
|
+
event_type IN (${TYPE_LIST})
|
|
25211
|
+
OR synced_at IS NOT NULL
|
|
25212
|
+
OR outbox_owed = 1
|
|
25213
|
+
)`;
|
|
25214
|
+
var SKIPPED = -1;
|
|
25215
|
+
var ROW_COLUMNS = `id,
|
|
25216
|
+
parent_id AS parentId,
|
|
25217
|
+
root_session_id AS rootSessionId,
|
|
25218
|
+
event_type AS eventType,
|
|
25219
|
+
host_id AS hostId,
|
|
25220
|
+
harness_id AS harnessId,
|
|
25221
|
+
source_project_id AS sourceProjectId,
|
|
25222
|
+
started_at AS startedAt,
|
|
25223
|
+
ended_at AS endedAt,
|
|
25224
|
+
severity,
|
|
25225
|
+
priority,
|
|
25226
|
+
content,
|
|
25227
|
+
content_hash AS contentHash,
|
|
25228
|
+
attributes`;
|
|
25229
|
+
var SqliteHistorySyncRepository = class {
|
|
25230
|
+
constructor(db) {
|
|
25231
|
+
this.db = db;
|
|
25232
|
+
this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
|
|
25233
|
+
this.sessionsStmt = db.prepare(
|
|
25234
|
+
`SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
|
|
25235
|
+
FROM audit_events
|
|
25236
|
+
WHERE synced_at IS NULL
|
|
25237
|
+
AND event_type IN (${TYPE_LIST})
|
|
25238
|
+
AND started_at < :before
|
|
25239
|
+
GROUP BY sessionId
|
|
25240
|
+
ORDER BY earliest
|
|
25241
|
+
LIMIT :limit`
|
|
25242
|
+
);
|
|
25243
|
+
this.rowsStmt = db.prepare(
|
|
25244
|
+
`SELECT ${ROW_COLUMNS}
|
|
25245
|
+
FROM audit_events
|
|
25246
|
+
WHERE synced_at IS NULL
|
|
25247
|
+
AND event_type IN (${TYPE_LIST})
|
|
25248
|
+
AND started_at < :before
|
|
25249
|
+
AND COALESCE(root_session_id, id) = :sessionId
|
|
25250
|
+
ORDER BY (event_type = 'session') DESC, started_at
|
|
25251
|
+
LIMIT :limit`
|
|
25252
|
+
);
|
|
25253
|
+
this.captureRowsStmt = db.prepare(
|
|
25254
|
+
`SELECT ${ROW_COLUMNS}
|
|
25255
|
+
FROM audit_events
|
|
25256
|
+
WHERE synced_at IS NULL
|
|
25257
|
+
AND sync_claimed_at IS NULL
|
|
25258
|
+
AND outbox_owed = 1
|
|
25259
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})
|
|
25260
|
+
AND started_at < :before
|
|
25261
|
+
ORDER BY started_at
|
|
25262
|
+
LIMIT :limit`
|
|
25263
|
+
);
|
|
25264
|
+
this.markOwedStmt = db.prepare(
|
|
25265
|
+
`UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
|
|
25266
|
+
);
|
|
25267
|
+
this.markCaptureBacklogOwedStmt = db.prepare(
|
|
25268
|
+
`UPDATE audit_events SET outbox_owed = 1
|
|
25269
|
+
WHERE synced_at IS NULL
|
|
25270
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})
|
|
25271
|
+
AND started_at < :before`
|
|
25272
|
+
);
|
|
25273
|
+
this.stampStmt = db.prepare(
|
|
25274
|
+
`UPDATE audit_events
|
|
25275
|
+
SET synced_at = :at,
|
|
25276
|
+
sync_claimed_at = NULL,
|
|
25277
|
+
sync_failed_at = :failedAt,
|
|
25278
|
+
sync_failure = :failure
|
|
25279
|
+
WHERE id = :id`
|
|
25280
|
+
);
|
|
25281
|
+
this.claimRowStmt = db.prepare(
|
|
25282
|
+
`UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
|
|
25283
|
+
);
|
|
25284
|
+
this.releaseRowStmt = db.prepare(
|
|
25285
|
+
`UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
|
|
25286
|
+
);
|
|
25287
|
+
this.releaseStaleClaimsStmt = db.prepare(
|
|
25288
|
+
`UPDATE audit_events SET sync_claimed_at = NULL
|
|
25289
|
+
WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
|
|
25290
|
+
);
|
|
25291
|
+
this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
|
|
25292
|
+
FROM audit_events${COUNTED_SCOPE}`);
|
|
25293
|
+
this.partitionByKindStmt = db.prepare(
|
|
25294
|
+
`SELECT event_type AS kind,${PARTITION_BUCKETS}
|
|
25295
|
+
FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
|
|
25296
|
+
GROUP BY event_type`
|
|
25297
|
+
);
|
|
25298
|
+
this.countsStmt = db.prepare(
|
|
25299
|
+
`SELECT
|
|
25300
|
+
SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
|
|
25301
|
+
SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
|
|
25302
|
+
SUM(CASE WHEN synced_at = ${String(SKIPPED)}
|
|
25303
|
+
AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
|
|
25304
|
+
THEN 1 ELSE 0 END) AS skipped,
|
|
25305
|
+
SUM(CASE WHEN synced_at = ${String(SKIPPED)}
|
|
25306
|
+
AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
|
|
25307
|
+
SUM(CASE WHEN synced_at = ${String(SKIPPED)}
|
|
25308
|
+
AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
|
|
25309
|
+
FROM audit_events
|
|
25310
|
+
WHERE event_type IN (${TYPE_LIST})`
|
|
25311
|
+
);
|
|
25312
|
+
this.captureSkipCountStmt = db.prepare(
|
|
25313
|
+
// EVERY sentinel capture, whatever the reason — deliberately NOT split the
|
|
25314
|
+
// way the structural totals are. The split exists because a refusal is
|
|
25315
|
+
// terminal only against the deployment that gave it, and the structural
|
|
25316
|
+
// re-arm frees it on a change of deployment. The capture lane has no such
|
|
25317
|
+
// escape: re-arming a capture would offer one deployment's undelivered
|
|
25318
|
+
// prompts, with their text, to a deployment that never saw them, which is
|
|
25319
|
+
// exactly what disownCapturesStmt exists to prevent. So on this lane both
|
|
25320
|
+
// reasons mean the same thing — this row will not be sent — and splitting
|
|
25321
|
+
// them would put refused captures in a bucket nothing reads and nothing
|
|
25322
|
+
// frees.
|
|
25323
|
+
`SELECT COUNT(*) AS skipped
|
|
25324
|
+
FROM audit_events
|
|
25325
|
+
WHERE synced_at = ${String(SKIPPED)}
|
|
25326
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})`
|
|
25327
|
+
);
|
|
25328
|
+
this.fingerprintStmt = db.prepare(
|
|
25329
|
+
`SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
|
|
25330
|
+
FROM history_sync WHERE id = 1`
|
|
25331
|
+
);
|
|
25332
|
+
this.setFingerprintStmt = db.prepare(
|
|
25333
|
+
`UPDATE history_sync
|
|
25334
|
+
SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
|
|
25335
|
+
WHERE id = 1`
|
|
25336
|
+
);
|
|
25337
|
+
this.disownCapturesStmt = db.prepare(
|
|
25338
|
+
`UPDATE audit_events SET outbox_owed = NULL
|
|
25339
|
+
WHERE outbox_owed IS NOT NULL
|
|
25340
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})
|
|
25341
|
+
AND started_at < :attachedAt`
|
|
25342
|
+
);
|
|
25343
|
+
this.rearmStmt = db.prepare(
|
|
25344
|
+
`UPDATE audit_events
|
|
25345
|
+
SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
|
|
25346
|
+
WHERE (synced_at > 0
|
|
25347
|
+
OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
|
|
25348
|
+
AND event_type IN (${TYPE_LIST})`
|
|
25349
|
+
);
|
|
25350
|
+
this.claimStmt = db.prepare(
|
|
25351
|
+
`UPDATE history_sync
|
|
25352
|
+
SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
|
|
25353
|
+
WHERE id = 1
|
|
25354
|
+
AND (owner_pid IS NULL
|
|
25355
|
+
OR heartbeat_at IS NULL
|
|
25356
|
+
OR heartbeat_at < :staleBefore
|
|
25357
|
+
OR heartbeat_at > :now)`
|
|
25358
|
+
);
|
|
25359
|
+
this.heartbeatStmt = db.prepare(
|
|
25360
|
+
`UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
|
|
25361
|
+
);
|
|
25362
|
+
this.releaseStmt = db.prepare(
|
|
25363
|
+
`UPDATE history_sync
|
|
25364
|
+
SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
|
|
25365
|
+
WHERE id = 1 AND owner_pid = :pid`
|
|
25366
|
+
);
|
|
25367
|
+
this.closeWindowStmt = db.prepare(
|
|
25368
|
+
`UPDATE audit_events
|
|
25369
|
+
SET synced_at = ${String(SKIPPED)},
|
|
25370
|
+
sync_failed_at = :at,
|
|
25371
|
+
sync_failure = 'detached_undelivered'
|
|
25372
|
+
WHERE synced_at IS NULL
|
|
25373
|
+
AND event_type IN (${TYPE_LIST})
|
|
25374
|
+
AND started_at >= :attachedAt`
|
|
25375
|
+
);
|
|
25376
|
+
this.releaseBoundaryStmt = db.prepare(
|
|
25377
|
+
`UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
|
|
25378
|
+
);
|
|
25379
|
+
this.freezeBoundaryStmt = db.prepare(
|
|
25380
|
+
`UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
|
|
25381
|
+
);
|
|
25382
|
+
this.leaseStmt = db.prepare(
|
|
25383
|
+
`SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
|
|
25384
|
+
acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
|
|
25385
|
+
FROM history_sync WHERE id = 1`
|
|
25386
|
+
);
|
|
25387
|
+
this.inspectionsStmt = db.prepare(
|
|
25388
|
+
`SELECT d.rule_id AS ruleId,
|
|
25389
|
+
d.name AS ruleName,
|
|
25390
|
+
d.version AS ruleVersion,
|
|
25391
|
+
d.category AS category,
|
|
25392
|
+
d.severity AS severity,
|
|
25393
|
+
f.span_start AS spanStart,
|
|
25394
|
+
f.span_end AS spanEnd,
|
|
25395
|
+
f.masked_match AS maskedMatch,
|
|
25396
|
+
f.action_taken AS actionTaken,
|
|
25397
|
+
f.confidence AS confidence
|
|
25398
|
+
FROM inspection_findings f
|
|
25399
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
25400
|
+
WHERE f.audit_event_id = :auditEventId
|
|
25401
|
+
ORDER BY f.span_start, f.id`
|
|
25402
|
+
);
|
|
24861
25403
|
}
|
|
24862
|
-
|
|
24863
|
-
|
|
25404
|
+
db;
|
|
25405
|
+
ensureRowStmt;
|
|
25406
|
+
sessionsStmt;
|
|
25407
|
+
rowsStmt;
|
|
25408
|
+
stampStmt;
|
|
25409
|
+
countsStmt;
|
|
25410
|
+
fingerprintStmt;
|
|
25411
|
+
setFingerprintStmt;
|
|
25412
|
+
rearmStmt;
|
|
25413
|
+
claimStmt;
|
|
25414
|
+
heartbeatStmt;
|
|
25415
|
+
releaseStmt;
|
|
25416
|
+
leaseStmt;
|
|
25417
|
+
inspectionsStmt;
|
|
25418
|
+
closeWindowStmt;
|
|
25419
|
+
releaseBoundaryStmt;
|
|
25420
|
+
freezeBoundaryStmt;
|
|
25421
|
+
captureRowsStmt;
|
|
25422
|
+
markOwedStmt;
|
|
25423
|
+
markCaptureBacklogOwedStmt;
|
|
25424
|
+
captureSkipCountStmt;
|
|
25425
|
+
disownCapturesStmt;
|
|
25426
|
+
partitionStmt;
|
|
25427
|
+
partitionByKindStmt;
|
|
25428
|
+
claimRowStmt;
|
|
25429
|
+
releaseRowStmt;
|
|
25430
|
+
releaseStaleClaimsStmt;
|
|
25431
|
+
/**
|
|
25432
|
+
* The masked detections recorded against one tool call.
|
|
25433
|
+
*
|
|
25434
|
+
* These travel with the event because a tool call's target is not
|
|
25435
|
+
* re-inspectable from the event alone — unlike a capture, where the text
|
|
25436
|
+
* itself is re-scannable. What crosses is the masked match and the rule that
|
|
25437
|
+
* produced it, never the value.
|
|
25438
|
+
*/
|
|
25439
|
+
inspectionsFor(auditEventId) {
|
|
25440
|
+
return allRows(this.inspectionsStmt, { auditEventId });
|
|
24864
25441
|
}
|
|
24865
|
-
|
|
24866
|
-
|
|
24867
|
-
|
|
24868
|
-
|
|
24869
|
-
|
|
24870
|
-
|
|
24871
|
-
|
|
24872
|
-
|
|
24873
|
-
|
|
24874
|
-
|
|
24875
|
-
|
|
25442
|
+
/**
|
|
25443
|
+
* Sessions with structural rows still to send, oldest first.
|
|
25444
|
+
*
|
|
25445
|
+
* BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
|
|
25446
|
+
* read. Anything recorded after the machine attached is the live forward
|
|
25447
|
+
* path's to deliver; this drain exists for what was recorded before it, and a
|
|
25448
|
+
* row both paths send is at best a duplicate request and at worst — for a
|
|
25449
|
+
* session root — an overwrite of the inventory ids the live path resolved.
|
|
25450
|
+
*/
|
|
25451
|
+
pendingSessions(limit, before) {
|
|
25452
|
+
return allRows(this.sessionsStmt, { limit, before }).map(
|
|
25453
|
+
(r) => r.sessionId
|
|
25454
|
+
);
|
|
24876
25455
|
}
|
|
24877
|
-
|
|
24878
|
-
|
|
24879
|
-
|
|
24880
|
-
const marks = [];
|
|
24881
|
-
for (const table of ["events", "findings"]) {
|
|
24882
|
-
try {
|
|
24883
|
-
const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
|
|
24884
|
-
if (row === void 0) {
|
|
24885
|
-
holdsRows = true;
|
|
24886
|
-
marks.push(`${table}:unreadable`);
|
|
24887
|
-
continue;
|
|
24888
|
-
}
|
|
24889
|
-
if (row.n > 0) holdsRows = true;
|
|
24890
|
-
marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
|
|
24891
|
-
} catch {
|
|
24892
|
-
holdsRows = true;
|
|
24893
|
-
marks.push(`${table}:unreadable`);
|
|
24894
|
-
}
|
|
25456
|
+
/** One session's undelivered structural rows within the backlog, root first. */
|
|
25457
|
+
pendingRows(sessionId, limit, before) {
|
|
25458
|
+
return allRows(this.rowsStmt, { sessionId, limit, before });
|
|
24895
25459
|
}
|
|
24896
|
-
|
|
24897
|
-
|
|
24898
|
-
|
|
24899
|
-
|
|
24900
|
-
|
|
24901
|
-
|
|
24902
|
-
|
|
24903
|
-
|
|
24904
|
-
|
|
24905
|
-
|
|
24906
|
-
akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
|
|
24907
|
-
return;
|
|
24908
|
-
}
|
|
25460
|
+
/**
|
|
25461
|
+
* Captures this machine still owes the deployment, oldest first.
|
|
25462
|
+
*
|
|
25463
|
+
* Selected by the `outbox_owed` marker the attached forward path writes, not
|
|
25464
|
+
* by a time window — see captureRowsStmt for why a window could not express
|
|
25465
|
+
* this. `before` is the grace window that leaves a just-recorded capture to
|
|
25466
|
+
* the live path.
|
|
25467
|
+
*/
|
|
25468
|
+
pendingCaptureRows(limit, before) {
|
|
25469
|
+
return allRows(this.captureRowsStmt, { limit, before });
|
|
24909
25470
|
}
|
|
24910
|
-
|
|
25471
|
+
/**
|
|
25472
|
+
* Record that a capture is OWED to the deployment.
|
|
25473
|
+
*
|
|
25474
|
+
* Written by the attached forward path when a live send did not confirm
|
|
25475
|
+
* delivery, and read by the drain as the whole of its eligibility test. It is
|
|
25476
|
+
* a fact rather than an inference: the machine was attached, the send did not
|
|
25477
|
+
* land, so the row is owed — which no time window can state, because the same
|
|
25478
|
+
* window that holds the rows a past attachment left owed also holds every
|
|
25479
|
+
* capture recorded while the machine was DETACHED, and those were never
|
|
25480
|
+
* offered to anyone.
|
|
25481
|
+
*
|
|
25482
|
+
* Idempotent, and never un-set: `markSynced` settling the row is what takes it
|
|
25483
|
+
* out of the drain's read.
|
|
25484
|
+
*/
|
|
25485
|
+
markCaptureOwed(id) {
|
|
25486
|
+
this.markOwedStmt.run({ id });
|
|
25487
|
+
}
|
|
25488
|
+
/**
|
|
25489
|
+
* Mark every capture already on disk as owed, as of `before`.
|
|
25490
|
+
*
|
|
25491
|
+
* The consent-time backfill, called once from `aka attach` when a human
|
|
25492
|
+
* grants existing-history consent — never from an ongoing drain pass, and
|
|
25493
|
+
* never inferred from a boundary that could later move. `before` is the
|
|
25494
|
+
* caller's own "now" at the moment consent was granted, so what this marks
|
|
25495
|
+
* is exactly the backlog the consent prompt already counted, not whatever a
|
|
25496
|
+
* later re-attach or key rotation might widen it to.
|
|
25497
|
+
*
|
|
25498
|
+
* Returns how many rows matched, for the caller to log or test against. Not a
|
|
25499
|
+
* count of NEWLY marked rows — a row still unsynced from an earlier call
|
|
25500
|
+
* matches again and is counted again, the same as `UPDATE`'s own `changes`.
|
|
25501
|
+
*/
|
|
25502
|
+
markCaptureBacklogOwed(before) {
|
|
25503
|
+
return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
|
|
25504
|
+
}
|
|
25505
|
+
/**
|
|
25506
|
+
* Record delivery. Called only AFTER the far side has accepted the rows.
|
|
25507
|
+
*
|
|
25508
|
+
* CLEARS any failure reason in the same statement. A row that failed against
|
|
25509
|
+
* one deployment and then landed is delivered, and leaving the reason behind
|
|
25510
|
+
* would leave the store holding two contradictory answers about one row —
|
|
25511
|
+
* with the surface free to render either.
|
|
25512
|
+
*/
|
|
25513
|
+
markSynced(ids, atMs) {
|
|
25514
|
+
this.stampAll(ids, atMs, null);
|
|
25515
|
+
}
|
|
25516
|
+
/**
|
|
25517
|
+
* Record that THIS MACHINE cannot express the row on the wire.
|
|
25518
|
+
*
|
|
25519
|
+
* Reserved for a local defect — a row that cannot be rebuilt into a valid
|
|
25520
|
+
* payload, or a body the client itself refused to send. It fails identically
|
|
25521
|
+
* against every deployment, so it is terminal everywhere and the re-arm leaves
|
|
25522
|
+
* it alone. A row that merely failed to REACH the deployment stays NULL, so it
|
|
25523
|
+
* is retried; marking those would turn one outage into permanent data loss.
|
|
25524
|
+
*/
|
|
25525
|
+
markSkipped(ids, atMs) {
|
|
25526
|
+
this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
|
|
25527
|
+
}
|
|
25528
|
+
/**
|
|
25529
|
+
* Record that THIS DEPLOYMENT refused the row.
|
|
25530
|
+
*
|
|
25531
|
+
* The same sentinel as `markSkipped`, and deliberately so: both stop the row
|
|
25532
|
+
* being re-offered on this lane, and `synced_at` goes on answering whether a
|
|
25533
|
+
* row is outstanding rather than why. What separates them is the reason, and
|
|
25534
|
+
* what the reason buys is the re-arm — a refusal is one deployment's verdict
|
|
25535
|
+
* on one body, so it is terminal only for as long as this machine points at
|
|
25536
|
+
* that deployment, and `rearmFor` clears it when the deployment changes.
|
|
25537
|
+
*
|
|
25538
|
+
* Leaving such a row NULL instead would be worse than the loss it replaces:
|
|
25539
|
+
* these reads carry no cursor, so an unstamped row the deployment refuses is
|
|
25540
|
+
* the head of every subsequent page, and the lane stalls behind it for ever.
|
|
25541
|
+
*/
|
|
25542
|
+
markRefused(ids, atMs) {
|
|
25543
|
+
this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
|
|
25544
|
+
}
|
|
25545
|
+
eachInTransaction(ids, run) {
|
|
25546
|
+
if (ids.length === 0) return;
|
|
24911
25547
|
withTransaction(
|
|
24912
|
-
db,
|
|
25548
|
+
this.db,
|
|
24913
25549
|
() => {
|
|
24914
|
-
|
|
24915
|
-
|
|
24916
|
-
|
|
24917
|
-
|
|
24918
|
-
|
|
24919
|
-
|
|
24920
|
-
|
|
24921
|
-
|
|
24922
|
-
|
|
24923
|
-
|
|
24924
|
-
|
|
24925
|
-
|
|
24926
|
-
|
|
24927
|
-
|
|
25550
|
+
for (const id of ids) run(id);
|
|
25551
|
+
},
|
|
25552
|
+
"IMMEDIATE"
|
|
25553
|
+
);
|
|
25554
|
+
}
|
|
25555
|
+
stampAll(ids, value, failure, failedAtMs) {
|
|
25556
|
+
if (ids.length === 0) return;
|
|
25557
|
+
const failedAt = failure === null ? null : failedAtMs ?? null;
|
|
25558
|
+
withTransaction(
|
|
25559
|
+
this.db,
|
|
25560
|
+
() => {
|
|
25561
|
+
for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
|
|
25562
|
+
},
|
|
25563
|
+
"IMMEDIATE"
|
|
25564
|
+
);
|
|
25565
|
+
}
|
|
25566
|
+
/**
|
|
25567
|
+
* Claim rows as in-flight.
|
|
25568
|
+
*
|
|
25569
|
+
* Advisory in exactly the sense the lease is: it records that a send is in
|
|
25570
|
+
* progress so a surface can say so, and a lost claim costs a row showing as
|
|
25571
|
+
* queued while it is actually being sent. It is not exclusion — the far side
|
|
25572
|
+
* settles a duplicate on the row id.
|
|
25573
|
+
*/
|
|
25574
|
+
claimRows(ids, atMs) {
|
|
25575
|
+
this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
|
|
25576
|
+
}
|
|
25577
|
+
/** Give back a claim without settling — the send failed, the row is queued again. */
|
|
25578
|
+
releaseRows(ids) {
|
|
25579
|
+
this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
|
|
25580
|
+
}
|
|
25581
|
+
/**
|
|
25582
|
+
* Clear claims older than `staleBefore`, and report how many were cleared.
|
|
25583
|
+
*
|
|
25584
|
+
* A process killed between claiming and settling leaves rows claimed with
|
|
25585
|
+
* nothing left to settle them. Without this they read as "sending" for ever.
|
|
25586
|
+
*/
|
|
25587
|
+
releaseStaleClaims(staleBefore) {
|
|
25588
|
+
return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
|
|
25589
|
+
}
|
|
25590
|
+
/**
|
|
25591
|
+
* Every tracked row in exactly one delivery state.
|
|
25592
|
+
*
|
|
25593
|
+
* Takes no boundary on purpose. The boundary answers "what should the drain
|
|
25594
|
+
* pick up now", which is a different question from "what state is this row
|
|
25595
|
+
* in" — and a machine that has never attached has no boundary to pass, so
|
|
25596
|
+
* requiring one would force a caller to invent one and report the whole store
|
|
25597
|
+
* as queued.
|
|
25598
|
+
*/
|
|
25599
|
+
/**
|
|
25600
|
+
* The same partition, one row per kind that a lane carries.
|
|
25601
|
+
*
|
|
25602
|
+
* A kind with nothing to report is ABSENT rather than a row of zeros: the
|
|
25603
|
+
* scope decides which rows exist at all, so a kind that has never been
|
|
25604
|
+
* recorded — or whose captures nobody ever owed — produces no group. A caller
|
|
25605
|
+
* rendering a fixed list of kinds must therefore treat a missing one as "no
|
|
25606
|
+
* rows", never as "zero sent"; the two look identical in a bar and mean
|
|
25607
|
+
* different things.
|
|
25608
|
+
*/
|
|
25609
|
+
partitionByKind() {
|
|
25610
|
+
return allRows(
|
|
25611
|
+
this.partitionByKindStmt,
|
|
25612
|
+
{}
|
|
25613
|
+
).map((row) => ({
|
|
25614
|
+
kind: row.kind,
|
|
25615
|
+
queued: row.queued ?? 0,
|
|
25616
|
+
inProgress: row.inProgress ?? 0,
|
|
25617
|
+
synced: row.synced ?? 0,
|
|
25618
|
+
failed: row.failed ?? 0,
|
|
25619
|
+
refused: row.refused ?? 0,
|
|
25620
|
+
detached: row.detached ?? 0,
|
|
25621
|
+
total: row.total ?? 0
|
|
25622
|
+
}));
|
|
25623
|
+
}
|
|
25624
|
+
partition() {
|
|
25625
|
+
const row = getRow(this.partitionStmt, {});
|
|
25626
|
+
return {
|
|
25627
|
+
queued: row?.queued ?? 0,
|
|
25628
|
+
inProgress: row?.inProgress ?? 0,
|
|
25629
|
+
synced: row?.synced ?? 0,
|
|
25630
|
+
failed: row?.failed ?? 0,
|
|
25631
|
+
refused: row?.refused ?? 0,
|
|
25632
|
+
detached: row?.detached ?? 0,
|
|
25633
|
+
total: row?.total ?? 0
|
|
25634
|
+
};
|
|
25635
|
+
}
|
|
25636
|
+
/** `pending` counts only what is inside the backlog; sent and skipped are totals. */
|
|
25637
|
+
counts(before) {
|
|
25638
|
+
const row = getRow(this.countsStmt, { before });
|
|
25639
|
+
const captures = getRow(this.captureSkipCountStmt);
|
|
25640
|
+
return {
|
|
25641
|
+
pending: row?.pending ?? 0,
|
|
25642
|
+
sent: row?.sent ?? 0,
|
|
25643
|
+
skipped: row?.skipped ?? 0,
|
|
25644
|
+
refused: row?.refused ?? 0,
|
|
25645
|
+
detached: row?.detached ?? 0,
|
|
25646
|
+
capturesSkipped: captures?.skipped ?? 0
|
|
25647
|
+
};
|
|
25648
|
+
}
|
|
25649
|
+
/**
|
|
25650
|
+
* The deployment the current stamps were made against, and where its backlog
|
|
25651
|
+
* ends.
|
|
25652
|
+
*
|
|
25653
|
+
* READ-ONLY. An absent row reads as an absent deployment, which is what a
|
|
25654
|
+
* machine that has never drained is — and every writer below seeds the row
|
|
25655
|
+
* before it needs one, so nothing depends on this creating it. Keeping the
|
|
25656
|
+
* write off the gate path matters because the gate runs on every pass while a
|
|
25657
|
+
* write has to take the database's write lock.
|
|
25658
|
+
*/
|
|
25659
|
+
deployment() {
|
|
25660
|
+
const row = getRow(
|
|
25661
|
+
this.fingerprintStmt
|
|
25662
|
+
);
|
|
25663
|
+
return {
|
|
25664
|
+
fingerprint: row?.fingerprint ?? void 0,
|
|
25665
|
+
backlogBefore: row?.backlogBefore ?? void 0
|
|
25666
|
+
};
|
|
25667
|
+
}
|
|
25668
|
+
/**
|
|
25669
|
+
* Point the ledger at a different deployment, discarding what it recorded
|
|
25670
|
+
* about the previous one.
|
|
25671
|
+
*
|
|
25672
|
+
* Delivery is a fact about ONE recipient: rows sent to the deployment a
|
|
25673
|
+
* machine has just left are undelivered as far as the new one is concerned.
|
|
25674
|
+
* All four in one transaction, so a crash between them cannot leave stamps
|
|
25675
|
+
* attributed to the wrong deployment, a boundary that belongs to another, or
|
|
25676
|
+
* a disown with no re-mark to follow it.
|
|
25677
|
+
*
|
|
25678
|
+
* The boundary is written HERE and only here, which is what freezes it: a
|
|
25679
|
+
* re-attach to the SAME deployment (a key rotation) leaves the fingerprint
|
|
25680
|
+
* unchanged, so this never runs and the backlog does not widen back over rows
|
|
25681
|
+
* the live path has since delivered.
|
|
25682
|
+
*
|
|
25683
|
+
* `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
|
|
25684
|
+
* granted existing-history consent for the deployment this call is arming —
|
|
25685
|
+
* a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
|
|
25686
|
+
* instant, `backlogBefore` is the ATTACH instant, and the two can be far
|
|
25687
|
+
* apart. Passed only when that grant is valid, since this method has no way
|
|
25688
|
+
* to check consent itself and must not mark a row owed for a machine that
|
|
25689
|
+
* never agreed to it. Applied AFTER the disown above, in the SAME
|
|
25690
|
+
* transaction: what the disown clears is every marker below `backlogBefore`,
|
|
25691
|
+
* which includes this deployment's OWN pre-attach rows — `aka attach` calls
|
|
25692
|
+
* `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
|
|
25693
|
+
* on the cleared side of that bound — and the re-mark in the same
|
|
25694
|
+
* transaction is what puts those rows back. A crash between the two cannot
|
|
25695
|
+
* strand the ledger disowned with nothing re-marked — the transaction either
|
|
25696
|
+
* lands whole or not at all, and a fingerprint mismatch that has not yet
|
|
25697
|
+
* committed re-enters this method on the very next pass. Omit it (the
|
|
25698
|
+
* structural-only tests do) to exercise the disown in isolation.
|
|
25699
|
+
*
|
|
25700
|
+
* The disown is bounded by `backlogBefore`, which is what keeps it from
|
|
25701
|
+
* touching a marker the NEW deployment's OWN live path has already set: B's
|
|
25702
|
+
* live path can mark a capture owed from the moment `aka attach` writes the
|
|
25703
|
+
* descriptor, before the drain's first pass ever reaches this method, and
|
|
25704
|
+
* such a row sits at or after the bound rather than below it. What keeps the
|
|
25705
|
+
* disown from eating THIS SAME CALL's own re-mark is the order, not the
|
|
25706
|
+
* bound — disown runs first, re-mark second, both inside the one
|
|
25707
|
+
* transaction above.
|
|
25708
|
+
*/
|
|
25709
|
+
rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
|
|
25710
|
+
this.ensureRowStmt.run();
|
|
25711
|
+
withTransaction(
|
|
25712
|
+
this.db,
|
|
25713
|
+
() => {
|
|
25714
|
+
const previous = getRow(this.fingerprintStmt)?.fingerprint;
|
|
25715
|
+
this.rearmStmt.run();
|
|
25716
|
+
if (previous !== null && previous !== void 0 && previous !== fingerprint) {
|
|
25717
|
+
this.disownCapturesStmt.run({ attachedAt: backlogBefore });
|
|
25718
|
+
}
|
|
25719
|
+
if (backfillCapturesBefore !== void 0) {
|
|
25720
|
+
this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
|
|
25721
|
+
}
|
|
25722
|
+
this.setFingerprintStmt.run({ fingerprint, backlogBefore });
|
|
25723
|
+
},
|
|
25724
|
+
"IMMEDIATE"
|
|
25725
|
+
);
|
|
25726
|
+
}
|
|
25727
|
+
/**
|
|
25728
|
+
* End the attached period: hand its rows to the live path, and release the
|
|
25729
|
+
* boundary so the next attachment can freeze a new one.
|
|
25730
|
+
*
|
|
25731
|
+
* WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
|
|
25732
|
+
* nothing delivers. The fingerprint is unchanged, so the boundary is never
|
|
25733
|
+
* re-frozen and stays at the FIRST attachment — while nothing forwards at all
|
|
25734
|
+
* during the detached period, because the machine is not attached. Rows
|
|
25735
|
+
* recorded in that window sit after the boundary and before the re-attach, so
|
|
25736
|
+
* neither path takes them, and the pending count reports none outstanding.
|
|
25737
|
+
*
|
|
25738
|
+
* WHAT IT RECORDS, and what it deliberately does not. These rows were the
|
|
25739
|
+
* closing attachment's to deliver and are no longer outstanding — that is what
|
|
25740
|
+
* lets the boundary move. It is NOT a claim that any of them arrived, and the
|
|
25741
|
+
* distinction is not academic: this used to write a delivery TIME, which every
|
|
25742
|
+
* read treats as delivery, so one detach turned a window of undelivered rows
|
|
25743
|
+
* into a window of delivered ones and no surface could tell. It writes the
|
|
25744
|
+
* skip sentinel and a reason of its own instead, so "no longer owed" and
|
|
25745
|
+
* "received" stop being the same fact.
|
|
25746
|
+
*
|
|
25747
|
+
* A change of deployment still frees them (see the re-arm), because the next
|
|
25748
|
+
* deployment has seen none of this machine's history — so the rows reach it
|
|
25749
|
+
* exactly as they did when this wrote a delivery time.
|
|
25750
|
+
*
|
|
25751
|
+
* ONE TRANSACTION, so a crash cannot release the boundary while leaving the
|
|
25752
|
+
* window unstamped — that half-state would re-send the whole attached period
|
|
25753
|
+
* on the next attach, which is the failure the boundary exists to prevent.
|
|
25754
|
+
*/
|
|
25755
|
+
closeAttachedWindow(attachedAtMs, atMs) {
|
|
25756
|
+
this.ensureRowStmt.run();
|
|
25757
|
+
withTransaction(
|
|
25758
|
+
this.db,
|
|
25759
|
+
() => {
|
|
25760
|
+
const row = getRow(this.fingerprintStmt);
|
|
25761
|
+
const from = row?.backlogBefore ?? attachedAtMs;
|
|
25762
|
+
this.closeWindowStmt.run({ at: atMs, attachedAt: from });
|
|
25763
|
+
this.releaseBoundaryStmt.run();
|
|
25764
|
+
},
|
|
25765
|
+
"IMMEDIATE"
|
|
25766
|
+
);
|
|
25767
|
+
}
|
|
25768
|
+
/**
|
|
25769
|
+
* Freeze a boundary for the deployment already on file, KEEPING the stamps.
|
|
25770
|
+
*
|
|
25771
|
+
* The re-attach half of the above. Distinct from `rearmFor`, which is for a
|
|
25772
|
+
* different deployment and therefore discards what was delivered to the old
|
|
25773
|
+
* one: here the recipient is the same, so everything already sent to it stays
|
|
25774
|
+
* sent.
|
|
25775
|
+
*/
|
|
25776
|
+
freezeBoundary(backlogBefore) {
|
|
25777
|
+
this.ensureRowStmt.run();
|
|
25778
|
+
this.freezeBoundaryStmt.run({ backlogBefore });
|
|
25779
|
+
}
|
|
25780
|
+
/** Take the claim, or report that someone live already holds it. */
|
|
25781
|
+
claim(pid, host, nowMs, staleAfterMs) {
|
|
25782
|
+
this.ensureRowStmt.run();
|
|
25783
|
+
let taken = false;
|
|
25784
|
+
withTransaction(
|
|
25785
|
+
this.db,
|
|
25786
|
+
() => {
|
|
25787
|
+
const result = this.claimStmt.run({
|
|
25788
|
+
pid,
|
|
25789
|
+
host,
|
|
25790
|
+
now: nowMs,
|
|
25791
|
+
staleBefore: nowMs - staleAfterMs
|
|
25792
|
+
});
|
|
25793
|
+
taken = result.changes === 1;
|
|
25794
|
+
},
|
|
25795
|
+
"IMMEDIATE"
|
|
25796
|
+
);
|
|
25797
|
+
return taken;
|
|
25798
|
+
}
|
|
25799
|
+
/** Say the holder is still alive. A no-op once the claim has moved on. */
|
|
25800
|
+
heartbeat(pid, nowMs) {
|
|
25801
|
+
this.heartbeatStmt.run({ now: nowMs, pid });
|
|
25802
|
+
}
|
|
25803
|
+
/** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
|
|
25804
|
+
release(pid) {
|
|
25805
|
+
this.releaseStmt.run({ pid });
|
|
25806
|
+
}
|
|
25807
|
+
/** Who holds the claim, if anyone. Read-only, for the same reason as above. */
|
|
25808
|
+
lease() {
|
|
25809
|
+
return getRow(this.leaseStmt);
|
|
25810
|
+
}
|
|
25811
|
+
};
|
|
25812
|
+
|
|
25813
|
+
// ../../packages/persistence/src/migrations.ts
|
|
25814
|
+
function describeObject(object2) {
|
|
25815
|
+
return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
|
|
25816
|
+
}
|
|
25817
|
+
function splitStatements(sql) {
|
|
25818
|
+
return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
|
|
25819
|
+
}
|
|
25820
|
+
function createdIndexName(statement) {
|
|
25821
|
+
const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
|
|
25822
|
+
return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
|
|
25823
|
+
}
|
|
25824
|
+
var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
|
|
25825
|
+
function applyMigrations(db, file2, options = {}) {
|
|
25826
|
+
const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
|
|
25827
|
+
db.exec(
|
|
25828
|
+
"CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
|
|
25829
|
+
);
|
|
25830
|
+
const applied = new Set(
|
|
25831
|
+
db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
|
|
25832
|
+
);
|
|
25833
|
+
const preLedgerStore = applied.size === 0 && legacyCount > 0;
|
|
25834
|
+
const record2 = db.prepare(
|
|
25835
|
+
"INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
|
|
25836
|
+
);
|
|
25837
|
+
for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
|
|
25838
|
+
if (applied.has(migration.tag)) continue;
|
|
25839
|
+
if (options.skipTags?.has(migration.tag) === true) continue;
|
|
25840
|
+
if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
|
|
25841
|
+
const evidence = evidenceObjects(migration.sql);
|
|
25842
|
+
const present = evidence.filter((o) => evidenceExists(db, o));
|
|
25843
|
+
if (present.length > 0 && present.length < evidence.length) {
|
|
25844
|
+
const missing = evidence.filter((o) => !present.includes(o));
|
|
25845
|
+
const message = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
|
|
25846
|
+
akaWarn(message);
|
|
25847
|
+
throw new Error(`[aka] ${message}`);
|
|
25848
|
+
}
|
|
25849
|
+
const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
|
|
25850
|
+
const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
|
|
25851
|
+
const statements = splitStatements(migration.sql);
|
|
25852
|
+
if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
|
|
25853
|
+
try {
|
|
25854
|
+
withTransaction(
|
|
25855
|
+
db,
|
|
25856
|
+
() => {
|
|
25857
|
+
for (const statement of statements) {
|
|
25858
|
+
const indexName = createdIndexName(statement);
|
|
25859
|
+
if (indexName === void 0) {
|
|
25860
|
+
if (alreadyApplied) continue;
|
|
25861
|
+
} else if (indexExists(db, indexName)) {
|
|
25862
|
+
continue;
|
|
25863
|
+
}
|
|
25864
|
+
db.exec(statement);
|
|
25865
|
+
}
|
|
25866
|
+
if (wantsFkOff && !alreadyApplied) {
|
|
25867
|
+
const violations = db.prepare("PRAGMA foreign_key_check").all();
|
|
25868
|
+
if (violations.length > 0) {
|
|
25869
|
+
throw new Error(
|
|
25870
|
+
`[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
|
|
25871
|
+
);
|
|
25872
|
+
}
|
|
25873
|
+
}
|
|
25874
|
+
record2.run(migration.tag, Date.now());
|
|
25875
|
+
},
|
|
25876
|
+
"IMMEDIATE"
|
|
25877
|
+
);
|
|
25878
|
+
} finally {
|
|
25879
|
+
if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
|
|
25880
|
+
}
|
|
25881
|
+
}
|
|
25882
|
+
if (legacyCount < SQLITE_MIGRATIONS.length) {
|
|
25883
|
+
db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
|
|
25884
|
+
}
|
|
25885
|
+
ensureSyncedAtColumn(db, "audit_events");
|
|
25886
|
+
ensureScanLedgerTable(db);
|
|
25887
|
+
ensureHistorySyncTable(db);
|
|
25888
|
+
ensureBlockedDetectionsTable(db);
|
|
25889
|
+
ensureRuleProbeCacheTable(db);
|
|
25890
|
+
ensureWriteGateTrigger(db);
|
|
25891
|
+
ensureTokenUsageColumns(db);
|
|
25892
|
+
reconcileSourceProjectIds(db);
|
|
25893
|
+
if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
|
|
25894
|
+
const drained = runLegacyHistoryBackfill(db);
|
|
25895
|
+
if (drained) applyLegacyDropMigration(db, file2);
|
|
25896
|
+
}
|
|
25897
|
+
}
|
|
25898
|
+
function readLegacyTables(db) {
|
|
25899
|
+
let holdsRows = false;
|
|
25900
|
+
const marks = [];
|
|
25901
|
+
for (const table of ["events", "findings"]) {
|
|
25902
|
+
try {
|
|
25903
|
+
const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
|
|
25904
|
+
if (row === void 0) {
|
|
25905
|
+
holdsRows = true;
|
|
25906
|
+
marks.push(`${table}:unreadable`);
|
|
25907
|
+
continue;
|
|
25908
|
+
}
|
|
25909
|
+
if (row.n > 0) holdsRows = true;
|
|
25910
|
+
marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
|
|
25911
|
+
} catch {
|
|
25912
|
+
holdsRows = true;
|
|
25913
|
+
marks.push(`${table}:unreadable`);
|
|
25914
|
+
}
|
|
25915
|
+
}
|
|
25916
|
+
return { holdsRows, mark: marks.join("|") };
|
|
25917
|
+
}
|
|
25918
|
+
function applyLegacyDropMigration(db, file2) {
|
|
25919
|
+
const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
|
|
25920
|
+
if (!migration) return;
|
|
25921
|
+
const before = file2 === void 0 ? void 0 : readLegacyTables(db);
|
|
25922
|
+
if (file2 !== void 0 && before?.holdsRows === true) {
|
|
25923
|
+
try {
|
|
25924
|
+
backupBeforeLegacyDrop(db, file2);
|
|
25925
|
+
} catch (error61) {
|
|
25926
|
+
akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
|
|
25927
|
+
return;
|
|
25928
|
+
}
|
|
25929
|
+
}
|
|
25930
|
+
try {
|
|
25931
|
+
withTransaction(
|
|
25932
|
+
db,
|
|
25933
|
+
() => {
|
|
25934
|
+
const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
|
|
25935
|
+
if (alreadyDropped) return;
|
|
25936
|
+
if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
|
|
25937
|
+
akaWarn(
|
|
25938
|
+
"legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
|
|
25939
|
+
);
|
|
25940
|
+
return;
|
|
25941
|
+
}
|
|
25942
|
+
for (const statement of splitStatements(migration.sql)) {
|
|
25943
|
+
db.exec(statement);
|
|
25944
|
+
}
|
|
25945
|
+
db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
|
|
25946
|
+
migration.tag,
|
|
25947
|
+
Date.now()
|
|
24928
25948
|
);
|
|
24929
25949
|
},
|
|
24930
25950
|
"IMMEDIATE"
|
|
@@ -25223,10 +26243,62 @@ function ensureSyncedAtColumn(db, table) {
|
|
|
25223
26243
|
if (!columns.includes("outbox_owed")) {
|
|
25224
26244
|
db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
|
|
25225
26245
|
}
|
|
26246
|
+
if (!columns.includes("sync_failed_at")) {
|
|
26247
|
+
db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
|
|
26248
|
+
}
|
|
26249
|
+
if (!columns.includes("sync_failure")) {
|
|
26250
|
+
withTransaction(
|
|
26251
|
+
db,
|
|
26252
|
+
() => {
|
|
26253
|
+
db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
|
|
26254
|
+
db.exec(
|
|
26255
|
+
`UPDATE ${table} SET synced_at = NULL
|
|
26256
|
+
WHERE synced_at = -1
|
|
26257
|
+
AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
|
|
26258
|
+
);
|
|
26259
|
+
},
|
|
26260
|
+
"IMMEDIATE"
|
|
26261
|
+
);
|
|
26262
|
+
}
|
|
25226
26263
|
db.exec(
|
|
25227
|
-
`CREATE
|
|
25228
|
-
|
|
26264
|
+
`CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
|
|
26265
|
+
BEFORE UPDATE OF sync_failure ON ${table}
|
|
26266
|
+
WHEN ${syncFailureRejectCondition()}
|
|
26267
|
+
BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
|
|
25229
26268
|
);
|
|
26269
|
+
const syncIndexColumns = [
|
|
26270
|
+
"event_type",
|
|
26271
|
+
"synced_at",
|
|
26272
|
+
"sync_claimed_at",
|
|
26273
|
+
"started_at",
|
|
26274
|
+
// Appended LAST on purpose. The delivery-state read now projects it, so it
|
|
26275
|
+
// has to be in the index for the read to stay covered — but putting it
|
|
26276
|
+
// ahead of `started_at` would reorder the prefix the structural drain's
|
|
26277
|
+
// reads match on.
|
|
26278
|
+
"sync_failure"
|
|
26279
|
+
// `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
|
|
26280
|
+
//
|
|
26281
|
+
// The delivery-state read tests it — a capture's state depends on whether a
|
|
26282
|
+
// live forward marked it owed — so carrying it here makes that read covering
|
|
26283
|
+
// rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
|
|
26284
|
+
// But a sixth column changes what the planner charges for this index, and
|
|
26285
|
+
// with no ANALYZE statistics it plans from schema shape alone: measured, it
|
|
26286
|
+
// then stops choosing the per-session index for the token rollup and walks
|
|
26287
|
+
// every `llm_call` in the store through the event-type index instead. That
|
|
26288
|
+
// read grows with the store; this one does not.
|
|
26289
|
+
//
|
|
26290
|
+
// 40 ms on the largest store measured, once per render, is a cost worth
|
|
26291
|
+
// paying to leave every other read's plan where it was.
|
|
26292
|
+
];
|
|
26293
|
+
const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
|
|
26294
|
+
const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
|
|
26295
|
+
if (!syncIndexMatches) {
|
|
26296
|
+
db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
|
|
26297
|
+
db.exec(
|
|
26298
|
+
`CREATE INDEX idx_audit_events_sync
|
|
26299
|
+
ON audit_events (${syncIndexColumns.join(", ")})`
|
|
26300
|
+
);
|
|
26301
|
+
}
|
|
25230
26302
|
db.exec(
|
|
25231
26303
|
`CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
|
|
25232
26304
|
ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
|
|
@@ -25448,7 +26520,11 @@ function buildAuditEvent(row) {
|
|
|
25448
26520
|
link: linkParsed?.success ? linkParsed.data : null,
|
|
25449
26521
|
targetId: row.target_id,
|
|
25450
26522
|
internal: intToBool(row.internal),
|
|
25451
|
-
flagged: intToBool(row.flagged)
|
|
26523
|
+
flagged: intToBool(row.flagged),
|
|
26524
|
+
// Only meaningful when the title came out empty — a row whose body was
|
|
26525
|
+
// expired but whose title fell back to `tool_name` still has something to
|
|
26526
|
+
// render, and flagging it would make the view apologise for nothing.
|
|
26527
|
+
bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
|
|
25452
26528
|
};
|
|
25453
26529
|
}
|
|
25454
26530
|
var TIMELINE_COLUMNS = `
|
|
@@ -25456,6 +26532,7 @@ var TIMELINE_COLUMNS = `
|
|
|
25456
26532
|
event_type,
|
|
25457
26533
|
started_at,
|
|
25458
26534
|
coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
|
|
26535
|
+
content_expired_at,
|
|
25459
26536
|
coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
|
|
25460
26537
|
coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
|
|
25461
26538
|
json_extract(attributes, '$.severity') AS severity,
|
|
@@ -25582,7 +26659,8 @@ var SqliteActivityRepository = class {
|
|
|
25582
26659
|
SELECT 1 FROM audit_events d
|
|
25583
26660
|
WHERE d.root_session_id = audit_events.id
|
|
25584
26661
|
AND (d.content LIKE ? ESCAPE '\\'
|
|
25585
|
-
OR json_extract(d.attributes, '$.detail')
|
|
26662
|
+
OR coalesce(json_extract(d.attributes, '$.detail'),
|
|
26663
|
+
json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
|
|
25586
26664
|
);
|
|
25587
26665
|
params.push(pattern, pattern, pattern, pattern, pattern, pattern);
|
|
25588
26666
|
}
|
|
@@ -26120,6 +27198,88 @@ var SqliteAuditEventsRepository = class {
|
|
|
26120
27198
|
}
|
|
26121
27199
|
};
|
|
26122
27200
|
|
|
27201
|
+
// ../../packages/persistence/src/repositories/body-retention.ts
|
|
27202
|
+
var DEFAULT_BATCH_SIZE = 500;
|
|
27203
|
+
var DEFAULT_MAX_ROWS = 5e4;
|
|
27204
|
+
var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
|
|
27205
|
+
var SqliteBodyRetentionRepository = class {
|
|
27206
|
+
constructor(db) {
|
|
27207
|
+
this.db = db;
|
|
27208
|
+
const select = (laneClause) => `
|
|
27209
|
+
SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
|
|
27210
|
+
FROM audit_events
|
|
27211
|
+
WHERE content IS NOT NULL
|
|
27212
|
+
AND started_at < :cutoff
|
|
27213
|
+
AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
|
|
27214
|
+
${laneClause}
|
|
27215
|
+
ORDER BY started_at
|
|
27216
|
+
LIMIT :limit`;
|
|
27217
|
+
this.candidatesStmt = this.db.prepare(select(""));
|
|
27218
|
+
this.candidatesSyncSafeStmt = this.db.prepare(
|
|
27219
|
+
select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
|
|
27220
|
+
);
|
|
27221
|
+
this.heldBySyncStmt = this.db.prepare(`
|
|
27222
|
+
SELECT COUNT(*) AS n
|
|
27223
|
+
FROM audit_events
|
|
27224
|
+
WHERE content IS NOT NULL
|
|
27225
|
+
AND started_at < :cutoff
|
|
27226
|
+
AND event_type IN (${SYNC_LANE_TYPES_SQL})
|
|
27227
|
+
AND synced_at IS NULL`);
|
|
27228
|
+
this.expireStmt = this.db.prepare(
|
|
27229
|
+
`UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
|
|
27230
|
+
);
|
|
27231
|
+
}
|
|
27232
|
+
db;
|
|
27233
|
+
candidatesStmt;
|
|
27234
|
+
candidatesSyncSafeStmt;
|
|
27235
|
+
heldBySyncStmt;
|
|
27236
|
+
expireStmt;
|
|
27237
|
+
/** How many bytes a pass with these options would free, changing nothing. */
|
|
27238
|
+
preview(opts) {
|
|
27239
|
+
const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
|
|
27240
|
+
const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
|
|
27241
|
+
const rows = stmt.all({ cutoff: opts.cutoff, limit });
|
|
27242
|
+
return {
|
|
27243
|
+
rowsExpired: rows.length,
|
|
27244
|
+
bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
|
|
27245
|
+
rowsHeldBySync: this.countHeldBySync(opts)
|
|
27246
|
+
};
|
|
27247
|
+
}
|
|
27248
|
+
/** Clear eligible bodies, in bounded batches. */
|
|
27249
|
+
expire(opts) {
|
|
27250
|
+
const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
|
|
27251
|
+
const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
|
|
27252
|
+
const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
|
|
27253
|
+
let rowsExpired = 0;
|
|
27254
|
+
let bytesFreed = 0;
|
|
27255
|
+
let done = true;
|
|
27256
|
+
while (rowsExpired < maxRows) {
|
|
27257
|
+
const remaining = Math.min(batchSize, maxRows - rowsExpired);
|
|
27258
|
+
const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
|
|
27259
|
+
if (batch.length === 0) break;
|
|
27260
|
+
withTransaction(
|
|
27261
|
+
this.db,
|
|
27262
|
+
() => {
|
|
27263
|
+
for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
|
|
27264
|
+
},
|
|
27265
|
+
"IMMEDIATE"
|
|
27266
|
+
);
|
|
27267
|
+
rowsExpired += batch.length;
|
|
27268
|
+
bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
|
|
27269
|
+
if (batch.length < remaining) break;
|
|
27270
|
+
if (rowsExpired >= maxRows) {
|
|
27271
|
+
done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
|
|
27272
|
+
}
|
|
27273
|
+
}
|
|
27274
|
+
return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
|
|
27275
|
+
}
|
|
27276
|
+
countHeldBySync(opts) {
|
|
27277
|
+
if (opts.sweepSyncLane) return 0;
|
|
27278
|
+
const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
|
|
27279
|
+
return row.n;
|
|
27280
|
+
}
|
|
27281
|
+
};
|
|
27282
|
+
|
|
26123
27283
|
// ../../packages/persistence/src/repositories/classified-data.ts
|
|
26124
27284
|
var SqliteClassifiedDataRepository = class {
|
|
26125
27285
|
constructor(db) {
|
|
@@ -26920,23 +28080,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
|
|
|
26920
28080
|
)`;
|
|
26921
28081
|
|
|
26922
28082
|
// ../../packages/persistence/src/repositories/findings.ts
|
|
26923
|
-
var PREVIEW_INSTANCES_PER_GROUP = 200;
|
|
26924
|
-
var DEFAULT_LOCATIONS_LIMIT = 100;
|
|
26925
|
-
var LOCATION_RULE_IDS_CAP = 20;
|
|
26926
|
-
function compareLocationOrder(a, b) {
|
|
26927
|
-
return compareFindingGroupOrder(
|
|
26928
|
-
{
|
|
26929
|
-
severity: a.maxSeverity,
|
|
26930
|
-
latestDetectedAt: a.latestDetectedAt,
|
|
26931
|
-
id: ""
|
|
26932
|
-
},
|
|
26933
|
-
{
|
|
26934
|
-
severity: b.maxSeverity,
|
|
26935
|
-
latestDetectedAt: b.latestDetectedAt,
|
|
26936
|
-
id: ""
|
|
26937
|
-
}
|
|
26938
|
-
);
|
|
26939
|
-
}
|
|
26940
28083
|
var CONCAT_SEP = ",";
|
|
26941
28084
|
var TUPLE_SEP = "|";
|
|
26942
28085
|
function splitConcat(value) {
|
|
@@ -26965,7 +28108,15 @@ function toFlatFindingRow(r) {
|
|
|
26965
28108
|
...r.tool_name === null ? {} : { toolName: r.tool_name },
|
|
26966
28109
|
eventId: r.event_id,
|
|
26967
28110
|
...r.session_id === null ? {} : { sessionId: r.session_id },
|
|
26968
|
-
status: deriveInstanceStatus(r)
|
|
28111
|
+
status: deriveInstanceStatus(r),
|
|
28112
|
+
delivery: deriveFindingDelivery({
|
|
28113
|
+
kind: r.kind,
|
|
28114
|
+
syncedAt: r.synced_at,
|
|
28115
|
+
syncClaimedAt: r.sync_claimed_at,
|
|
28116
|
+
syncFailedAt: r.sync_failed_at,
|
|
28117
|
+
syncFailure: r.sync_failure,
|
|
28118
|
+
outboxOwed: r.outbox_owed
|
|
28119
|
+
})
|
|
26969
28120
|
};
|
|
26970
28121
|
}
|
|
26971
28122
|
function encodeGroupCursor(group) {
|
|
@@ -26988,13 +28139,51 @@ function decodeGroupCursor(cursor) {
|
|
|
26988
28139
|
return null;
|
|
26989
28140
|
}
|
|
26990
28141
|
function firstAfter(sorted, cursor) {
|
|
26991
|
-
const index = sorted.findIndex((
|
|
28142
|
+
const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
|
|
26992
28143
|
return index === -1 ? sorted.length : index;
|
|
26993
28144
|
}
|
|
26994
28145
|
function findDeepLinked(sorted, page, id) {
|
|
26995
|
-
if (page.some((
|
|
26996
|
-
return sorted.find((
|
|
28146
|
+
if (page.some((t) => t.id === id)) return void 0;
|
|
28147
|
+
return sorted.find((t) => t.id === id);
|
|
26997
28148
|
}
|
|
28149
|
+
function encodeLocationCursor(location) {
|
|
28150
|
+
const payload = {
|
|
28151
|
+
sev: location.maxSeverity,
|
|
28152
|
+
t: location.latestDetectedAt,
|
|
28153
|
+
r: location.repo,
|
|
28154
|
+
f: location.file
|
|
28155
|
+
};
|
|
28156
|
+
return Buffer.from(JSON.stringify(payload)).toString("base64url");
|
|
28157
|
+
}
|
|
28158
|
+
function decodeLocationCursor(cursor) {
|
|
28159
|
+
const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
28160
|
+
if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
|
|
28161
|
+
return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
|
|
28162
|
+
}
|
|
28163
|
+
return null;
|
|
28164
|
+
}
|
|
28165
|
+
function firstLocationAfter(sorted, cursor) {
|
|
28166
|
+
const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
|
|
28167
|
+
return index === -1 ? sorted.length : index;
|
|
28168
|
+
}
|
|
28169
|
+
function findDeepLinkedLocation(sorted, page, id) {
|
|
28170
|
+
if (page.some((l) => l.id === id)) return void 0;
|
|
28171
|
+
return sorted.find((l) => l.id === id);
|
|
28172
|
+
}
|
|
28173
|
+
var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
|
|
28174
|
+
d.severity AS severity, f.masked_match AS masked_match,
|
|
28175
|
+
f.action_taken AS action_taken, f.confidence AS confidence,
|
|
28176
|
+
e.started_at AS occurred_at,
|
|
28177
|
+
e.source_tool AS source_tool,
|
|
28178
|
+
e.repo AS repo,
|
|
28179
|
+
e.file_path AS file,
|
|
28180
|
+
e.tool_name AS tool_name,
|
|
28181
|
+
f.audit_event_id AS event_id, e.root_session_id AS session_id,
|
|
28182
|
+
e.event_type AS kind, f.finding_key AS finding_key,
|
|
28183
|
+
${latestResolutionStatusSql("f")} AS latest_status,
|
|
28184
|
+
e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
|
|
28185
|
+
e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
|
|
28186
|
+
e.outbox_owed AS outbox_owed`;
|
|
26998
28187
|
var DAY_MS3 = 864e5;
|
|
26999
28188
|
var SqliteFindingsRepository = class {
|
|
27000
28189
|
constructor(db) {
|
|
@@ -27115,30 +28304,26 @@ var SqliteFindingsRepository = class {
|
|
|
27115
28304
|
);
|
|
27116
28305
|
}
|
|
27117
28306
|
/**
|
|
27118
|
-
*
|
|
27119
|
-
*
|
|
27120
|
-
*
|
|
27121
|
-
*
|
|
27122
|
-
*
|
|
27123
|
-
*
|
|
27124
|
-
*
|
|
27125
|
-
*
|
|
27126
|
-
*
|
|
27127
|
-
*
|
|
27128
|
-
*
|
|
27129
|
-
*
|
|
28307
|
+
* Finding TYPES for the dashboard — one row per rule, scoped to the four
|
|
28308
|
+
* capture kinds (audit_events also holds structural/reconciler/scan rows this
|
|
28309
|
+
* list must never surface), with per-filter-excluded facets, the requested
|
|
28310
|
+
* filters applied, and sorted by severity then recency. Filtering and faceting
|
|
28311
|
+
* run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
|
|
28312
|
+
* full filtered set; `items` is the requested page (default 50), keyset-paged.
|
|
28313
|
+
* Under a `status` filter, `totals.findings` counts only findings whose
|
|
28314
|
+
* derived status was requested.
|
|
28315
|
+
*
|
|
28316
|
+
* ONE read, which materializes no findings: a single aggregate per rule_id,
|
|
28317
|
+
* folding EVERY finding into the numbers a type row and the filters need
|
|
28318
|
+
* (count, severity, category, providers, actions, statuses, latest, search
|
|
28319
|
+
* text). The findings OF a type come from listFindingInstances scoped to
|
|
28320
|
+
* `subtype`, so neither list bounds the other and no per-type cap exists.
|
|
27130
28321
|
*
|
|
27131
|
-
* Two reads, neither of which materializes a row per finding:
|
|
27132
|
-
* 1. one aggregate row per rule_id, folding EVERY instance into the numbers
|
|
27133
|
-
* the group and the filters need (count, providers, actions, statuses,
|
|
27134
|
-
* latest, search text);
|
|
27135
|
-
* 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
|
|
27136
|
-
* populate `instances` for the table's expanded rows.
|
|
27137
28322
|
* The aggregates carry raw DB values and are translated by the same
|
|
27138
|
-
* @akasecurity/schema mappers
|
|
27139
|
-
* rule is ever restated in SQL.
|
|
28323
|
+
* @akasecurity/schema mappers every other path uses, so no enum mapping or
|
|
28324
|
+
* status rule is ever restated in SQL.
|
|
27140
28325
|
*/
|
|
27141
|
-
|
|
28326
|
+
listFindingTypes(query) {
|
|
27142
28327
|
const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
|
|
27143
28328
|
const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
|
|
27144
28329
|
const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
|
|
@@ -27151,12 +28336,7 @@ var SqliteFindingsRepository = class {
|
|
|
27151
28336
|
predicate,
|
|
27152
28337
|
params: sessionParams
|
|
27153
28338
|
});
|
|
27154
|
-
const
|
|
27155
|
-
sessionId: query.sessionId,
|
|
27156
|
-
from: query.from
|
|
27157
|
-
});
|
|
27158
|
-
const groupable = rows.map(toFlatFindingRow);
|
|
27159
|
-
const allGroups = buildFindingGroups(groupable, { aggregates });
|
|
28339
|
+
const allTypes = buildFindingTypes(aggregates);
|
|
27160
28340
|
const filterOpts = {
|
|
27161
28341
|
severity: query.severity,
|
|
27162
28342
|
providers: query.provider,
|
|
@@ -27165,30 +28345,25 @@ var SqliteFindingsRepository = class {
|
|
|
27165
28345
|
subtype: query.subtype,
|
|
27166
28346
|
q: query.q
|
|
27167
28347
|
};
|
|
27168
|
-
const facets = computeFindingFacets(
|
|
27169
|
-
const sorted =
|
|
28348
|
+
const facets = computeFindingFacets(allTypes, filterOpts);
|
|
28349
|
+
const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
|
|
27170
28350
|
const statusFilter = query.status ?? [];
|
|
27171
28351
|
const totals = {
|
|
27172
|
-
findings: sorted.reduce((acc,
|
|
27173
|
-
if (statusFilter.length === 0) return acc +
|
|
27174
|
-
const agg = aggregates.get(
|
|
27175
|
-
return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ??
|
|
28352
|
+
findings: sorted.reduce((acc, t) => {
|
|
28353
|
+
if (statusFilter.length === 0) return acc + t.instanceCount;
|
|
28354
|
+
const agg = aggregates.get(t.id);
|
|
28355
|
+
return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
|
|
27176
28356
|
}, 0),
|
|
27177
|
-
|
|
28357
|
+
types: sorted.length
|
|
27178
28358
|
};
|
|
27179
|
-
const limit = query.limit ??
|
|
28359
|
+
const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
|
|
27180
28360
|
const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
|
|
27181
28361
|
const start = cursor === null ? 0 : firstAfter(sorted, cursor);
|
|
27182
28362
|
const page = sorted.slice(start, start + limit);
|
|
27183
28363
|
const lastOnPage = page.at(-1);
|
|
27184
28364
|
const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
|
|
27185
28365
|
const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
|
|
27186
|
-
const
|
|
27187
|
-
const narrow = (g) => statusSet ? {
|
|
27188
|
-
...g,
|
|
27189
|
-
instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
|
|
27190
|
-
} : g;
|
|
27191
|
-
const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
|
|
28366
|
+
const items = [...page, ...deepLinked ? [deepLinked] : []];
|
|
27192
28367
|
return Promise.resolve({
|
|
27193
28368
|
totals,
|
|
27194
28369
|
facets,
|
|
@@ -27199,7 +28374,7 @@ var SqliteFindingsRepository = class {
|
|
|
27199
28374
|
}
|
|
27200
28375
|
/**
|
|
27201
28376
|
* One row per rule_id, folding EVERY instance of the group into the values
|
|
27202
|
-
*
|
|
28377
|
+
* buildFindingTypes cannot recover from an aggregate. Bounded by the number of
|
|
27203
28378
|
* distinct rule_ids (the installed packs' rules), not by the store's size.
|
|
27204
28379
|
*
|
|
27205
28380
|
* A single scan, folded in two levels: the inner SELECT groups by
|
|
@@ -27253,6 +28428,7 @@ var SqliteFindingsRepository = class {
|
|
|
27253
28428
|
providers: query.provider,
|
|
27254
28429
|
actions: query.action,
|
|
27255
28430
|
statuses: query.status,
|
|
28431
|
+
deliveries: query.deployment,
|
|
27256
28432
|
tools: query.tool,
|
|
27257
28433
|
repo: query.repo,
|
|
27258
28434
|
file: query.file,
|
|
@@ -27293,13 +28469,25 @@ var SqliteFindingsRepository = class {
|
|
|
27293
28469
|
});
|
|
27294
28470
|
}
|
|
27295
28471
|
/**
|
|
27296
|
-
* The same findings folded by
|
|
28472
|
+
* The same findings folded by WHERE they live — one row per (repo, file) pair.
|
|
27297
28473
|
*
|
|
27298
28474
|
* The grouping keys come from the capturing event's attributes, which is what
|
|
27299
|
-
* the local store relates a finding to
|
|
27300
|
-
*
|
|
27301
|
-
* empty-string bucket, which
|
|
27302
|
-
*
|
|
28475
|
+
* the local store relates a finding to; there is no finding↔asset row to group
|
|
28476
|
+
* by instead. A repo or file the event did not record folds into the
|
|
28477
|
+
* empty-string bucket, which is a real location like any other: it is listed,
|
|
28478
|
+
* it is selectable, and its `?loc=` token is as good as any other row's.
|
|
28479
|
+
*
|
|
28480
|
+
* ONE flat list rather than repos nesting files. A rollup can only be paged by
|
|
28481
|
+
* repo, which leaves the file list inside it unbounded — the shape the by-type
|
|
28482
|
+
* list was rebuilt to remove — and two-level pagination inside an
|
|
28483
|
+
* expand/collapse table is what pushed that view to master/detail in the first
|
|
28484
|
+
* place.
|
|
28485
|
+
*
|
|
28486
|
+
* Every filter narrows the FINDINGS and the locations fall out of what
|
|
28487
|
+
* survives, so each row's `instanceCount` is exactly what listFindingInstances
|
|
28488
|
+
* reports for the same filters scoped to that pair. The view depends on it:
|
|
28489
|
+
* one toolbar sits over both panels precisely because a location owns none of
|
|
28490
|
+
* its fields.
|
|
27303
28491
|
*/
|
|
27304
28492
|
listFindingLocations(query) {
|
|
27305
28493
|
const opts = {
|
|
@@ -27308,16 +28496,20 @@ var SqliteFindingsRepository = class {
|
|
|
27308
28496
|
providers: query.provider,
|
|
27309
28497
|
actions: query.action,
|
|
27310
28498
|
statuses: query.status,
|
|
28499
|
+
deliveries: query.deployment,
|
|
27311
28500
|
tools: query.tool,
|
|
27312
28501
|
q: query.q
|
|
27313
28502
|
};
|
|
27314
|
-
const limit = query.limit ??
|
|
28503
|
+
const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
|
|
28504
|
+
const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
|
|
27315
28505
|
const byRepo = /* @__PURE__ */ new Map();
|
|
28506
|
+
const accumulator = createInstanceFacetAccumulator(opts);
|
|
27316
28507
|
let total = 0;
|
|
27317
28508
|
for (const row of this.scanFindingRows({
|
|
27318
28509
|
sessionId: query.sessionId,
|
|
27319
28510
|
from: query.from
|
|
27320
28511
|
})) {
|
|
28512
|
+
accumulator.add(row);
|
|
27321
28513
|
if (!matchesInstanceFilters(row, opts)) continue;
|
|
27322
28514
|
total += 1;
|
|
27323
28515
|
let files = byRepo.get(row.repo);
|
|
@@ -27332,103 +28524,35 @@ var SqliteFindingsRepository = class {
|
|
|
27332
28524
|
}
|
|
27333
28525
|
addToLocation(acc, row);
|
|
27334
28526
|
}
|
|
27335
|
-
|
|
27336
|
-
const
|
|
27337
|
-
|
|
27338
|
-
|
|
27339
|
-
|
|
27340
|
-
|
|
27341
|
-
|
|
27342
|
-
|
|
27343
|
-
|
|
27344
|
-
|
|
27345
|
-
|
|
27346
|
-
|
|
27347
|
-
|
|
27348
|
-
|
|
27349
|
-
|
|
27350
|
-
|
|
27351
|
-
|
|
27352
|
-
|
|
27353
|
-
|
|
27354
|
-
|
|
27355
|
-
|
|
27356
|
-
|
|
27357
|
-
);
|
|
27358
|
-
const statuses = fileRows.map((f) => f.status);
|
|
27359
|
-
const folded = foldGroupStatus(statuses);
|
|
27360
|
-
return {
|
|
27361
|
-
repo,
|
|
27362
|
-
instanceCount: rollup.instanceCount,
|
|
27363
|
-
maxSeverity: rollup.maxSeverity,
|
|
27364
|
-
latestDetectedAt: rollup.latestDetectedAt,
|
|
27365
|
-
...folded === void 0 ? {} : { status: folded },
|
|
27366
|
-
files: fileRows
|
|
27367
|
-
};
|
|
27368
|
-
});
|
|
27369
|
-
repos.sort(compareLocationOrder);
|
|
28527
|
+
const sorted = [];
|
|
28528
|
+
for (const [repo, files] of byRepo) {
|
|
28529
|
+
for (const [file2, acc] of files) {
|
|
28530
|
+
const status = foldGroupStatus(acc.statuses);
|
|
28531
|
+
sorted.push({
|
|
28532
|
+
id: encodeLocationId(repo, file2),
|
|
28533
|
+
repo,
|
|
28534
|
+
file: file2,
|
|
28535
|
+
instanceCount: acc.instanceCount,
|
|
28536
|
+
maxSeverity: acc.maxSeverity,
|
|
28537
|
+
latestDetectedAt: acc.latestDetectedAt,
|
|
28538
|
+
...status === void 0 ? {} : { status },
|
|
28539
|
+
ruleIds: [...acc.ruleIds]
|
|
28540
|
+
});
|
|
28541
|
+
}
|
|
28542
|
+
}
|
|
28543
|
+
sorted.sort(compareLocationOrder);
|
|
28544
|
+
const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
|
|
28545
|
+
const page = sorted.slice(start, start + limit);
|
|
28546
|
+
const lastOnPage = page.at(-1);
|
|
28547
|
+
const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
|
|
28548
|
+
const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
|
|
27370
28549
|
return Promise.resolve({
|
|
27371
|
-
totals: { findings: total,
|
|
27372
|
-
|
|
27373
|
-
|
|
28550
|
+
totals: { findings: total, locations: sorted.length },
|
|
28551
|
+
facets: accumulator.facets(),
|
|
28552
|
+
items: [...page, ...deepLinked ? [deepLinked] : []],
|
|
28553
|
+
nextCursor
|
|
27374
28554
|
});
|
|
27375
28555
|
}
|
|
27376
|
-
/**
|
|
27377
|
-
* Each group's newest instances, for the table's expanded rows.
|
|
27378
|
-
*
|
|
27379
|
-
* ONE index-ordered scan with early termination, and the shape is the point.
|
|
27380
|
-
* The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
|
|
27381
|
-
* started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
|
|
27382
|
-
* through a temp B-tree to keep a bounded preview of each group, and then
|
|
27383
|
-
* sorts the survivors again for the page order. Both sorts grow with the
|
|
27384
|
-
* store while the answer does not.
|
|
27385
|
-
*
|
|
27386
|
-
* Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
|
|
27387
|
-
* (or the session or window index the scope names — see `findingScanSql`),
|
|
27388
|
-
* which is already the order the page wants, and keeps rows per rule until
|
|
27389
|
-
* each rule has as many as it can show. The aggregate the caller already holds
|
|
27390
|
-
* says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
|
|
27391
|
-
* per rule, summed, is the number of rows this scan has to find, and it stops
|
|
27392
|
-
* on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
|
|
27393
|
-
* (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
|
|
27394
|
-
* store with many firing rules widens it. The bound that DOES hold
|
|
27395
|
-
* unconditionally is the sorted form's floor: this scan visits at most as
|
|
27396
|
-
* many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
|
|
27397
|
-
* sorted, and stops the moment every rule has its cap, where the sorted form
|
|
27398
|
-
* sorts the whole scope regardless. The true worst case — the rarest rule's
|
|
27399
|
-
* wanted instances sitting at the tail of the scope — is one pass over
|
|
27400
|
-
* everything in scope with a block sort of the id tie-break only, never a
|
|
27401
|
-
* sort of the scope, which is still that floor.
|
|
27402
|
-
*
|
|
27403
|
-
* A row whose rule the aggregate did not see is skipped: the two statements
|
|
27404
|
-
* run without a shared snapshot, so a capture landing between them can add a
|
|
27405
|
-
* rule here that has no counts there, and the counts are what the group is
|
|
27406
|
-
* built from.
|
|
27407
|
-
*/
|
|
27408
|
-
previewRows(aggregates, scope) {
|
|
27409
|
-
const wanted = /* @__PURE__ */ new Map();
|
|
27410
|
-
let remaining = 0;
|
|
27411
|
-
for (const [ruleId, agg] of aggregates) {
|
|
27412
|
-
const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
|
|
27413
|
-
wanted.set(ruleId, n);
|
|
27414
|
-
remaining += n;
|
|
27415
|
-
}
|
|
27416
|
-
const rows = [];
|
|
27417
|
-
if (remaining === 0) return rows;
|
|
27418
|
-
const { sql, params } = this.findingScanSql(scope);
|
|
27419
|
-
const taken = /* @__PURE__ */ new Map();
|
|
27420
|
-
for (const r of iterateRows(this.db.prepare(sql), params)) {
|
|
27421
|
-
const want = wanted.get(r.rule_id);
|
|
27422
|
-
if (want === void 0) continue;
|
|
27423
|
-
const have = taken.get(r.rule_id) ?? 0;
|
|
27424
|
-
if (have >= want) continue;
|
|
27425
|
-
taken.set(r.rule_id, have + 1);
|
|
27426
|
-
rows.push(r);
|
|
27427
|
-
remaining -= 1;
|
|
27428
|
-
if (remaining === 0) break;
|
|
27429
|
-
}
|
|
27430
|
-
return rows;
|
|
27431
|
-
}
|
|
27432
28556
|
/**
|
|
27433
28557
|
* Every finding in scope as a FlatFindingRow, newest first, streamed.
|
|
27434
28558
|
*
|
|
@@ -27455,6 +28579,33 @@ var SqliteFindingsRepository = class {
|
|
|
27455
28579
|
yield toFlatFindingRow(r);
|
|
27456
28580
|
}
|
|
27457
28581
|
}
|
|
28582
|
+
/**
|
|
28583
|
+
* One finding by its own id, or null when no such row exists.
|
|
28584
|
+
*
|
|
28585
|
+
* A primary-key seek on `inspection_findings`, so its cost does not grow with
|
|
28586
|
+
* the store — and, unlike anything derived from a list page, it resolves a
|
|
28587
|
+
* finding of ANY age. That is what the Findings page's one-shot `?finding=`
|
|
28588
|
+
* deep link needs: the id it carries may name a finding thousands of rows
|
|
28589
|
+
* older than anything a first page holds.
|
|
28590
|
+
*
|
|
28591
|
+
* Deliberately UNFILTERED — no capture-kind, session or time predicate. It
|
|
28592
|
+
* RESOLVES an id; whether that row would survive the list's current filters is
|
|
28593
|
+
* a different question, and hiding the target because a filter excludes it is
|
|
28594
|
+
* worse than showing it.
|
|
28595
|
+
*
|
|
28596
|
+
* `groupId` on the result IS the rule id, so this one read answers both "which
|
|
28597
|
+
* type should the list select?" and "what does the drawer show?".
|
|
28598
|
+
*/
|
|
28599
|
+
findingInstance(id) {
|
|
28600
|
+
const row = this.db.prepare(
|
|
28601
|
+
`SELECT ${FINDING_ROW_COLUMNS_SQL}
|
|
28602
|
+
FROM inspection_findings f
|
|
28603
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
28604
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
28605
|
+
WHERE f.id = ?`
|
|
28606
|
+
).get(id);
|
|
28607
|
+
return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
|
|
28608
|
+
}
|
|
27458
28609
|
/**
|
|
27459
28610
|
* The one statement both instance-level scans run: every finding in scope,
|
|
27460
28611
|
* joined to its event and definition, newest first.
|
|
@@ -27488,17 +28639,7 @@ var SqliteFindingsRepository = class {
|
|
|
27488
28639
|
conditions.push("e.started_at >= ?");
|
|
27489
28640
|
params.push(isoToEpochMillis(scope.from));
|
|
27490
28641
|
}
|
|
27491
|
-
const sql = `SELECT
|
|
27492
|
-
d.severity AS severity, f.masked_match AS masked_match,
|
|
27493
|
-
f.action_taken AS action_taken, f.confidence AS confidence,
|
|
27494
|
-
e.started_at AS occurred_at,
|
|
27495
|
-
e.source_tool AS source_tool,
|
|
27496
|
-
e.repo AS repo,
|
|
27497
|
-
e.file_path AS file,
|
|
27498
|
-
e.tool_name AS tool_name,
|
|
27499
|
-
f.audit_event_id AS event_id, e.root_session_id AS session_id,
|
|
27500
|
-
e.event_type AS kind, f.finding_key AS finding_key,
|
|
27501
|
-
${latestResolutionStatusSql("f")} AS latest_status
|
|
28642
|
+
const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
|
|
27502
28643
|
FROM audit_events e
|
|
27503
28644
|
CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
|
|
27504
28645
|
CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
@@ -27512,6 +28653,26 @@ var SqliteFindingsRepository = class {
|
|
|
27512
28653
|
group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
|
|
27513
28654
|
const rows = this.db.prepare(
|
|
27514
28655
|
`SELECT rule_id,
|
|
28656
|
+
-- BARE columns beside max(latest_at), which is deliberate and
|
|
28657
|
+
-- is SQLite's documented behaviour: with a single min()/max()
|
|
28658
|
+
-- in an aggregate query, every bare column takes its value from
|
|
28659
|
+
-- the row that produced the extremum. So these are the severity
|
|
28660
|
+
-- and category of the definition whose finding is NEWEST, which
|
|
28661
|
+
-- is what the row-based build they replaced read off its first
|
|
28662
|
+
-- (newest-first) row.
|
|
28663
|
+
--
|
|
28664
|
+
-- min() is WRONG here and was the defect: inspection_definitions
|
|
28665
|
+
-- holds one row per rule VERSION (see its writer \u2014 a version bump
|
|
28666
|
+
-- mints a new row), so a rule whose severity moved between
|
|
28667
|
+
-- versions has several, and min() picks the ALPHABETICALLY
|
|
28668
|
+
-- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
|
|
28669
|
+
-- That is arbitrary in direction, and it feeds the badge, the
|
|
28670
|
+
-- filter, the facet counts and the primary sort key.
|
|
28671
|
+
--
|
|
28672
|
+
-- Adding a second min()/max() aggregate here would make these
|
|
28673
|
+
-- bare columns ambiguous again; keep max(latest_at) the only one.
|
|
28674
|
+
severity,
|
|
28675
|
+
category,
|
|
27515
28676
|
sum(tuple_count) AS instance_count,
|
|
27516
28677
|
max(latest_at) AS latest_at,
|
|
27517
28678
|
group_concat(source_tools) AS source_tools,
|
|
@@ -27522,6 +28683,14 @@ var SqliteFindingsRepository = class {
|
|
|
27522
28683
|
group_concat(tool_names) AS tool_names
|
|
27523
28684
|
FROM (
|
|
27524
28685
|
SELECT d.rule_id AS rule_id,
|
|
28686
|
+
-- Severity and category are columns of the DEFINITION, and
|
|
28687
|
+
-- a rule can have SEVERAL definitions (one per version), so
|
|
28688
|
+
-- these are grouped on below and resolved to the newest
|
|
28689
|
+
-- firing version by the outer query's bare-column select.
|
|
28690
|
+
-- They ride the aggregate because the type build has no rows
|
|
28691
|
+
-- to read them off \u2014 see buildFindingTypes.
|
|
28692
|
+
d.severity AS severity,
|
|
28693
|
+
d.category AS category,
|
|
27525
28694
|
e.event_type || '${TUPLE_SEP}' ||
|
|
27526
28695
|
(CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
|
|
27527
28696
|
coalesce(latest.status, '') AS status_tuple,
|
|
@@ -27536,7 +28705,7 @@ var SqliteFindingsRepository = class {
|
|
|
27536
28705
|
LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
|
|
27537
28706
|
ON latest.finding_key = f.finding_key
|
|
27538
28707
|
${scope.predicate}
|
|
27539
|
-
GROUP BY d.rule_id, status_tuple
|
|
28708
|
+
GROUP BY d.rule_id, d.severity, d.category, status_tuple
|
|
27540
28709
|
)
|
|
27541
28710
|
GROUP BY rule_id`
|
|
27542
28711
|
).all(scope.params);
|
|
@@ -27545,6 +28714,8 @@ var SqliteFindingsRepository = class {
|
|
|
27545
28714
|
r.rule_id,
|
|
27546
28715
|
{
|
|
27547
28716
|
instanceCount: r.instance_count,
|
|
28717
|
+
severity: r.severity,
|
|
28718
|
+
category: r.category,
|
|
27548
28719
|
sourceTools: splitConcat(r.source_tools),
|
|
27549
28720
|
actionsTaken: splitConcat(r.actions_taken),
|
|
27550
28721
|
statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
|
|
@@ -27561,7 +28732,7 @@ var SqliteFindingsRepository = class {
|
|
|
27561
28732
|
latestDetectedAt: epochMillisToIso(r.latest_at),
|
|
27562
28733
|
// Free text only — joined and substring-matched, so group_concat's
|
|
27563
28734
|
// commas need no unpicking (a repo/path containing one still matches).
|
|
27564
|
-
// Left undefined (not '') when unfetched, so
|
|
28735
|
+
// Left undefined (not '') when unfetched, so buildFindingTypes can
|
|
27565
28736
|
// tell "no q this request" from "a group with no repo/file at all"
|
|
27566
28737
|
// and skip priming a haystack nothing will read.
|
|
27567
28738
|
...withSearchText ? {
|
|
@@ -27589,7 +28760,9 @@ var SqliteFindingsRepository = class {
|
|
|
27589
28760
|
)
|
|
27590
28761
|
);
|
|
27591
28762
|
for (const row of grouped) {
|
|
27592
|
-
if (
|
|
28763
|
+
if (Object.hasOwn(byAction, row.action_taken)) {
|
|
28764
|
+
byAction[row.action_taken] = row.c;
|
|
28765
|
+
}
|
|
27593
28766
|
}
|
|
27594
28767
|
const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
|
|
27595
28768
|
const sevRows = allRows(
|
|
@@ -27606,7 +28779,9 @@ var SqliteFindingsRepository = class {
|
|
|
27606
28779
|
)
|
|
27607
28780
|
);
|
|
27608
28781
|
for (const row of sevRows) {
|
|
27609
|
-
if (
|
|
28782
|
+
if (Object.hasOwn(bySeverity, row.severity)) {
|
|
28783
|
+
bySeverity[row.severity] = row.c;
|
|
28784
|
+
}
|
|
27610
28785
|
}
|
|
27611
28786
|
const categories = ENFORCEABLE_CATEGORIES;
|
|
27612
28787
|
const enabledRows = allRows(
|
|
@@ -27655,469 +28830,6 @@ function isoDay(ms) {
|
|
|
27655
28830
|
return new Date(ms).toISOString().slice(0, 10);
|
|
27656
28831
|
}
|
|
27657
28832
|
|
|
27658
|
-
// ../../packages/persistence/src/repositories/history-sync.ts
|
|
27659
|
-
var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
|
|
27660
|
-
var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
27661
|
-
var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
|
|
27662
|
-
var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
27663
|
-
var SKIPPED = -1;
|
|
27664
|
-
var ROW_COLUMNS = `id,
|
|
27665
|
-
parent_id AS parentId,
|
|
27666
|
-
root_session_id AS rootSessionId,
|
|
27667
|
-
event_type AS eventType,
|
|
27668
|
-
host_id AS hostId,
|
|
27669
|
-
harness_id AS harnessId,
|
|
27670
|
-
source_project_id AS sourceProjectId,
|
|
27671
|
-
started_at AS startedAt,
|
|
27672
|
-
ended_at AS endedAt,
|
|
27673
|
-
severity,
|
|
27674
|
-
priority,
|
|
27675
|
-
content,
|
|
27676
|
-
content_hash AS contentHash,
|
|
27677
|
-
attributes`;
|
|
27678
|
-
var SqliteHistorySyncRepository = class {
|
|
27679
|
-
constructor(db) {
|
|
27680
|
-
this.db = db;
|
|
27681
|
-
this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
|
|
27682
|
-
this.sessionsStmt = db.prepare(
|
|
27683
|
-
`SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
|
|
27684
|
-
FROM audit_events
|
|
27685
|
-
WHERE synced_at IS NULL
|
|
27686
|
-
AND event_type IN (${TYPE_LIST})
|
|
27687
|
-
AND started_at < :before
|
|
27688
|
-
GROUP BY sessionId
|
|
27689
|
-
ORDER BY earliest
|
|
27690
|
-
LIMIT :limit`
|
|
27691
|
-
);
|
|
27692
|
-
this.rowsStmt = db.prepare(
|
|
27693
|
-
`SELECT ${ROW_COLUMNS}
|
|
27694
|
-
FROM audit_events
|
|
27695
|
-
WHERE synced_at IS NULL
|
|
27696
|
-
AND event_type IN (${TYPE_LIST})
|
|
27697
|
-
AND started_at < :before
|
|
27698
|
-
AND COALESCE(root_session_id, id) = :sessionId
|
|
27699
|
-
ORDER BY (event_type = 'session') DESC, started_at
|
|
27700
|
-
LIMIT :limit`
|
|
27701
|
-
);
|
|
27702
|
-
this.captureRowsStmt = db.prepare(
|
|
27703
|
-
`SELECT ${ROW_COLUMNS}
|
|
27704
|
-
FROM audit_events
|
|
27705
|
-
WHERE synced_at IS NULL
|
|
27706
|
-
AND sync_claimed_at IS NULL
|
|
27707
|
-
AND outbox_owed = 1
|
|
27708
|
-
AND event_type IN (${CAPTURE_TYPE_LIST})
|
|
27709
|
-
AND started_at < :before
|
|
27710
|
-
ORDER BY started_at
|
|
27711
|
-
LIMIT :limit`
|
|
27712
|
-
);
|
|
27713
|
-
this.markOwedStmt = db.prepare(
|
|
27714
|
-
`UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
|
|
27715
|
-
);
|
|
27716
|
-
this.stampStmt = db.prepare(
|
|
27717
|
-
`UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
|
|
27718
|
-
);
|
|
27719
|
-
this.claimRowStmt = db.prepare(
|
|
27720
|
-
`UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
|
|
27721
|
-
);
|
|
27722
|
-
this.releaseRowStmt = db.prepare(
|
|
27723
|
-
`UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
|
|
27724
|
-
);
|
|
27725
|
-
this.releaseStaleClaimsStmt = db.prepare(
|
|
27726
|
-
`UPDATE audit_events SET sync_claimed_at = NULL
|
|
27727
|
-
WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
|
|
27728
|
-
);
|
|
27729
|
-
this.partitionStmt = db.prepare(
|
|
27730
|
-
`SELECT
|
|
27731
|
-
SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
|
|
27732
|
-
SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
|
|
27733
|
-
SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
|
|
27734
|
-
SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
|
|
27735
|
-
COUNT(*) AS total
|
|
27736
|
-
FROM audit_events
|
|
27737
|
-
WHERE event_type IN (${TYPE_LIST})`
|
|
27738
|
-
);
|
|
27739
|
-
this.countsStmt = db.prepare(
|
|
27740
|
-
`SELECT
|
|
27741
|
-
SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
|
|
27742
|
-
SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
|
|
27743
|
-
SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
|
|
27744
|
-
FROM audit_events
|
|
27745
|
-
WHERE event_type IN (${TYPE_LIST})`
|
|
27746
|
-
);
|
|
27747
|
-
this.captureSkipCountStmt = db.prepare(
|
|
27748
|
-
`SELECT COUNT(*) AS skipped
|
|
27749
|
-
FROM audit_events
|
|
27750
|
-
WHERE synced_at = ${String(SKIPPED)}
|
|
27751
|
-
AND event_type IN (${CAPTURE_TYPE_LIST})`
|
|
27752
|
-
);
|
|
27753
|
-
this.fingerprintStmt = db.prepare(
|
|
27754
|
-
`SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
|
|
27755
|
-
FROM history_sync WHERE id = 1`
|
|
27756
|
-
);
|
|
27757
|
-
this.setFingerprintStmt = db.prepare(
|
|
27758
|
-
`UPDATE history_sync
|
|
27759
|
-
SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
|
|
27760
|
-
WHERE id = 1`
|
|
27761
|
-
);
|
|
27762
|
-
this.disownCapturesStmt = db.prepare(
|
|
27763
|
-
`UPDATE audit_events SET outbox_owed = NULL
|
|
27764
|
-
WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
|
|
27765
|
-
);
|
|
27766
|
-
this.rearmStmt = db.prepare(
|
|
27767
|
-
`UPDATE audit_events SET synced_at = NULL
|
|
27768
|
-
WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
|
|
27769
|
-
);
|
|
27770
|
-
this.claimStmt = db.prepare(
|
|
27771
|
-
`UPDATE history_sync
|
|
27772
|
-
SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
|
|
27773
|
-
WHERE id = 1
|
|
27774
|
-
AND (owner_pid IS NULL
|
|
27775
|
-
OR heartbeat_at IS NULL
|
|
27776
|
-
OR heartbeat_at < :staleBefore
|
|
27777
|
-
OR heartbeat_at > :now)`
|
|
27778
|
-
);
|
|
27779
|
-
this.heartbeatStmt = db.prepare(
|
|
27780
|
-
`UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
|
|
27781
|
-
);
|
|
27782
|
-
this.releaseStmt = db.prepare(
|
|
27783
|
-
`UPDATE history_sync
|
|
27784
|
-
SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
|
|
27785
|
-
WHERE id = 1 AND owner_pid = :pid`
|
|
27786
|
-
);
|
|
27787
|
-
this.closeWindowStmt = db.prepare(
|
|
27788
|
-
`UPDATE audit_events SET synced_at = :at
|
|
27789
|
-
WHERE synced_at IS NULL
|
|
27790
|
-
AND event_type IN (${TYPE_LIST})
|
|
27791
|
-
AND started_at >= :attachedAt`
|
|
27792
|
-
);
|
|
27793
|
-
this.releaseBoundaryStmt = db.prepare(
|
|
27794
|
-
`UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
|
|
27795
|
-
);
|
|
27796
|
-
this.freezeBoundaryStmt = db.prepare(
|
|
27797
|
-
`UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
|
|
27798
|
-
);
|
|
27799
|
-
this.leaseStmt = db.prepare(
|
|
27800
|
-
`SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
|
|
27801
|
-
acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
|
|
27802
|
-
FROM history_sync WHERE id = 1`
|
|
27803
|
-
);
|
|
27804
|
-
this.inspectionsStmt = db.prepare(
|
|
27805
|
-
`SELECT d.rule_id AS ruleId,
|
|
27806
|
-
d.name AS ruleName,
|
|
27807
|
-
d.version AS ruleVersion,
|
|
27808
|
-
d.category AS category,
|
|
27809
|
-
d.severity AS severity,
|
|
27810
|
-
f.span_start AS spanStart,
|
|
27811
|
-
f.span_end AS spanEnd,
|
|
27812
|
-
f.masked_match AS maskedMatch,
|
|
27813
|
-
f.action_taken AS actionTaken,
|
|
27814
|
-
f.confidence AS confidence
|
|
27815
|
-
FROM inspection_findings f
|
|
27816
|
-
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
27817
|
-
WHERE f.audit_event_id = :auditEventId
|
|
27818
|
-
ORDER BY f.span_start, f.id`
|
|
27819
|
-
);
|
|
27820
|
-
}
|
|
27821
|
-
db;
|
|
27822
|
-
ensureRowStmt;
|
|
27823
|
-
sessionsStmt;
|
|
27824
|
-
rowsStmt;
|
|
27825
|
-
stampStmt;
|
|
27826
|
-
countsStmt;
|
|
27827
|
-
fingerprintStmt;
|
|
27828
|
-
setFingerprintStmt;
|
|
27829
|
-
rearmStmt;
|
|
27830
|
-
claimStmt;
|
|
27831
|
-
heartbeatStmt;
|
|
27832
|
-
releaseStmt;
|
|
27833
|
-
leaseStmt;
|
|
27834
|
-
inspectionsStmt;
|
|
27835
|
-
closeWindowStmt;
|
|
27836
|
-
releaseBoundaryStmt;
|
|
27837
|
-
freezeBoundaryStmt;
|
|
27838
|
-
captureRowsStmt;
|
|
27839
|
-
markOwedStmt;
|
|
27840
|
-
captureSkipCountStmt;
|
|
27841
|
-
disownCapturesStmt;
|
|
27842
|
-
partitionStmt;
|
|
27843
|
-
claimRowStmt;
|
|
27844
|
-
releaseRowStmt;
|
|
27845
|
-
releaseStaleClaimsStmt;
|
|
27846
|
-
/**
|
|
27847
|
-
* The masked detections recorded against one tool call.
|
|
27848
|
-
*
|
|
27849
|
-
* These travel with the event because a tool call's target is not
|
|
27850
|
-
* re-inspectable from the event alone — unlike a capture, where the text
|
|
27851
|
-
* itself is re-scannable. What crosses is the masked match and the rule that
|
|
27852
|
-
* produced it, never the value.
|
|
27853
|
-
*/
|
|
27854
|
-
inspectionsFor(auditEventId) {
|
|
27855
|
-
return allRows(this.inspectionsStmt, { auditEventId });
|
|
27856
|
-
}
|
|
27857
|
-
/**
|
|
27858
|
-
* Sessions with structural rows still to send, oldest first.
|
|
27859
|
-
*
|
|
27860
|
-
* BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
|
|
27861
|
-
* read. Anything recorded after the machine attached is the live forward
|
|
27862
|
-
* path's to deliver; this drain exists for what was recorded before it, and a
|
|
27863
|
-
* row both paths send is at best a duplicate request and at worst — for a
|
|
27864
|
-
* session root — an overwrite of the inventory ids the live path resolved.
|
|
27865
|
-
*/
|
|
27866
|
-
pendingSessions(limit, before) {
|
|
27867
|
-
return allRows(this.sessionsStmt, { limit, before }).map(
|
|
27868
|
-
(r) => r.sessionId
|
|
27869
|
-
);
|
|
27870
|
-
}
|
|
27871
|
-
/** One session's undelivered structural rows within the backlog, root first. */
|
|
27872
|
-
pendingRows(sessionId, limit, before) {
|
|
27873
|
-
return allRows(this.rowsStmt, { sessionId, limit, before });
|
|
27874
|
-
}
|
|
27875
|
-
/**
|
|
27876
|
-
* Captures this machine still owes the deployment, oldest first.
|
|
27877
|
-
*
|
|
27878
|
-
* Selected by the `outbox_owed` marker the attached forward path writes, not
|
|
27879
|
-
* by a time window — see captureRowsStmt for why a window could not express
|
|
27880
|
-
* this. `before` is the grace window that leaves a just-recorded capture to
|
|
27881
|
-
* the live path.
|
|
27882
|
-
*/
|
|
27883
|
-
pendingCaptureRows(limit, before) {
|
|
27884
|
-
return allRows(this.captureRowsStmt, { limit, before });
|
|
27885
|
-
}
|
|
27886
|
-
/**
|
|
27887
|
-
* Record that a capture is OWED to the deployment.
|
|
27888
|
-
*
|
|
27889
|
-
* Written by the attached forward path when a live send did not confirm
|
|
27890
|
-
* delivery, and read by the drain as the whole of its eligibility test. It is
|
|
27891
|
-
* a fact rather than an inference: the machine was attached, the send did not
|
|
27892
|
-
* land, so the row is owed — which no time window can state, because the same
|
|
27893
|
-
* window that holds the rows a past attachment left owed also holds every
|
|
27894
|
-
* capture recorded while the machine was DETACHED, and those were never
|
|
27895
|
-
* offered to anyone.
|
|
27896
|
-
*
|
|
27897
|
-
* Idempotent, and never un-set: `markSynced` settling the row is what takes it
|
|
27898
|
-
* out of the drain's read.
|
|
27899
|
-
*/
|
|
27900
|
-
markCaptureOwed(id) {
|
|
27901
|
-
this.markOwedStmt.run({ id });
|
|
27902
|
-
}
|
|
27903
|
-
/** Record delivery. Called only AFTER the far side has accepted the rows. */
|
|
27904
|
-
markSynced(ids, atMs) {
|
|
27905
|
-
this.stampAll(ids, atMs);
|
|
27906
|
-
}
|
|
27907
|
-
/**
|
|
27908
|
-
* Record that a row will never be sent.
|
|
27909
|
-
*
|
|
27910
|
-
* Reserved for a local defect — a row that cannot be rebuilt into a valid
|
|
27911
|
-
* payload. A row that merely failed to reach the deployment stays NULL, so it
|
|
27912
|
-
* is retried; marking those would turn one outage into permanent data loss.
|
|
27913
|
-
*/
|
|
27914
|
-
markSkipped(ids) {
|
|
27915
|
-
this.stampAll(ids, SKIPPED);
|
|
27916
|
-
}
|
|
27917
|
-
eachInTransaction(ids, run) {
|
|
27918
|
-
if (ids.length === 0) return;
|
|
27919
|
-
withTransaction(
|
|
27920
|
-
this.db,
|
|
27921
|
-
() => {
|
|
27922
|
-
for (const id of ids) run(id);
|
|
27923
|
-
},
|
|
27924
|
-
"IMMEDIATE"
|
|
27925
|
-
);
|
|
27926
|
-
}
|
|
27927
|
-
stampAll(ids, value) {
|
|
27928
|
-
if (ids.length === 0) return;
|
|
27929
|
-
withTransaction(
|
|
27930
|
-
this.db,
|
|
27931
|
-
() => {
|
|
27932
|
-
for (const id of ids) this.stampStmt.run({ at: value, id });
|
|
27933
|
-
},
|
|
27934
|
-
"IMMEDIATE"
|
|
27935
|
-
);
|
|
27936
|
-
}
|
|
27937
|
-
/**
|
|
27938
|
-
* Claim rows as in-flight.
|
|
27939
|
-
*
|
|
27940
|
-
* Advisory in exactly the sense the lease is: it records that a send is in
|
|
27941
|
-
* progress so a surface can say so, and a lost claim costs a row showing as
|
|
27942
|
-
* queued while it is actually being sent. It is not exclusion — the far side
|
|
27943
|
-
* settles a duplicate on the row id.
|
|
27944
|
-
*/
|
|
27945
|
-
claimRows(ids, atMs) {
|
|
27946
|
-
this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
|
|
27947
|
-
}
|
|
27948
|
-
/** Give back a claim without settling — the send failed, the row is queued again. */
|
|
27949
|
-
releaseRows(ids) {
|
|
27950
|
-
this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
|
|
27951
|
-
}
|
|
27952
|
-
/**
|
|
27953
|
-
* Clear claims older than `staleBefore`, and report how many were cleared.
|
|
27954
|
-
*
|
|
27955
|
-
* A process killed between claiming and settling leaves rows claimed with
|
|
27956
|
-
* nothing left to settle them. Without this they read as "sending" for ever.
|
|
27957
|
-
*/
|
|
27958
|
-
releaseStaleClaims(staleBefore) {
|
|
27959
|
-
return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
|
|
27960
|
-
}
|
|
27961
|
-
/**
|
|
27962
|
-
* Every tracked row in exactly one delivery state.
|
|
27963
|
-
*
|
|
27964
|
-
* Takes no boundary on purpose. The boundary answers "what should the drain
|
|
27965
|
-
* pick up now", which is a different question from "what state is this row
|
|
27966
|
-
* in" — and a machine that has never attached has no boundary to pass, so
|
|
27967
|
-
* requiring one would force a caller to invent one and report the whole store
|
|
27968
|
-
* as queued.
|
|
27969
|
-
*/
|
|
27970
|
-
partition() {
|
|
27971
|
-
const row = getRow(this.partitionStmt, {});
|
|
27972
|
-
return {
|
|
27973
|
-
queued: row?.queued ?? 0,
|
|
27974
|
-
inProgress: row?.inProgress ?? 0,
|
|
27975
|
-
synced: row?.synced ?? 0,
|
|
27976
|
-
failed: row?.failed ?? 0,
|
|
27977
|
-
total: row?.total ?? 0
|
|
27978
|
-
};
|
|
27979
|
-
}
|
|
27980
|
-
/** `pending` counts only what is inside the backlog; sent and skipped are totals. */
|
|
27981
|
-
counts(before) {
|
|
27982
|
-
const row = getRow(
|
|
27983
|
-
this.countsStmt,
|
|
27984
|
-
{ before }
|
|
27985
|
-
);
|
|
27986
|
-
const captures = getRow(this.captureSkipCountStmt);
|
|
27987
|
-
return {
|
|
27988
|
-
pending: row?.pending ?? 0,
|
|
27989
|
-
sent: row?.sent ?? 0,
|
|
27990
|
-
skipped: row?.skipped ?? 0,
|
|
27991
|
-
capturesSkipped: captures?.skipped ?? 0
|
|
27992
|
-
};
|
|
27993
|
-
}
|
|
27994
|
-
/**
|
|
27995
|
-
* The deployment the current stamps were made against, and where its backlog
|
|
27996
|
-
* ends.
|
|
27997
|
-
*
|
|
27998
|
-
* READ-ONLY. An absent row reads as an absent deployment, which is what a
|
|
27999
|
-
* machine that has never drained is — and every writer below seeds the row
|
|
28000
|
-
* before it needs one, so nothing depends on this creating it. Keeping the
|
|
28001
|
-
* write off the gate path matters because the gate runs on every pass while a
|
|
28002
|
-
* write has to take the database's write lock.
|
|
28003
|
-
*/
|
|
28004
|
-
deployment() {
|
|
28005
|
-
const row = getRow(
|
|
28006
|
-
this.fingerprintStmt
|
|
28007
|
-
);
|
|
28008
|
-
return {
|
|
28009
|
-
fingerprint: row?.fingerprint ?? void 0,
|
|
28010
|
-
backlogBefore: row?.backlogBefore ?? void 0
|
|
28011
|
-
};
|
|
28012
|
-
}
|
|
28013
|
-
/**
|
|
28014
|
-
* Point the ledger at a different deployment, discarding what it recorded
|
|
28015
|
-
* about the previous one.
|
|
28016
|
-
*
|
|
28017
|
-
* Delivery is a fact about ONE recipient: rows sent to the deployment a
|
|
28018
|
-
* machine has just left are undelivered as far as the new one is concerned.
|
|
28019
|
-
* All three in one transaction, so a crash between them cannot leave stamps
|
|
28020
|
-
* attributed to the wrong deployment, or a boundary that belongs to another.
|
|
28021
|
-
*
|
|
28022
|
-
* The boundary is written HERE and only here, which is what freezes it: a
|
|
28023
|
-
* re-attach to the SAME deployment (a key rotation) leaves the fingerprint
|
|
28024
|
-
* unchanged, so this never runs and the backlog does not widen back over rows
|
|
28025
|
-
* the live path has since delivered.
|
|
28026
|
-
*/
|
|
28027
|
-
rearmFor(fingerprint, backlogBefore) {
|
|
28028
|
-
this.ensureRowStmt.run();
|
|
28029
|
-
withTransaction(
|
|
28030
|
-
this.db,
|
|
28031
|
-
() => {
|
|
28032
|
-
const previous = getRow(this.fingerprintStmt)?.fingerprint;
|
|
28033
|
-
this.rearmStmt.run();
|
|
28034
|
-
if (previous !== null && previous !== void 0 && previous !== fingerprint) {
|
|
28035
|
-
this.disownCapturesStmt.run();
|
|
28036
|
-
}
|
|
28037
|
-
this.setFingerprintStmt.run({ fingerprint, backlogBefore });
|
|
28038
|
-
},
|
|
28039
|
-
"IMMEDIATE"
|
|
28040
|
-
);
|
|
28041
|
-
}
|
|
28042
|
-
/**
|
|
28043
|
-
* End the attached period: hand its rows to the live path, and release the
|
|
28044
|
-
* boundary so the next attachment can freeze a new one.
|
|
28045
|
-
*
|
|
28046
|
-
* WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
|
|
28047
|
-
* nothing delivers. The fingerprint is unchanged, so the boundary is never
|
|
28048
|
-
* re-frozen and stays at the FIRST attachment — while nothing forwards at all
|
|
28049
|
-
* during the detached period, because the machine is not attached. Rows
|
|
28050
|
-
* recorded in that window sit after the boundary and before the re-attach, so
|
|
28051
|
-
* neither path takes them, and the pending count reports none outstanding.
|
|
28052
|
-
*
|
|
28053
|
-
* Stamping the attached window is not a claim that every one of those rows
|
|
28054
|
-
* reached the deployment — the live path drops on failure and says so
|
|
28055
|
-
* elsewhere. It records that they were ITS to deliver, which is exactly the
|
|
28056
|
-
* status quo: they sit outside the frozen boundary today and are equally never
|
|
28057
|
-
* re-sent. Making it explicit is what lets the boundary move.
|
|
28058
|
-
*
|
|
28059
|
-
* ONE TRANSACTION, so a crash cannot release the boundary while leaving the
|
|
28060
|
-
* window unstamped — that half-state would re-send the whole attached period
|
|
28061
|
-
* on the next attach, which is the failure the boundary exists to prevent.
|
|
28062
|
-
*/
|
|
28063
|
-
closeAttachedWindow(attachedAtMs, atMs) {
|
|
28064
|
-
this.ensureRowStmt.run();
|
|
28065
|
-
withTransaction(
|
|
28066
|
-
this.db,
|
|
28067
|
-
() => {
|
|
28068
|
-
const row = getRow(this.fingerprintStmt);
|
|
28069
|
-
const from = row?.backlogBefore ?? attachedAtMs;
|
|
28070
|
-
this.closeWindowStmt.run({ at: atMs, attachedAt: from });
|
|
28071
|
-
this.releaseBoundaryStmt.run();
|
|
28072
|
-
},
|
|
28073
|
-
"IMMEDIATE"
|
|
28074
|
-
);
|
|
28075
|
-
}
|
|
28076
|
-
/**
|
|
28077
|
-
* Freeze a boundary for the deployment already on file, KEEPING the stamps.
|
|
28078
|
-
*
|
|
28079
|
-
* The re-attach half of the above. Distinct from `rearmFor`, which is for a
|
|
28080
|
-
* different deployment and therefore discards what was delivered to the old
|
|
28081
|
-
* one: here the recipient is the same, so everything already sent to it stays
|
|
28082
|
-
* sent.
|
|
28083
|
-
*/
|
|
28084
|
-
freezeBoundary(backlogBefore) {
|
|
28085
|
-
this.ensureRowStmt.run();
|
|
28086
|
-
this.freezeBoundaryStmt.run({ backlogBefore });
|
|
28087
|
-
}
|
|
28088
|
-
/** Take the claim, or report that someone live already holds it. */
|
|
28089
|
-
claim(pid, host, nowMs, staleAfterMs) {
|
|
28090
|
-
this.ensureRowStmt.run();
|
|
28091
|
-
let taken = false;
|
|
28092
|
-
withTransaction(
|
|
28093
|
-
this.db,
|
|
28094
|
-
() => {
|
|
28095
|
-
const result = this.claimStmt.run({
|
|
28096
|
-
pid,
|
|
28097
|
-
host,
|
|
28098
|
-
now: nowMs,
|
|
28099
|
-
staleBefore: nowMs - staleAfterMs
|
|
28100
|
-
});
|
|
28101
|
-
taken = result.changes === 1;
|
|
28102
|
-
},
|
|
28103
|
-
"IMMEDIATE"
|
|
28104
|
-
);
|
|
28105
|
-
return taken;
|
|
28106
|
-
}
|
|
28107
|
-
/** Say the holder is still alive. A no-op once the claim has moved on. */
|
|
28108
|
-
heartbeat(pid, nowMs) {
|
|
28109
|
-
this.heartbeatStmt.run({ now: nowMs, pid });
|
|
28110
|
-
}
|
|
28111
|
-
/** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
|
|
28112
|
-
release(pid) {
|
|
28113
|
-
this.releaseStmt.run({ pid });
|
|
28114
|
-
}
|
|
28115
|
-
/** Who holds the claim, if anyone. Read-only, for the same reason as above. */
|
|
28116
|
-
lease() {
|
|
28117
|
-
return getRow(this.leaseStmt);
|
|
28118
|
-
}
|
|
28119
|
-
};
|
|
28120
|
-
|
|
28121
28833
|
// ../../packages/persistence/src/repositories/inspection-definitions.ts
|
|
28122
28834
|
var SqliteInspectionDefinitionsRepository = class {
|
|
28123
28835
|
constructor(db) {
|
|
@@ -28312,7 +29024,8 @@ function managedSettingsPaths(platform2 = process.platform) {
|
|
|
28312
29024
|
}
|
|
28313
29025
|
return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
|
|
28314
29026
|
}
|
|
28315
|
-
|
|
29027
|
+
var testOnlyManagedPaths = null;
|
|
29028
|
+
function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
|
|
28316
29029
|
for (const path of paths) {
|
|
28317
29030
|
let text;
|
|
28318
29031
|
try {
|
|
@@ -28347,6 +29060,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
|
|
|
28347
29060
|
if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
|
|
28348
29061
|
if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
|
|
28349
29062
|
if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
|
|
29063
|
+
if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
|
|
28350
29064
|
if (values.vaultConsent !== void 0) {
|
|
28351
29065
|
merged.vaultConsent = values.vaultConsent ? (
|
|
28352
29066
|
// Keep an existing valid grant so its acknowledgedAt survives; mint one
|
|
@@ -30792,7 +31506,7 @@ function toUtcDateString(ms) {
|
|
|
30792
31506
|
return new Date(ms).toISOString().slice(0, 10);
|
|
30793
31507
|
}
|
|
30794
31508
|
function isTimeseriesSeverity(s) {
|
|
30795
|
-
return s === "critical" || s === "high" || s === "medium";
|
|
31509
|
+
return s === "critical" || s === "high" || s === "medium" || s === "low";
|
|
30796
31510
|
}
|
|
30797
31511
|
var SqliteSecurityRepository = class {
|
|
30798
31512
|
constructor(db, now = () => Date.now()) {
|
|
@@ -30854,7 +31568,7 @@ var SqliteSecurityRepository = class {
|
|
|
30854
31568
|
ELSE 0
|
|
30855
31569
|
END) AS open_at_rest
|
|
30856
31570
|
FROM inspection_findings f
|
|
30857
|
-
JOIN audit_events e ON e.id = f.audit_event_id
|
|
31571
|
+
JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
|
|
30858
31572
|
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
30859
31573
|
LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
|
|
30860
31574
|
ON latest.finding_key = f.finding_key
|
|
@@ -30921,12 +31635,16 @@ var SqliteSecurityRepository = class {
|
|
|
30921
31635
|
const now = this.now();
|
|
30922
31636
|
const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
|
|
30923
31637
|
const rows = this.findingsInRange(windowStart, now);
|
|
30924
|
-
const points = Array.from(
|
|
30925
|
-
|
|
30926
|
-
|
|
30927
|
-
|
|
30928
|
-
|
|
30929
|
-
|
|
31638
|
+
const points = Array.from(
|
|
31639
|
+
{ length: numBuckets },
|
|
31640
|
+
(_, i) => ({
|
|
31641
|
+
timestamp: toUtcDateString(windowStart + i * bucketMs),
|
|
31642
|
+
critical: 0,
|
|
31643
|
+
high: 0,
|
|
31644
|
+
medium: 0,
|
|
31645
|
+
low: 0
|
|
31646
|
+
})
|
|
31647
|
+
);
|
|
30930
31648
|
for (const r of rows) {
|
|
30931
31649
|
const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
|
|
30932
31650
|
const bucket = points[idx];
|
|
@@ -31076,7 +31794,7 @@ var SqliteSecurityRepository = class {
|
|
|
31076
31794
|
this.db.prepare(
|
|
31077
31795
|
`SELECT e.repo AS repo, count(*) AS c
|
|
31078
31796
|
FROM inspection_findings f
|
|
31079
|
-
JOIN audit_events e ON e.id = f.audit_event_id
|
|
31797
|
+
JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
|
|
31080
31798
|
WHERE e.started_at >= :from AND e.started_at < :to
|
|
31081
31799
|
AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
|
|
31082
31800
|
AND e.repo IS NOT NULL
|
|
@@ -31144,6 +31862,7 @@ var SqliteSecurityRepository = class {
|
|
|
31144
31862
|
`SELECT f.finding_key AS finding_key,
|
|
31145
31863
|
d.rule_id AS rule_id,
|
|
31146
31864
|
d.severity AS severity,
|
|
31865
|
+
e.repo AS repo,
|
|
31147
31866
|
e.file_path AS path,
|
|
31148
31867
|
COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
|
|
31149
31868
|
latest.resolved_at AS latest_resolved_at
|
|
@@ -31163,6 +31882,7 @@ var SqliteSecurityRepository = class {
|
|
|
31163
31882
|
const items = rows.map((r) => ({
|
|
31164
31883
|
findingKey: r.finding_key,
|
|
31165
31884
|
ruleId: r.rule_id,
|
|
31885
|
+
repo: r.repo ?? "",
|
|
31166
31886
|
severity: r.severity,
|
|
31167
31887
|
path: r.path ?? "",
|
|
31168
31888
|
resolvedAt: new Date(r.latest_resolved_at).toISOString(),
|
|
@@ -31172,15 +31892,68 @@ var SqliteSecurityRepository = class {
|
|
|
31172
31892
|
}));
|
|
31173
31893
|
return Promise.resolve({ items });
|
|
31174
31894
|
}
|
|
31895
|
+
/**
|
|
31896
|
+
* Per-rule tallies of the findings that are still OPEN, whole-store.
|
|
31897
|
+
*
|
|
31898
|
+
* Scoped by status rather than by time, because the card this feeds is a to-do
|
|
31899
|
+
* list: a secret committed three weeks ago and never rotated is still the most
|
|
31900
|
+
* important thing to fix, and any window hides it. It carried a "newest N
|
|
31901
|
+
* findings" cap and then a range; the first meant a different span on every
|
|
31902
|
+
* machine, and the second reported "no recommendations" over live exposure.
|
|
31903
|
+
*
|
|
31904
|
+
* `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
|
|
31905
|
+
* so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
|
|
31906
|
+
* is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
|
|
31907
|
+
* dismissal is a judgement, not a remediation) and drops untracked legacy rows.
|
|
31908
|
+
* The two answer different questions and only this one has to match a link.
|
|
31909
|
+
*
|
|
31910
|
+
* Aggregated in SQL: the result is O(distinct rule × category × severity), so a
|
|
31911
|
+
* whole-store scope costs a grouped scan rather than a row per finding.
|
|
31912
|
+
*/
|
|
31913
|
+
recommendationInputs() {
|
|
31914
|
+
const rows = allRows(
|
|
31915
|
+
this.db.prepare(
|
|
31916
|
+
`SELECT d.rule_id AS rule_id,
|
|
31917
|
+
d.category AS category,
|
|
31918
|
+
d.severity AS severity,
|
|
31919
|
+
COUNT(*) AS count
|
|
31920
|
+
FROM inspection_findings f
|
|
31921
|
+
JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
|
|
31922
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
31923
|
+
LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
|
|
31924
|
+
ON latest.finding_key = f.finding_key
|
|
31925
|
+
WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
|
|
31926
|
+
AND e.event_type = 'code_change'
|
|
31927
|
+
AND (
|
|
31928
|
+
f.finding_key IS NULL
|
|
31929
|
+
OR latest.status IS NULL
|
|
31930
|
+
OR latest.status NOT IN ('resolved', 'dismissed')
|
|
31931
|
+
)
|
|
31932
|
+
GROUP BY d.rule_id, d.category, d.severity`
|
|
31933
|
+
)
|
|
31934
|
+
);
|
|
31935
|
+
return Promise.resolve(
|
|
31936
|
+
rows.map((r) => ({
|
|
31937
|
+
ruleId: r.rule_id,
|
|
31938
|
+
category: r.category,
|
|
31939
|
+
severity: r.severity,
|
|
31940
|
+
count: r.count
|
|
31941
|
+
}))
|
|
31942
|
+
);
|
|
31943
|
+
}
|
|
31175
31944
|
// Findings whose parent event occurred in [fromMs, toMs), with the parent's
|
|
31176
31945
|
// epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
|
|
31177
31946
|
// numeric and the JS aggregations bucket/split on ms directly.
|
|
31178
31947
|
findingsInRange(fromMs, toMs) {
|
|
31179
31948
|
const rows = allRows(
|
|
31180
31949
|
this.db.prepare(
|
|
31181
|
-
`
|
|
31950
|
+
// `rule_id`/`category` cost nothing extra: inspection_definitions is already
|
|
31951
|
+
// joined for `severity`, so they are two more columns off a row this read
|
|
31952
|
+
// already fetches. They feed the recommended-actions rollup.
|
|
31953
|
+
`SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
|
|
31954
|
+
d.rule_id AS rule_id, d.category AS category
|
|
31182
31955
|
FROM inspection_findings f
|
|
31183
|
-
JOIN audit_events e ON e.id = f.audit_event_id
|
|
31956
|
+
JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
|
|
31184
31957
|
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
31185
31958
|
WHERE e.started_at >= :from AND e.started_at < :to
|
|
31186
31959
|
AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
|
|
@@ -31191,7 +31964,9 @@ var SqliteSecurityRepository = class {
|
|
|
31191
31964
|
return rows.map((r) => ({
|
|
31192
31965
|
occurredAt: r.occurred_at,
|
|
31193
31966
|
severity: r.severity,
|
|
31194
|
-
actionTaken: r.action_taken
|
|
31967
|
+
actionTaken: r.action_taken,
|
|
31968
|
+
ruleId: r.rule_id,
|
|
31969
|
+
category: r.category
|
|
31195
31970
|
}));
|
|
31196
31971
|
}
|
|
31197
31972
|
};
|
|
@@ -32019,6 +32794,7 @@ function openWithPragmas(file2) {
|
|
|
32019
32794
|
db.exec("PRAGMA journal_mode = WAL");
|
|
32020
32795
|
db.exec("PRAGMA busy_timeout = 2000");
|
|
32021
32796
|
db.exec("PRAGMA foreign_keys = ON");
|
|
32797
|
+
registerSqlFunctions(db);
|
|
32022
32798
|
} catch (err) {
|
|
32023
32799
|
closeQuietly(db);
|
|
32024
32800
|
throw err;
|
|
@@ -32048,7 +32824,7 @@ function backupLegacyStore(db, file2) {
|
|
|
32048
32824
|
discardStore(file2, backup);
|
|
32049
32825
|
return backup;
|
|
32050
32826
|
}
|
|
32051
|
-
function openAndInitialize(file2, base) {
|
|
32827
|
+
function openAndInitialize(file2, base, skipTags) {
|
|
32052
32828
|
let db = openWithPragmas(file2);
|
|
32053
32829
|
try {
|
|
32054
32830
|
if (isForeignSqliteLineage(db)) {
|
|
@@ -32058,7 +32834,7 @@ function openAndInitialize(file2, base) {
|
|
|
32058
32834
|
`Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
|
|
32059
32835
|
);
|
|
32060
32836
|
}
|
|
32061
|
-
applyMigrations(db, file2);
|
|
32837
|
+
applyMigrations(db, file2, { skipTags });
|
|
32062
32838
|
tightenPerms(file2);
|
|
32063
32839
|
const policies = new SqlitePoliciesRepository(db);
|
|
32064
32840
|
const installedPacks = new SqliteInstalledPacksRepository(db, base);
|
|
@@ -32073,6 +32849,7 @@ function openAndInitialize(file2, base) {
|
|
|
32073
32849
|
exceptions: new SqliteExceptionsRepository(db),
|
|
32074
32850
|
resolutions: new SqliteResolutionsRepository(db),
|
|
32075
32851
|
ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
|
|
32852
|
+
bodyRetention: new SqliteBodyRetentionRepository(db),
|
|
32076
32853
|
security: new SqliteSecurityRepository(db),
|
|
32077
32854
|
detections: new SqliteDetectionsRepository(db),
|
|
32078
32855
|
shares: new SqliteSharesRepository(db),
|
|
@@ -32095,7 +32872,8 @@ function openAndInitialize(file2, base) {
|
|
|
32095
32872
|
throw err;
|
|
32096
32873
|
}
|
|
32097
32874
|
}
|
|
32098
|
-
|
|
32875
|
+
var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
|
|
32876
|
+
function openLocalDatabase(dir, options = {}) {
|
|
32099
32877
|
ensureDataDirSync(dir);
|
|
32100
32878
|
const file2 = join7(dir, DB_FILENAME);
|
|
32101
32879
|
reapStalePartials(file2);
|
|
@@ -32107,6 +32885,7 @@ function openLocalDatabase(dir) {
|
|
|
32107
32885
|
installedPacks,
|
|
32108
32886
|
scanLedger,
|
|
32109
32887
|
historySync,
|
|
32888
|
+
bodyRetention,
|
|
32110
32889
|
secretVault,
|
|
32111
32890
|
exceptions,
|
|
32112
32891
|
resolutions,
|
|
@@ -32130,7 +32909,8 @@ function openLocalDatabase(dir) {
|
|
|
32130
32909
|
// `dir` is always `<base>/data` — every caller resolves it through
|
|
32131
32910
|
// `dataDir()` — so its parent is the `~/.aka` base the layout splits into
|
|
32132
32911
|
// settings/ and data/, and the pack-policy floor needs both halves.
|
|
32133
|
-
dirname2(dir)
|
|
32912
|
+
dirname2(dir),
|
|
32913
|
+
options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
|
|
32134
32914
|
);
|
|
32135
32915
|
function captureRowId(event) {
|
|
32136
32916
|
return captureId(
|
|
@@ -32323,6 +33103,7 @@ function openLocalDatabase(dir) {
|
|
|
32323
33103
|
installedPacks,
|
|
32324
33104
|
scanLedger,
|
|
32325
33105
|
historySync,
|
|
33106
|
+
bodyRetention,
|
|
32326
33107
|
secretVault,
|
|
32327
33108
|
exceptions,
|
|
32328
33109
|
resolutions,
|
|
@@ -32361,6 +33142,70 @@ function openLocalDatabase(dir) {
|
|
|
32361
33142
|
};
|
|
32362
33143
|
}
|
|
32363
33144
|
|
|
33145
|
+
// ../../packages/persistence/src/egress-wire.ts
|
|
33146
|
+
import { createHash as createHash3 } from "crypto";
|
|
33147
|
+
var PROJECT_KEY_DIGEST_VERSION = "v2";
|
|
33148
|
+
var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
|
|
33149
|
+
var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
|
|
33150
|
+
var FILE_URL = /^file:\/\//i;
|
|
33151
|
+
var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
|
|
33152
|
+
var SLASH = "/".charCodeAt(0);
|
|
33153
|
+
var GIT_SUFFIX = ".git";
|
|
33154
|
+
function trimSlashes(path) {
|
|
33155
|
+
let start = 0;
|
|
33156
|
+
let end = path.length;
|
|
33157
|
+
while (start < end && path.charCodeAt(start) === SLASH) start += 1;
|
|
33158
|
+
while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
|
|
33159
|
+
return path.slice(start, end);
|
|
33160
|
+
}
|
|
33161
|
+
function canonicalGitUrl(url2) {
|
|
33162
|
+
const trimmed = url2.trim();
|
|
33163
|
+
if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
|
|
33164
|
+
const scheme = SCHEME_FORM.exec(trimmed);
|
|
33165
|
+
const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
|
|
33166
|
+
const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
|
|
33167
|
+
if (host === void 0) return trimmed;
|
|
33168
|
+
const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
|
|
33169
|
+
const bare = trimSlashes(path);
|
|
33170
|
+
const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
|
|
33171
|
+
return cleaned === "" ? host : `${host}/${cleaned}`;
|
|
33172
|
+
}
|
|
33173
|
+
function hashProjectKey(projectKey) {
|
|
33174
|
+
const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
|
|
33175
|
+
return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
|
|
33176
|
+
}
|
|
33177
|
+
function toIngestHit(hit) {
|
|
33178
|
+
return {
|
|
33179
|
+
host: hit.host,
|
|
33180
|
+
kind: hit.kind,
|
|
33181
|
+
name: hit.name,
|
|
33182
|
+
category: hit.category,
|
|
33183
|
+
trust: hit.trust,
|
|
33184
|
+
network: hit.network,
|
|
33185
|
+
method: hit.method,
|
|
33186
|
+
transport: hit.transport,
|
|
33187
|
+
url: hit.url,
|
|
33188
|
+
template: hit.template,
|
|
33189
|
+
dataClass: hit.dataClass,
|
|
33190
|
+
site: {
|
|
33191
|
+
file: hit.site.file,
|
|
33192
|
+
line: hit.site.line,
|
|
33193
|
+
dynamic: hit.site.dynamic,
|
|
33194
|
+
vendored: hit.site.vendored
|
|
33195
|
+
}
|
|
33196
|
+
};
|
|
33197
|
+
}
|
|
33198
|
+
function toEgressIngestRequest(input2) {
|
|
33199
|
+
const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
|
|
33200
|
+
const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
|
|
33201
|
+
return {
|
|
33202
|
+
projectKey: hashProjectKey(input2.projectKey),
|
|
33203
|
+
project: input2.project,
|
|
33204
|
+
reconcile,
|
|
33205
|
+
hits: hits.map(toIngestHit)
|
|
33206
|
+
};
|
|
33207
|
+
}
|
|
33208
|
+
|
|
32364
33209
|
// ../../packages/persistence/src/exception-policy.ts
|
|
32365
33210
|
var UserGrantPolicyProvider = class {
|
|
32366
33211
|
#exceptions;
|
|
@@ -32382,13 +33227,13 @@ var UserGrantPolicyProvider = class {
|
|
|
32382
33227
|
};
|
|
32383
33228
|
|
|
32384
33229
|
// ../../packages/persistence/src/finding-key.ts
|
|
32385
|
-
import { createHash as
|
|
33230
|
+
import { createHash as createHash4 } from "crypto";
|
|
32386
33231
|
function normalizeFilePath(filePath) {
|
|
32387
33232
|
return filePath.replaceAll("\\", "/");
|
|
32388
33233
|
}
|
|
32389
33234
|
function computeFindingKey(input2) {
|
|
32390
33235
|
const normalizedPath = normalizeFilePath(input2.filePath);
|
|
32391
|
-
return
|
|
33236
|
+
return createHash4("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
|
|
32392
33237
|
}
|
|
32393
33238
|
|
|
32394
33239
|
// ../../packages/persistence/src/fingerprint.ts
|
|
@@ -32514,14 +33359,50 @@ function fingerprintValue(key, raw) {
|
|
|
32514
33359
|
return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
|
|
32515
33360
|
}
|
|
32516
33361
|
|
|
32517
|
-
// ../../packages/persistence/src/
|
|
32518
|
-
import {
|
|
33362
|
+
// ../../packages/persistence/src/forward-health.ts
|
|
33363
|
+
import { readFileSync as readFileSync7 } from "fs";
|
|
32519
33364
|
import { join as join9 } from "path";
|
|
33365
|
+
var FAILURES = /* @__PURE__ */ new Set([
|
|
33366
|
+
"unauthorized",
|
|
33367
|
+
"forbidden",
|
|
33368
|
+
"unreachable"
|
|
33369
|
+
]);
|
|
33370
|
+
var BREAKER_COOLDOWN_MS = 3e4;
|
|
33371
|
+
function parseForwardHealth(raw, nowMs) {
|
|
33372
|
+
try {
|
|
33373
|
+
const parsed2 = JSON.parse(raw);
|
|
33374
|
+
if (typeof parsed2 !== "object" || parsed2 === null) return null;
|
|
33375
|
+
const record2 = parsed2;
|
|
33376
|
+
const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
|
|
33377
|
+
const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
|
|
33378
|
+
const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
|
|
33379
|
+
return { consecutiveFailures: failures, openedAtMs, lastFailure };
|
|
33380
|
+
} catch {
|
|
33381
|
+
return null;
|
|
33382
|
+
}
|
|
33383
|
+
}
|
|
33384
|
+
function isForwardPaused(health, nowMs) {
|
|
33385
|
+
const openedAtMs = health?.openedAtMs ?? null;
|
|
33386
|
+
if (openedAtMs === null) return false;
|
|
33387
|
+
return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
|
|
33388
|
+
}
|
|
33389
|
+
|
|
33390
|
+
// ../../packages/persistence/src/history-backfill.ts
|
|
33391
|
+
import { existsSync as existsSync4 } from "fs";
|
|
33392
|
+
import { join as join10 } from "path";
|
|
33393
|
+
|
|
33394
|
+
// ../../packages/persistence/src/history-preview.ts
|
|
33395
|
+
import { existsSync as existsSync5 } from "fs";
|
|
33396
|
+
import { join as join11 } from "path";
|
|
32520
33397
|
import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
|
|
32521
33398
|
|
|
33399
|
+
// ../../packages/persistence/src/history-sync-state.ts
|
|
33400
|
+
import { readFileSync as readFileSync8 } from "fs";
|
|
33401
|
+
import { join as join12 } from "path";
|
|
33402
|
+
|
|
32522
33403
|
// ../../packages/persistence/src/store-symlinks.ts
|
|
32523
|
-
import { existsSync as
|
|
32524
|
-
import { dirname as dirname3, join as
|
|
33404
|
+
import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
|
|
33405
|
+
import { dirname as dirname3, join as join13, resolve } from "path";
|
|
32525
33406
|
var STORE_DB = "the store database (including the prompt corpus)";
|
|
32526
33407
|
var STORE_SETTINGS = "your settings file";
|
|
32527
33408
|
function storeContents(home) {
|
|
@@ -32530,7 +33411,7 @@ function storeContents(home) {
|
|
|
32530
33411
|
[settingsDir(home), STORE_SETTINGS],
|
|
32531
33412
|
[dataDir(home), STORE_DB],
|
|
32532
33413
|
[keysDir(home), "the vault key"],
|
|
32533
|
-
[
|
|
33414
|
+
[join13(settingsDir(home), "settings.json"), STORE_SETTINGS],
|
|
32534
33415
|
[dbPath(home), STORE_DB]
|
|
32535
33416
|
]);
|
|
32536
33417
|
}
|
|
@@ -32545,7 +33426,7 @@ function symlinkedStorePaths(home, platform2 = process.platform) {
|
|
|
32545
33426
|
holds,
|
|
32546
33427
|
// existsSync follows the link, so a target that is gone reads as
|
|
32547
33428
|
// absent here while lstat above still sees the link itself.
|
|
32548
|
-
missing: !
|
|
33429
|
+
missing: !existsSync6(path),
|
|
32549
33430
|
mode: targetMode(path, platform2)
|
|
32550
33431
|
}
|
|
32551
33432
|
];
|
|
@@ -32681,8 +33562,8 @@ function formatPointer(category, keyVersion, pointerId, tag) {
|
|
|
32681
33562
|
// ../../packages/persistence/src/vault/key-provider.ts
|
|
32682
33563
|
import { execFileSync } from "child_process";
|
|
32683
33564
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
32684
|
-
import { chmodSync as chmodSync3, readFileSync as
|
|
32685
|
-
import { join as
|
|
33565
|
+
import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
|
|
33566
|
+
import { join as join14 } from "path";
|
|
32686
33567
|
var VAULT_OCCUPANT_REASON = {
|
|
32687
33568
|
symlink: "the path is a symlink; remove it so a keyring can be created",
|
|
32688
33569
|
gone: "the path was occupied but holds no keyring (removed while it was being created)",
|
|
@@ -32781,7 +33662,7 @@ function claimRotationLock(lock, owner) {
|
|
|
32781
33662
|
throw asError(err);
|
|
32782
33663
|
}
|
|
32783
33664
|
try {
|
|
32784
|
-
writeFileSync3(
|
|
33665
|
+
writeFileSync3(join14(lock, LOCK_OWNER_FILE), `${owner}
|
|
32785
33666
|
`, { mode: DATA_FILE_MODE });
|
|
32786
33667
|
return true;
|
|
32787
33668
|
} catch (err) {
|
|
@@ -32790,7 +33671,7 @@ function claimRotationLock(lock, owner) {
|
|
|
32790
33671
|
}
|
|
32791
33672
|
}
|
|
32792
33673
|
function acquireRotationLock(keysDir2) {
|
|
32793
|
-
const lock =
|
|
33674
|
+
const lock = join14(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
|
|
32794
33675
|
const owner = randomBytes2(16).toString("hex");
|
|
32795
33676
|
if (claimRotationLock(lock, owner)) return { lock, owner };
|
|
32796
33677
|
let held;
|
|
@@ -32817,7 +33698,7 @@ function acquireRotationLock(keysDir2) {
|
|
|
32817
33698
|
}
|
|
32818
33699
|
function releaseRotationLock(lease) {
|
|
32819
33700
|
try {
|
|
32820
|
-
if (
|
|
33701
|
+
if (readFileSync9(join14(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
|
|
32821
33702
|
} catch {
|
|
32822
33703
|
return;
|
|
32823
33704
|
}
|
|
@@ -32838,7 +33719,7 @@ var FileKeyProvider = class {
|
|
|
32838
33719
|
this.#keysDir = keysDir2;
|
|
32839
33720
|
}
|
|
32840
33721
|
get filePath() {
|
|
32841
|
-
return
|
|
33722
|
+
return join14(this.#keysDir, VAULT_KEY_FILENAME);
|
|
32842
33723
|
}
|
|
32843
33724
|
loadOrCreate() {
|
|
32844
33725
|
return asAsync(() => {
|
|
@@ -32868,7 +33749,7 @@ var FileKeyProvider = class {
|
|
|
32868
33749
|
#read() {
|
|
32869
33750
|
let raw;
|
|
32870
33751
|
try {
|
|
32871
|
-
raw =
|
|
33752
|
+
raw = readFileSync9(this.filePath, "utf8");
|
|
32872
33753
|
} catch (err) {
|
|
32873
33754
|
if (err.code === "ENOENT") return null;
|
|
32874
33755
|
throw err instanceof Error ? err : new Error(String(err));
|
|
@@ -33503,13 +34384,13 @@ var SecretVault = class {
|
|
|
33503
34384
|
};
|
|
33504
34385
|
|
|
33505
34386
|
// ../../packages/persistence/src/warn-era-cap.ts
|
|
33506
|
-
import { existsSync as
|
|
33507
|
-
import { join as
|
|
34387
|
+
import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
|
|
34388
|
+
import { join as join15 } from "path";
|
|
33508
34389
|
var MARKER = "warn-era-capped";
|
|
33509
34390
|
function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
|
|
33510
34391
|
if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
|
|
33511
|
-
const marker =
|
|
33512
|
-
if (
|
|
34392
|
+
const marker = join15(dataDir2, MARKER);
|
|
34393
|
+
if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
|
|
33513
34394
|
const capped = db.policies.capCategoryActions();
|
|
33514
34395
|
writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
|
|
33515
34396
|
`, { mode: DATA_FILE_MODE });
|
|
@@ -33568,8 +34449,8 @@ function resolveProvider() {
|
|
|
33568
34449
|
function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
|
|
33569
34450
|
try {
|
|
33570
34451
|
ensureLayoutDirSync(base);
|
|
33571
|
-
const settingsFile =
|
|
33572
|
-
if (
|
|
34452
|
+
const settingsFile = join16(settingsDir(base), "settings.json");
|
|
34453
|
+
if (existsSync8(settingsFile)) tightenFile(settingsFile);
|
|
33573
34454
|
} catch {
|
|
33574
34455
|
}
|
|
33575
34456
|
migrateLegacyLayout(base);
|
|
@@ -33592,9 +34473,9 @@ function resolveProviderSafe(resolveProviderFn) {
|
|
|
33592
34473
|
}
|
|
33593
34474
|
|
|
33594
34475
|
// ../../packages/plugin-sdk/src/config-inventory.ts
|
|
33595
|
-
import { readdirSync as readdirSync2, readFileSync as
|
|
34476
|
+
import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
|
|
33596
34477
|
import { homedir as homedir2 } from "os";
|
|
33597
|
-
import { basename as basename3, join as
|
|
34478
|
+
import { basename as basename3, join as join18 } from "path";
|
|
33598
34479
|
|
|
33599
34480
|
// ../../packages/detections/src/egress/registry.ts
|
|
33600
34481
|
var EXTRACTOR_VERSION = "1";
|
|
@@ -36686,8 +37567,8 @@ function uniqueRuleIds(findings) {
|
|
|
36686
37567
|
}
|
|
36687
37568
|
|
|
36688
37569
|
// ../../packages/plugin-sdk/src/repo.ts
|
|
36689
|
-
import { existsSync as
|
|
36690
|
-
import { basename as basename2, dirname as dirname4, isAbsolute, join as
|
|
37570
|
+
import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
|
|
37571
|
+
import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
|
|
36691
37572
|
function resolveRepo(cwd) {
|
|
36692
37573
|
try {
|
|
36693
37574
|
const root = findGitRoot(cwd);
|
|
@@ -36702,36 +37583,36 @@ function resolveRepo(cwd) {
|
|
|
36702
37583
|
function findGitRoot(start) {
|
|
36703
37584
|
let dir = start;
|
|
36704
37585
|
for (; ; ) {
|
|
36705
|
-
if (
|
|
37586
|
+
if (existsSync9(join17(dir, ".git"))) return dir;
|
|
36706
37587
|
const parent = dirname4(dir);
|
|
36707
37588
|
if (parent === dir) return void 0;
|
|
36708
37589
|
dir = parent;
|
|
36709
37590
|
}
|
|
36710
37591
|
}
|
|
36711
37592
|
function resolveGitContext(root) {
|
|
36712
|
-
const dotGit =
|
|
37593
|
+
const dotGit = join17(root, ".git");
|
|
36713
37594
|
try {
|
|
36714
37595
|
if (statSync6(dotGit).isDirectory()) {
|
|
36715
|
-
return { configPath:
|
|
37596
|
+
return { configPath: join17(dotGit, "config"), headRoot: root };
|
|
36716
37597
|
}
|
|
36717
37598
|
} catch {
|
|
36718
37599
|
return void 0;
|
|
36719
37600
|
}
|
|
36720
37601
|
const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
|
|
36721
37602
|
if (!target) return void 0;
|
|
36722
|
-
const gitdir = isAbsolute(target) ? target :
|
|
36723
|
-
if (
|
|
36724
|
-
return { configPath:
|
|
37603
|
+
const gitdir = isAbsolute(target) ? target : join17(root, target);
|
|
37604
|
+
if (existsSync9(join17(gitdir, "config"))) {
|
|
37605
|
+
return { configPath: join17(gitdir, "config"), headRoot: root };
|
|
36725
37606
|
}
|
|
36726
|
-
const commonRaw = safeRead(
|
|
37607
|
+
const commonRaw = safeRead(join17(gitdir, "commondir"))?.trim();
|
|
36727
37608
|
if (!commonRaw) return void 0;
|
|
36728
|
-
const commonGitDir = isAbsolute(commonRaw) ? commonRaw :
|
|
37609
|
+
const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join17(gitdir, commonRaw);
|
|
36729
37610
|
const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
|
|
36730
|
-
return { configPath:
|
|
37611
|
+
return { configPath: join17(commonGitDir, "config"), headRoot };
|
|
36731
37612
|
}
|
|
36732
37613
|
function safeRead(path) {
|
|
36733
37614
|
try {
|
|
36734
|
-
return
|
|
37615
|
+
return readFileSync10(path, "utf8");
|
|
36735
37616
|
} catch {
|
|
36736
37617
|
return void 0;
|
|
36737
37618
|
}
|
|
@@ -36769,9 +37650,9 @@ function slugFromUrl(url2) {
|
|
|
36769
37650
|
}
|
|
36770
37651
|
|
|
36771
37652
|
// ../../packages/plugin-sdk/src/events.ts
|
|
36772
|
-
import { createHash as
|
|
37653
|
+
import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
|
|
36773
37654
|
function contentHashOf(text) {
|
|
36774
|
-
return
|
|
37655
|
+
return createHash5("sha256").update(text).digest("hex");
|
|
36775
37656
|
}
|
|
36776
37657
|
function buildIngestEvent(input2) {
|
|
36777
37658
|
const contentHash = input2.contentHash ?? contentHashOf(input2.content);
|
|
@@ -36797,7 +37678,7 @@ function buildIngestEvent(input2) {
|
|
|
36797
37678
|
}
|
|
36798
37679
|
|
|
36799
37680
|
// ../../packages/plugin-sdk/src/isolated-scan.ts
|
|
36800
|
-
import { existsSync as
|
|
37681
|
+
import { existsSync as existsSync10 } from "fs";
|
|
36801
37682
|
import { fileURLToPath } from "url";
|
|
36802
37683
|
import { Worker } from "worker_threads";
|
|
36803
37684
|
var ISOLATED_SCAN_BUDGET_MS = 2e3;
|
|
@@ -36811,7 +37692,7 @@ function resolveWorkerUrl() {
|
|
|
36811
37692
|
for (const name of ["scan-worker.js", "scan-worker.ts"]) {
|
|
36812
37693
|
const candidate = new URL(name, import.meta.url);
|
|
36813
37694
|
try {
|
|
36814
|
-
if (
|
|
37695
|
+
if (existsSync10(fileURLToPath(candidate))) {
|
|
36815
37696
|
resolvedWorkerUrl = candidate;
|
|
36816
37697
|
return candidate;
|
|
36817
37698
|
}
|
|
@@ -37274,13 +38155,9 @@ function createGuardedScanner(partition, gateway, opts) {
|
|
|
37274
38155
|
};
|
|
37275
38156
|
}
|
|
37276
38157
|
|
|
37277
|
-
// ../../packages/plugin-sdk/src/
|
|
37278
|
-
|
|
37279
|
-
import {
|
|
37280
|
-
import { join as join16 } from "path";
|
|
37281
|
-
|
|
37282
|
-
// ../../packages/plugin-sdk/src/inventory-resolver.ts
|
|
37283
|
-
import { arch, hostname as hostname4, platform, release } from "os";
|
|
38158
|
+
// ../../packages/plugin-sdk/src/host-floor.ts
|
|
38159
|
+
import { readFileSync as readFileSync13 } from "fs";
|
|
38160
|
+
import { join as join20 } from "path";
|
|
37284
38161
|
|
|
37285
38162
|
// ../../packages/plugin-sdk/src/model-governance.ts
|
|
37286
38163
|
import {
|
|
@@ -37288,11 +38165,11 @@ import {
|
|
|
37288
38165
|
fstatSync,
|
|
37289
38166
|
mkdirSync as mkdirSync2,
|
|
37290
38167
|
openSync as openSync2,
|
|
37291
|
-
readFileSync as
|
|
38168
|
+
readFileSync as readFileSync12,
|
|
37292
38169
|
readSync,
|
|
37293
38170
|
writeFileSync as writeFileSync5
|
|
37294
38171
|
} from "fs";
|
|
37295
|
-
import { join as
|
|
38172
|
+
import { join as join19 } from "path";
|
|
37296
38173
|
var SESSION_MODEL_MARKER = "session-model";
|
|
37297
38174
|
var DATE_SUFFIX = /-\d{8}$/;
|
|
37298
38175
|
function normalizeModelId(model) {
|
|
@@ -37308,7 +38185,7 @@ function isModelProhibited(model, prohibited) {
|
|
|
37308
38185
|
function readSessionModel(dataDir2, sessionId) {
|
|
37309
38186
|
if (sessionId === void 0 || sessionId === "") return void 0;
|
|
37310
38187
|
try {
|
|
37311
|
-
const parsed2 = JSON.parse(
|
|
38188
|
+
const parsed2 = JSON.parse(readFileSync12(join19(dataDir2, SESSION_MODEL_MARKER), "utf8"));
|
|
37312
38189
|
if (typeof parsed2 !== "object" || parsed2 === null) return void 0;
|
|
37313
38190
|
const record2 = parsed2;
|
|
37314
38191
|
if (record2.sessionId !== sessionId) return void 0;
|
|
@@ -37322,7 +38199,7 @@ function readTail(path) {
|
|
|
37322
38199
|
const fd = openSync2(path, "r");
|
|
37323
38200
|
try {
|
|
37324
38201
|
const { size } = fstatSync(fd);
|
|
37325
|
-
if (size <= TAIL_BYTES) return { text:
|
|
38202
|
+
if (size <= TAIL_BYTES) return { text: readFileSync12(fd, "utf8"), truncated: false };
|
|
37326
38203
|
const buffer = Buffer.allocUnsafe(TAIL_BYTES);
|
|
37327
38204
|
let filled = 0;
|
|
37328
38205
|
while (filled < TAIL_BYTES) {
|
|
@@ -37400,18 +38277,44 @@ function buildModelRefusalEvent(input2) {
|
|
|
37400
38277
|
};
|
|
37401
38278
|
}
|
|
37402
38279
|
|
|
38280
|
+
// ../../packages/plugin-sdk/src/host-floor.ts
|
|
38281
|
+
var HOST_FEATURE = {
|
|
38282
|
+
ModelSwitch: "model-switch",
|
|
38283
|
+
VaultPointerDisplay: "vault-pointer-display"
|
|
38284
|
+
};
|
|
38285
|
+
var HOST_FLOORS = {
|
|
38286
|
+
[HOST_FEATURE.ModelSwitch]: {
|
|
38287
|
+
label: "model-switch protection",
|
|
38288
|
+
hookEvents: ["PreModelSwitch", "PostModelSwitch"],
|
|
38289
|
+
since: "2.1.251"
|
|
38290
|
+
},
|
|
38291
|
+
[HOST_FEATURE.VaultPointerDisplay]: {
|
|
38292
|
+
label: "vault pointer display",
|
|
38293
|
+
hookEvents: ["MessageDisplay"],
|
|
38294
|
+
since: "2.1.152"
|
|
38295
|
+
}
|
|
38296
|
+
};
|
|
38297
|
+
|
|
38298
|
+
// ../../packages/plugin-sdk/src/ignore-layers.ts
|
|
38299
|
+
var import_ignore = __toESM(require_ignore(), 1);
|
|
38300
|
+
import { readFileSync as readFileSync14 } from "fs";
|
|
38301
|
+
import { join as join21 } from "path";
|
|
38302
|
+
|
|
38303
|
+
// ../../packages/plugin-sdk/src/inventory-resolver.ts
|
|
38304
|
+
import { arch, hostname as hostname4, platform, release } from "os";
|
|
38305
|
+
|
|
37403
38306
|
// ../../packages/plugin-sdk/src/nudge.ts
|
|
37404
|
-
import { mkdirSync as mkdirSync3, readFileSync as
|
|
37405
|
-
import { join as
|
|
38307
|
+
import { mkdirSync as mkdirSync3, readFileSync as readFileSync15, writeFileSync as writeFileSync6 } from "fs";
|
|
38308
|
+
import { join as join22 } from "path";
|
|
37406
38309
|
var NUDGE_MARKER = "nudge-last-session";
|
|
37407
38310
|
function claimOnboardingNudge(dataDir2, sessionId) {
|
|
37408
38311
|
return claimOncePerSession(dataDir2, NUDGE_MARKER, sessionId);
|
|
37409
38312
|
}
|
|
37410
38313
|
function claimOncePerSession(dataDir2, marker, sessionId) {
|
|
37411
38314
|
if (!sessionId) return true;
|
|
37412
|
-
const path =
|
|
38315
|
+
const path = join22(dataDir2, marker);
|
|
37413
38316
|
try {
|
|
37414
|
-
if (
|
|
38317
|
+
if (readFileSync15(path, "utf8") === sessionId) return false;
|
|
37415
38318
|
} catch {
|
|
37416
38319
|
}
|
|
37417
38320
|
try {
|
|
@@ -37462,8 +38365,8 @@ function createPolicyResolver(bundle) {
|
|
|
37462
38365
|
}
|
|
37463
38366
|
|
|
37464
38367
|
// ../../packages/plugin-sdk/src/project-files.ts
|
|
37465
|
-
import { existsSync as
|
|
37466
|
-
import { basename as basename5, join as
|
|
38368
|
+
import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
|
|
38369
|
+
import { basename as basename5, join as join23 } from "path";
|
|
37467
38370
|
|
|
37468
38371
|
// ../../packages/plugin-sdk/src/provider-env-antigravity.ts
|
|
37469
38372
|
var optionalBaseUrl2 = external_exports.preprocess((v) => {
|
|
@@ -37494,6 +38397,14 @@ var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
|
|
|
37494
38397
|
// ../../packages/plugin-sdk/src/runtime.ts
|
|
37495
38398
|
import { randomUUID as randomUUID14 } from "crypto";
|
|
37496
38399
|
var ENFORCEMENT_CEILING_ENABLED = false;
|
|
38400
|
+
function applyEnforcementCeiling(action, policyMode, enabled) {
|
|
38401
|
+
if (!enabled || policyMode !== "warn") return action;
|
|
38402
|
+
return action === "block" || action === "redact" ? "warn" : action;
|
|
38403
|
+
}
|
|
38404
|
+
function resolveEnforcedAction(action, opts) {
|
|
38405
|
+
const degraded = !opts.rewritable && action === "redact" ? builtinPolicyToAction(opts.redactFallback) : action;
|
|
38406
|
+
return applyEnforcementCeiling(degraded, opts.policyMode, opts.ceilingEnabled);
|
|
38407
|
+
}
|
|
37497
38408
|
function startTiming() {
|
|
37498
38409
|
try {
|
|
37499
38410
|
return performance.now();
|
|
@@ -37530,7 +38441,7 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
37530
38441
|
bundlesPacked = true;
|
|
37531
38442
|
}
|
|
37532
38443
|
const policyMode = settings.policy;
|
|
37533
|
-
|
|
38444
|
+
let redactFallback = settings.redactFallback;
|
|
37534
38445
|
const dataDir2 = opts?.dataDir;
|
|
37535
38446
|
let rules = [];
|
|
37536
38447
|
let scanner;
|
|
@@ -37574,6 +38485,7 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
37574
38485
|
rules = [...verified, ...unverified];
|
|
37575
38486
|
scanner = createGuardedScanner({ verified, unverified }, gateway, opts?.scanIsolation);
|
|
37576
38487
|
bundleExceptions = bundle.exceptions ?? [];
|
|
38488
|
+
redactFallback = strongerRedactFallback(settings.redactFallback, bundle.redactFallback);
|
|
37577
38489
|
initialized = true;
|
|
37578
38490
|
}
|
|
37579
38491
|
let cachedKey;
|
|
@@ -37602,21 +38514,23 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
37602
38514
|
}
|
|
37603
38515
|
function actionForFinding(finding, excepted, rewritable = true) {
|
|
37604
38516
|
if (excepted?.has(finding)) return "allow";
|
|
37605
|
-
|
|
37606
|
-
|
|
37607
|
-
|
|
37608
|
-
|
|
37609
|
-
|
|
37610
|
-
|
|
38517
|
+
return resolveEnforcedAction(resolveAction(finding.ruleId, finding.category), {
|
|
38518
|
+
policyMode,
|
|
38519
|
+
redactFallback,
|
|
38520
|
+
rewritable,
|
|
38521
|
+
ceilingEnabled: ENFORCEMENT_CEILING_ENABLED
|
|
38522
|
+
});
|
|
37611
38523
|
}
|
|
37612
38524
|
function decide(findings, text, excepted, rewritable = true) {
|
|
37613
38525
|
if (findings.length === 0) return { action: "log", text, findings: [] };
|
|
37614
38526
|
const actionFor = (finding) => actionForFinding(finding, excepted, rewritable);
|
|
38527
|
+
const degradedActions = rewritable ? [] : findings.filter((f) => actionForFinding(f, excepted, true) === "redact").map(actionFor);
|
|
38528
|
+
const degraded = degradedActions.length === 0 ? {} : { redactDegradedTo: degradedActions.reduce((a, b) => strongerAction(a, b)) };
|
|
37615
38529
|
let worst = "log";
|
|
37616
38530
|
for (const finding of findings) {
|
|
37617
38531
|
worst = strongerAction(worst, actionFor(finding));
|
|
37618
38532
|
}
|
|
37619
|
-
if (worst === "block") return { action: "block", text: null, findings };
|
|
38533
|
+
if (worst === "block") return { action: "block", text: null, findings, ...degraded };
|
|
37620
38534
|
if (worst === "redact") {
|
|
37621
38535
|
const redactFindings = findings.filter((f) => actionFor(f) === "redact");
|
|
37622
38536
|
const reversibleFindings = redactFindings.filter((f) => resolver.isReversible(f.ruleId));
|
|
@@ -37626,9 +38540,13 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
37626
38540
|
findings,
|
|
37627
38541
|
enforcedFindings: redactFindings,
|
|
37628
38542
|
reversibleFindings
|
|
38543
|
+
// No `degraded` here, and it is not an omission: `rewritable` is per
|
|
38544
|
+
// CAPTURE, so on an unrewritable field every redact has already become
|
|
38545
|
+
// the fallback and this branch is unreachable. Spreading it would read
|
|
38546
|
+
// as a case that can happen.
|
|
37629
38547
|
};
|
|
37630
38548
|
}
|
|
37631
|
-
return { action: worst, text, findings };
|
|
38549
|
+
return { action: worst, text, findings, ...degraded };
|
|
37632
38550
|
}
|
|
37633
38551
|
function fingerprintOf(key, finding, cache) {
|
|
37634
38552
|
let fp = cache.get(finding);
|
|
@@ -37757,8 +38675,8 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
37757
38675
|
};
|
|
37758
38676
|
}
|
|
37759
38677
|
}
|
|
37760
|
-
async function processText(text, context) {
|
|
37761
|
-
return (await evaluate(text, context, {})).decision;
|
|
38678
|
+
async function processText(text, context, opts2 = {}) {
|
|
38679
|
+
return (await evaluate(text, context, {}, opts2.rewritable)).decision;
|
|
37762
38680
|
}
|
|
37763
38681
|
async function capture(input2, opts2 = {}) {
|
|
37764
38682
|
const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
|
|
@@ -37781,10 +38699,12 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
37781
38699
|
);
|
|
37782
38700
|
const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
|
|
37783
38701
|
const inspectionMs = elapsedMs(timingStartedAt);
|
|
37784
|
-
const
|
|
38702
|
+
const redactDegradedTo = decision.redactDegradedTo;
|
|
38703
|
+
const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 ? {
|
|
37785
38704
|
...input2.metadata,
|
|
37786
38705
|
...exceptionIds.length > 0 ? { exceptionIds } : {},
|
|
37787
|
-
...inspectionMs !== void 0 ? { inspectionMs } : {}
|
|
38706
|
+
...inspectionMs !== void 0 ? { inspectionMs } : {},
|
|
38707
|
+
...redactDegradedTo !== void 0 ? { redactDegradedTo } : {}
|
|
37788
38708
|
} : input2.metadata;
|
|
37789
38709
|
const event = buildIngestEvent({
|
|
37790
38710
|
kind: input2.kind,
|
|
@@ -37856,7 +38776,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
|
37856
38776
|
|
|
37857
38777
|
// ../../packages/plugin-sdk/src/throttle.ts
|
|
37858
38778
|
import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
|
|
37859
|
-
import { join as
|
|
38779
|
+
import { join as join24 } from "path";
|
|
37860
38780
|
|
|
37861
38781
|
// ../../packages/plugin-sdk/src/tokenize.ts
|
|
37862
38782
|
function redactedPlaceholder(category) {
|
|
@@ -38199,9 +39119,9 @@ function commandsFor(platform2) {
|
|
|
38199
39119
|
function writeClipboard(text, opts) {
|
|
38200
39120
|
try {
|
|
38201
39121
|
const platform2 = opts?.platform ?? process.platform;
|
|
38202
|
-
const
|
|
39122
|
+
const spawn4 = opts?.spawn ?? defaultSpawner;
|
|
38203
39123
|
for (const command of commandsFor(platform2)) {
|
|
38204
|
-
if (
|
|
39124
|
+
if (spawn4(command.cmd, [...command.args], text).ok) return true;
|
|
38205
39125
|
}
|
|
38206
39126
|
return false;
|
|
38207
39127
|
} catch {
|
|
@@ -38211,9 +39131,9 @@ function writeClipboard(text, opts) {
|
|
|
38211
39131
|
|
|
38212
39132
|
// src/hooks/model-guard.ts
|
|
38213
39133
|
import { randomUUID as randomUUID15 } from "crypto";
|
|
38214
|
-
import { readFileSync as
|
|
39134
|
+
import { readFileSync as readFileSync16, statSync as statSync9 } from "fs";
|
|
38215
39135
|
import { homedir as homedir3 } from "os";
|
|
38216
|
-
import { dirname as dirname6, join as
|
|
39136
|
+
import { dirname as dirname6, join as join25 } from "path";
|
|
38217
39137
|
function resolveSessionModel(dataDir2, sessionId, transcriptPath) {
|
|
38218
39138
|
return readSessionModel(dataDir2, sessionId) ?? modelFromTranscript(transcriptPath);
|
|
38219
39139
|
}
|
|
@@ -38309,45 +39229,8 @@ function baseMetadata(input2) {
|
|
|
38309
39229
|
}
|
|
38310
39230
|
|
|
38311
39231
|
// src/hooks/store-health.ts
|
|
38312
|
-
import { mkdirSync as mkdirSync5, readFileSync as
|
|
38313
|
-
import { dirname as dirname7, join as
|
|
38314
|
-
|
|
38315
|
-
// ../../packages/plugin-runtime/src/attached/egress-wire.ts
|
|
38316
|
-
import { createHash as createHash5 } from "crypto";
|
|
38317
|
-
function hashProjectKey(projectKey) {
|
|
38318
|
-
return createHash5("sha256").update(projectKey, "utf8").digest("hex");
|
|
38319
|
-
}
|
|
38320
|
-
function toIngestHit(hit) {
|
|
38321
|
-
return {
|
|
38322
|
-
host: hit.host,
|
|
38323
|
-
kind: hit.kind,
|
|
38324
|
-
name: hit.name,
|
|
38325
|
-
category: hit.category,
|
|
38326
|
-
trust: hit.trust,
|
|
38327
|
-
network: hit.network,
|
|
38328
|
-
method: hit.method,
|
|
38329
|
-
transport: hit.transport,
|
|
38330
|
-
url: hit.url,
|
|
38331
|
-
template: hit.template,
|
|
38332
|
-
dataClass: hit.dataClass,
|
|
38333
|
-
site: {
|
|
38334
|
-
file: hit.site.file,
|
|
38335
|
-
line: hit.site.line,
|
|
38336
|
-
dynamic: hit.site.dynamic,
|
|
38337
|
-
vendored: hit.site.vendored
|
|
38338
|
-
}
|
|
38339
|
-
};
|
|
38340
|
-
}
|
|
38341
|
-
function toEgressIngestRequest(input2) {
|
|
38342
|
-
const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
|
|
38343
|
-
const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
|
|
38344
|
-
return {
|
|
38345
|
-
projectKey: hashProjectKey(input2.projectKey),
|
|
38346
|
-
project: input2.project,
|
|
38347
|
-
reconcile,
|
|
38348
|
-
hits: hits.map(toIngestHit)
|
|
38349
|
-
};
|
|
38350
|
-
}
|
|
39232
|
+
import { mkdirSync as mkdirSync5, readFileSync as readFileSync20, writeFileSync as writeFileSync8 } from "fs";
|
|
39233
|
+
import { dirname as dirname7, join as join31 } from "path";
|
|
38351
39234
|
|
|
38352
39235
|
// ../../packages/remote/src/http.ts
|
|
38353
39236
|
import { request as httpRequest } from "http";
|
|
@@ -38532,10 +39415,10 @@ function parsed(schema, body, route) {
|
|
|
38532
39415
|
}
|
|
38533
39416
|
function withoutTrailingSlashes(endpoint) {
|
|
38534
39417
|
let end = endpoint.length;
|
|
38535
|
-
while (end > 0 && endpoint.charCodeAt(end - 1) ===
|
|
39418
|
+
while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
|
|
38536
39419
|
return endpoint.slice(0, end);
|
|
38537
39420
|
}
|
|
38538
|
-
var
|
|
39421
|
+
var SLASH2 = "/".charCodeAt(0);
|
|
38539
39422
|
function createRemoteClient(options) {
|
|
38540
39423
|
const base = withoutTrailingSlashes(options.endpoint);
|
|
38541
39424
|
const url2 = (route) => `${base}${route}`;
|
|
@@ -38628,6 +39511,7 @@ function createRemoteClient(options) {
|
|
|
38628
39511
|
url: url2(ROUTES.shares),
|
|
38629
39512
|
body: JSON.stringify(validated.data)
|
|
38630
39513
|
});
|
|
39514
|
+
if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
|
|
38631
39515
|
okBody(response);
|
|
38632
39516
|
},
|
|
38633
39517
|
async pollCommand() {
|
|
@@ -38650,19 +39534,51 @@ function createRemoteClient(options) {
|
|
|
38650
39534
|
};
|
|
38651
39535
|
}
|
|
38652
39536
|
|
|
38653
|
-
// ../../packages/
|
|
39537
|
+
// ../../packages/remote/src/failure-kind.ts
|
|
38654
39538
|
function statusOf(err) {
|
|
38655
39539
|
if (typeof err !== "object" || err === null || !("status" in err)) return null;
|
|
38656
39540
|
const { status } = err;
|
|
38657
39541
|
if (typeof status !== "number" || !Number.isInteger(status)) return null;
|
|
38658
39542
|
return status >= 100 && status <= 599 ? status : null;
|
|
38659
39543
|
}
|
|
38660
|
-
function
|
|
38661
|
-
|
|
39544
|
+
function nameOf(err) {
|
|
39545
|
+
if (typeof err !== "object" || err === null || !("name" in err)) return null;
|
|
39546
|
+
return typeof err.name === "string" ? err.name : null;
|
|
39547
|
+
}
|
|
39548
|
+
function classifyRemoteFailure(err) {
|
|
39549
|
+
switch (nameOf(err)) {
|
|
39550
|
+
case "RemoteRouteAbsent":
|
|
39551
|
+
return "route-absent";
|
|
39552
|
+
case "RemoteRequestInvalid":
|
|
39553
|
+
return "invalid-request";
|
|
39554
|
+
case "RemoteResponseInvalid":
|
|
39555
|
+
return "rejected";
|
|
39556
|
+
default:
|
|
39557
|
+
break;
|
|
39558
|
+
}
|
|
39559
|
+
const status = statusOf(err);
|
|
39560
|
+
if (status === null) return "unreachable";
|
|
39561
|
+
switch (status) {
|
|
38662
39562
|
case 401:
|
|
38663
39563
|
return "unauthorized";
|
|
38664
39564
|
case 403:
|
|
38665
39565
|
return "forbidden";
|
|
39566
|
+
case 429:
|
|
39567
|
+
return "unreachable";
|
|
39568
|
+
case 404:
|
|
39569
|
+
return "unreachable";
|
|
39570
|
+
default:
|
|
39571
|
+
return status >= 400 && status <= 499 ? "rejected" : "unreachable";
|
|
39572
|
+
}
|
|
39573
|
+
}
|
|
39574
|
+
|
|
39575
|
+
// ../../packages/plugin-runtime/src/attached/failure.ts
|
|
39576
|
+
function classifyFailure(err) {
|
|
39577
|
+
switch (classifyRemoteFailure(err)) {
|
|
39578
|
+
case "unauthorized":
|
|
39579
|
+
return "unauthorized";
|
|
39580
|
+
case "forbidden":
|
|
39581
|
+
return "forbidden";
|
|
38666
39582
|
default:
|
|
38667
39583
|
return "unreachable";
|
|
38668
39584
|
}
|
|
@@ -38684,11 +39600,11 @@ function withTimeout(promise2, ms) {
|
|
|
38684
39600
|
}
|
|
38685
39601
|
|
|
38686
39602
|
// ../../packages/plugin-runtime/src/attached/forward-drops.ts
|
|
38687
|
-
import { readFileSync as
|
|
38688
|
-
import { join as
|
|
39603
|
+
import { readFileSync as readFileSync17 } from "fs";
|
|
39604
|
+
import { join as join26 } from "path";
|
|
38689
39605
|
var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
|
|
38690
39606
|
function forwardDropsPath(dataDir2) {
|
|
38691
|
-
return
|
|
39607
|
+
return join26(dataDir2, FORWARD_DROPS_FILENAME);
|
|
38692
39608
|
}
|
|
38693
39609
|
function recordForwardDrops(dataDir2, count, nowMs) {
|
|
38694
39610
|
if (count <= 0) return;
|
|
@@ -38706,7 +39622,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
|
|
|
38706
39622
|
}
|
|
38707
39623
|
function readForwardDrops(dataDir2) {
|
|
38708
39624
|
try {
|
|
38709
|
-
const parsed2 = JSON.parse(
|
|
39625
|
+
const parsed2 = JSON.parse(readFileSync17(forwardDropsPath(dataDir2), "utf8"));
|
|
38710
39626
|
if (typeof parsed2 !== "object" || parsed2 === null) return null;
|
|
38711
39627
|
const record2 = parsed2;
|
|
38712
39628
|
if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
|
|
@@ -38724,9 +39640,8 @@ function readForwardDrops(dataDir2) {
|
|
|
38724
39640
|
|
|
38725
39641
|
// ../../packages/plugin-runtime/src/attached/forward-policy.ts
|
|
38726
39642
|
import { randomUUID as randomUUID16 } from "crypto";
|
|
38727
|
-
import { readFileSync as readFileSync15 } from "fs";
|
|
38728
39643
|
import { readFile, rename, writeFile } from "fs/promises";
|
|
38729
|
-
import { join as
|
|
39644
|
+
import { join as join27 } from "path";
|
|
38730
39645
|
function isInvalidRequest(err) {
|
|
38731
39646
|
return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
|
|
38732
39647
|
}
|
|
@@ -38740,31 +39655,12 @@ function isServerRejection(err) {
|
|
|
38740
39655
|
var FORWARD_BUDGET_MS = 1500;
|
|
38741
39656
|
var DECISION_PATH_BUDGET_MS = 800;
|
|
38742
39657
|
var BREAKER_FAILURE_THRESHOLD = 3;
|
|
38743
|
-
var BREAKER_COOLDOWN_MS = 3e4;
|
|
38744
39658
|
var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
|
|
38745
|
-
var FAILURES = /* @__PURE__ */ new Set([
|
|
38746
|
-
"unauthorized",
|
|
38747
|
-
"forbidden",
|
|
38748
|
-
"unreachable"
|
|
38749
|
-
]);
|
|
38750
39659
|
var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
|
|
38751
39660
|
var STATE_FILENAME = FORWARD_STATE_FILENAME;
|
|
38752
|
-
function parseBreakerState(raw, nowMs) {
|
|
38753
|
-
try {
|
|
38754
|
-
const parsed2 = JSON.parse(raw);
|
|
38755
|
-
if (typeof parsed2 !== "object" || parsed2 === null) return null;
|
|
38756
|
-
const record2 = parsed2;
|
|
38757
|
-
const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
|
|
38758
|
-
const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
|
|
38759
|
-
const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
|
|
38760
|
-
return { consecutiveFailures: failures, openedAtMs, lastFailure };
|
|
38761
|
-
} catch {
|
|
38762
|
-
return null;
|
|
38763
|
-
}
|
|
38764
|
-
}
|
|
38765
39661
|
function createForwardPolicy(deps) {
|
|
38766
39662
|
const now = deps.now ?? (() => Date.now());
|
|
38767
|
-
const file2 =
|
|
39663
|
+
const file2 = join27(deps.dir, STATE_FILENAME);
|
|
38768
39664
|
let state = null;
|
|
38769
39665
|
let loading = null;
|
|
38770
39666
|
async function readState() {
|
|
@@ -38774,7 +39670,7 @@ function createForwardPolicy(deps) {
|
|
|
38774
39670
|
} catch {
|
|
38775
39671
|
return { ...CLOSED };
|
|
38776
39672
|
}
|
|
38777
|
-
return
|
|
39673
|
+
return parseForwardHealth(raw, now()) ?? { ...CLOSED };
|
|
38778
39674
|
}
|
|
38779
39675
|
async function load() {
|
|
38780
39676
|
if (state !== null) return state;
|
|
@@ -38820,7 +39716,7 @@ function createForwardPolicy(deps) {
|
|
|
38820
39716
|
};
|
|
38821
39717
|
const at = now();
|
|
38822
39718
|
if (current.openedAtMs !== null) {
|
|
38823
|
-
if (
|
|
39719
|
+
if (isForwardPaused(current, at)) {
|
|
38824
39720
|
return { ok: false, reason: "breaker-open" };
|
|
38825
39721
|
}
|
|
38826
39722
|
await persist({
|
|
@@ -39357,7 +40253,18 @@ var AttachedDataGateway = class {
|
|
|
39357
40253
|
// and the spread above would otherwise drop the field silently — which is
|
|
39358
40254
|
// exactly what it did, leaving the whole control inert on every device
|
|
39359
40255
|
// while every test around it stayed green.
|
|
39360
|
-
prohibitedModels: cached2.prohibitedModels
|
|
40256
|
+
prohibitedModels: cached2.prohibitedModels,
|
|
40257
|
+
// NAMED for the same reason as the line above, and it is the same defect
|
|
40258
|
+
// if it is not: `...local` above spreads the DEVICE's bundle, so a field
|
|
40259
|
+
// only the cache carries is dropped in silence. That is what left
|
|
40260
|
+
// `prohibitedModels` inert on every attached device with every test
|
|
40261
|
+
// around it green.
|
|
40262
|
+
//
|
|
40263
|
+
// Taken from the cache rather than merged here, because merging it needs
|
|
40264
|
+
// the device's own SETTING — which is not a bundle field and is not in
|
|
40265
|
+
// scope at this seam. The runtime does that merge, raise-only, where both
|
|
40266
|
+
// values are in hand (createPluginRuntime's ensureInitialized).
|
|
40267
|
+
redactFallback: cached2.redactFallback
|
|
39361
40268
|
// ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
|
|
39362
40269
|
// merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
|
|
39363
40270
|
// it emits, so an 'authored' policy arriving from the control plane
|
|
@@ -39485,10 +40392,6 @@ function toolAuditEvent(input2) {
|
|
|
39485
40392
|
};
|
|
39486
40393
|
}
|
|
39487
40394
|
|
|
39488
|
-
// ../../packages/plugin-runtime/src/attached/history-state.ts
|
|
39489
|
-
import { readFileSync as readFileSync16 } from "fs";
|
|
39490
|
-
import { join as join24 } from "path";
|
|
39491
|
-
|
|
39492
40395
|
// ../../packages/plugin-runtime/src/attached/history-sync.ts
|
|
39493
40396
|
import { createHash as createHash6 } from "crypto";
|
|
39494
40397
|
import { hostname as hostname5 } from "os";
|
|
@@ -39497,6 +40400,10 @@ import { hostname as hostname5 } from "os";
|
|
|
39497
40400
|
var CORRELATION_ID = EventMetadata.shape.correlationId;
|
|
39498
40401
|
var TRACE_ID = EventMetadata.shape.traceId;
|
|
39499
40402
|
var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
|
|
40403
|
+
var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
|
|
40404
|
+
|
|
40405
|
+
// ../../packages/plugin-runtime/src/attached/history-sync.ts
|
|
40406
|
+
var CAPTURE_BATCH_BYTES = 1024 * 1024;
|
|
39500
40407
|
|
|
39501
40408
|
// ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
|
|
39502
40409
|
import { spawn } from "child_process";
|
|
@@ -39504,7 +40411,7 @@ import { fileURLToPath as fileURLToPath2 } from "url";
|
|
|
39504
40411
|
var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
|
|
39505
40412
|
|
|
39506
40413
|
// ../../packages/plugin-runtime/src/attached/plugin-block.ts
|
|
39507
|
-
import { readFileSync as
|
|
40414
|
+
import { readFileSync as readFileSync18 } from "fs";
|
|
39508
40415
|
function createPluginBlock(build, policyStore) {
|
|
39509
40416
|
return async () => {
|
|
39510
40417
|
const cached2 = await policyStore.read();
|
|
@@ -39523,7 +40430,7 @@ function createPluginBlock(build, policyStore) {
|
|
|
39523
40430
|
// ../../packages/plugin-runtime/src/attached/policy-store.ts
|
|
39524
40431
|
import { randomUUID as randomUUID17 } from "crypto";
|
|
39525
40432
|
import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
|
|
39526
|
-
import { join as
|
|
40433
|
+
import { join as join28 } from "path";
|
|
39527
40434
|
|
|
39528
40435
|
// ../../packages/plugin-runtime/src/attached/atomic-publish.ts
|
|
39529
40436
|
import { rename as rename2 } from "fs/promises";
|
|
@@ -39547,7 +40454,7 @@ async function publishByRename(tmp, file2, move = rename2) {
|
|
|
39547
40454
|
|
|
39548
40455
|
// ../../packages/plugin-runtime/src/attached/policy-store.ts
|
|
39549
40456
|
function createPolicyStore(dir = dataDir()) {
|
|
39550
|
-
const file2 =
|
|
40457
|
+
const file2 = join28(dir, "policy-cache.json");
|
|
39551
40458
|
async function read() {
|
|
39552
40459
|
try {
|
|
39553
40460
|
const raw = await readFile2(file2, "utf8");
|
|
@@ -39778,11 +40685,11 @@ function readStorePosture(dbPath2) {
|
|
|
39778
40685
|
// ../../packages/plugin-runtime/src/attached/posture-store.ts
|
|
39779
40686
|
import { randomUUID as randomUUID18 } from "crypto";
|
|
39780
40687
|
import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
|
|
39781
|
-
import { join as
|
|
40688
|
+
import { join as join29 } from "path";
|
|
39782
40689
|
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
39783
40690
|
function createPostureStore(dir = settingsDir(), legacyDir) {
|
|
39784
|
-
const file2 =
|
|
39785
|
-
const legacyFile = legacyDir === void 0 ? null :
|
|
40691
|
+
const file2 = join29(dir, "posture-state.json");
|
|
40692
|
+
const legacyFile = legacyDir === void 0 ? null : join29(legacyDir, "posture-state.json");
|
|
39786
40693
|
async function persist(state) {
|
|
39787
40694
|
await ensureDataDir(dir);
|
|
39788
40695
|
const tmp = `${file2}.${randomUUID18()}.tmp`;
|
|
@@ -39850,8 +40757,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
|
|
|
39850
40757
|
}
|
|
39851
40758
|
|
|
39852
40759
|
// ../../packages/plugin-runtime/src/attached/sync-state.ts
|
|
39853
|
-
import { readFileSync as
|
|
39854
|
-
import { join as
|
|
40760
|
+
import { readFileSync as readFileSync19 } from "fs";
|
|
40761
|
+
import { join as join30 } from "path";
|
|
39855
40762
|
|
|
39856
40763
|
// ../../packages/plugin-runtime/src/attached/status.ts
|
|
39857
40764
|
var REFUSAL_LINES = {
|
|
@@ -39872,6 +40779,14 @@ import { spawn as spawn2 } from "child_process";
|
|
|
39872
40779
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
39873
40780
|
var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
|
|
39874
40781
|
|
|
40782
|
+
// ../../packages/plugin-runtime/src/content-retention-pass.ts
|
|
40783
|
+
var MAX_ROWS_PER_SWEEP = 50 * 1e3;
|
|
40784
|
+
|
|
40785
|
+
// ../../packages/plugin-runtime/src/content-retention-trigger.ts
|
|
40786
|
+
import { spawn as spawn3 } from "child_process";
|
|
40787
|
+
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
40788
|
+
var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
|
|
40789
|
+
|
|
39875
40790
|
// ../../packages/plugin-runtime/src/attached/factory.ts
|
|
39876
40791
|
import { hostname as hostname6 } from "os";
|
|
39877
40792
|
|
|
@@ -40347,7 +41262,7 @@ function markerDirs(dataDir2) {
|
|
|
40347
41262
|
function alreadyClaimed(dirs, marker, sessionId) {
|
|
40348
41263
|
return dirs.some((dir) => {
|
|
40349
41264
|
try {
|
|
40350
|
-
return
|
|
41265
|
+
return readFileSync20(join31(dir, marker), "utf8") === sessionId;
|
|
40351
41266
|
} catch {
|
|
40352
41267
|
return false;
|
|
40353
41268
|
}
|
|
@@ -40357,7 +41272,7 @@ function recordClaim(dirs, marker, sessionId) {
|
|
|
40357
41272
|
for (const dir of dirs) {
|
|
40358
41273
|
try {
|
|
40359
41274
|
mkdirSync5(dir, { recursive: true, mode: DATA_DIR_MODE });
|
|
40360
|
-
writeFileSync8(
|
|
41275
|
+
writeFileSync8(join31(dir, marker), sessionId, { mode: DATA_FILE_MODE });
|
|
40361
41276
|
return;
|
|
40362
41277
|
} catch {
|
|
40363
41278
|
}
|