@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
package/scripts/backfill.js
CHANGED
|
@@ -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,10 +492,7 @@ var require_ignore = __commonJS({
|
|
|
492
492
|
});
|
|
493
493
|
|
|
494
494
|
// src/backfill.ts
|
|
495
|
-
import { fileURLToPath as
|
|
496
|
-
|
|
497
|
-
// ../../packages/plugin-runtime/src/attached/egress-wire.ts
|
|
498
|
-
import { createHash as createHash4 } from "crypto";
|
|
495
|
+
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
499
496
|
|
|
500
497
|
// ../../packages/persistence/src/attached-derived.ts
|
|
501
498
|
import { rmSync } from "fs";
|
|
@@ -508,6 +505,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
|
|
|
508
505
|
import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
|
|
509
506
|
import { join as join2 } from "path";
|
|
510
507
|
|
|
508
|
+
// ../../packages/schema/src/drizzle/deferred-migrations.ts
|
|
509
|
+
var DEFERRED_MIGRATION_TAGS = [
|
|
510
|
+
"0031_audit_capture_by_time_index",
|
|
511
|
+
"0032_audit_capture_by_id_index",
|
|
512
|
+
"0033_audit_capture_location_index",
|
|
513
|
+
"0034_findings_read_indexes"
|
|
514
|
+
];
|
|
515
|
+
|
|
511
516
|
// ../../packages/schema/src/drizzle/sqlite-ddl.ts
|
|
512
517
|
var SQLITE_MIGRATIONS = [
|
|
513
518
|
{
|
|
@@ -625,6 +630,30 @@ var SQLITE_MIGRATIONS = [
|
|
|
625
630
|
{
|
|
626
631
|
tag: "0028_activity_session_probe_indexes",
|
|
627
632
|
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"
|
|
633
|
+
},
|
|
634
|
+
{
|
|
635
|
+
tag: "0029_audit_capture_rollup_index",
|
|
636
|
+
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');"
|
|
637
|
+
},
|
|
638
|
+
{
|
|
639
|
+
tag: "0030_audit_content_expiry",
|
|
640
|
+
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;"
|
|
641
|
+
},
|
|
642
|
+
{
|
|
643
|
+
tag: "0031_audit_capture_by_time_index",
|
|
644
|
+
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');"
|
|
645
|
+
},
|
|
646
|
+
{
|
|
647
|
+
tag: "0032_audit_capture_by_id_index",
|
|
648
|
+
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');"
|
|
649
|
+
},
|
|
650
|
+
{
|
|
651
|
+
tag: "0033_audit_capture_location_index",
|
|
652
|
+
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');"
|
|
653
|
+
},
|
|
654
|
+
{
|
|
655
|
+
tag: "0034_findings_read_indexes",
|
|
656
|
+
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`);"
|
|
628
657
|
}
|
|
629
658
|
];
|
|
630
659
|
|
|
@@ -20625,7 +20654,7 @@ var TOOL_TO_HARNESS = {
|
|
|
20625
20654
|
[SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi
|
|
20626
20655
|
};
|
|
20627
20656
|
function harnessFromTool(tool) {
|
|
20628
|
-
return TOOL_TO_HARNESS[tool] ?? tool;
|
|
20657
|
+
return (Object.hasOwn(TOOL_TO_HARNESS, tool) ? TOOL_TO_HARNESS[tool] : void 0) ?? tool;
|
|
20629
20658
|
}
|
|
20630
20659
|
|
|
20631
20660
|
// ../../packages/schema/src/zod/finding.ts
|
|
@@ -20675,6 +20704,15 @@ var FindingCategory = external_exports.enum([
|
|
|
20675
20704
|
]).meta({ id: "FindingCategory" });
|
|
20676
20705
|
var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
|
|
20677
20706
|
var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
|
|
20707
|
+
var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
|
|
20708
|
+
var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
|
|
20709
|
+
var FindingDelivery = external_exports.object({
|
|
20710
|
+
state: FindingDeliveryState,
|
|
20711
|
+
// The delivery time for `sent`; the failure time for `not_sent` when recorded.
|
|
20712
|
+
at: external_exports.iso.datetime().optional(),
|
|
20713
|
+
// Only on `not_sent`, and only when a known reason was recorded.
|
|
20714
|
+
reason: SyncFailureReason.optional()
|
|
20715
|
+
}).meta({ id: "FindingDelivery" });
|
|
20678
20716
|
var ResolutionMethod = external_exports.enum([
|
|
20679
20717
|
"enforced-in-flight",
|
|
20680
20718
|
"fixed-at-source",
|
|
@@ -20731,7 +20769,10 @@ var FindingInstance = external_exports.object({
|
|
|
20731
20769
|
// The session that event belongs to, when it has one — the seam a
|
|
20732
20770
|
// per-instance "view session" link needs. Absent for events captured
|
|
20733
20771
|
// outside a session.
|
|
20734
|
-
sessionId: external_exports.string().optional()
|
|
20772
|
+
sessionId: external_exports.string().optional(),
|
|
20773
|
+
// The delivery state of the event above (see FindingDelivery). Optional so
|
|
20774
|
+
// readers that do not project it stay valid.
|
|
20775
|
+
delivery: FindingDelivery.optional()
|
|
20735
20776
|
}).meta({ id: "FindingInstance" });
|
|
20736
20777
|
var FindingGroup = external_exports.object({
|
|
20737
20778
|
id: external_exports.string(),
|
|
@@ -20748,13 +20789,11 @@ var FindingGroup = external_exports.object({
|
|
|
20748
20789
|
latestDetectedAt: external_exports.iso.datetime(),
|
|
20749
20790
|
instances: external_exports.array(FindingInstance),
|
|
20750
20791
|
// Derived from instances' statuses with open-dominates precedence (see
|
|
20751
|
-
//
|
|
20792
|
+
// foldGroupStatus). Undefined only when no instance carries a status.
|
|
20752
20793
|
status: FindingStatus.optional(),
|
|
20753
|
-
// The distinct people across the WHOLE group, not just the
|
|
20754
|
-
//
|
|
20755
|
-
//
|
|
20756
|
-
// instance carries a user, or when the store supplied whole-group folds
|
|
20757
|
-
// without one.
|
|
20794
|
+
// The distinct people across the WHOLE group, not just the instances
|
|
20795
|
+
// carried here. Undefined when no instance carries a user, or when the
|
|
20796
|
+
// store supplied whole-group folds without one.
|
|
20758
20797
|
users: external_exports.array(FindingUser).optional()
|
|
20759
20798
|
}).meta({ id: "FindingGroup" });
|
|
20760
20799
|
var FindingStats = external_exports.object({
|
|
@@ -20783,21 +20822,34 @@ var FindingFacets = external_exports.object({
|
|
|
20783
20822
|
// counted under no value.
|
|
20784
20823
|
status: external_exports.array(FindingFacetItem),
|
|
20785
20824
|
// Host tool (attributes.tool_name). Present only on the instance-level
|
|
20786
|
-
// reads, which can filter by it; the
|
|
20825
|
+
// reads, which can filter by it; the type-level read omits the dimension
|
|
20787
20826
|
// because a group spans tools.
|
|
20788
|
-
tool: external_exports.array(FindingFacetItem).optional()
|
|
20827
|
+
tool: external_exports.array(FindingFacetItem).optional(),
|
|
20828
|
+
// Delivery states (FindingDeliveryState). Present only on the
|
|
20829
|
+
// instance-level reads, like `tool`.
|
|
20830
|
+
deployment: external_exports.array(FindingFacetItem).optional()
|
|
20789
20831
|
}).meta({ id: "FindingFacets" });
|
|
20790
|
-
var
|
|
20791
|
-
|
|
20832
|
+
var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
|
|
20833
|
+
id: "FindingTypeSummary"
|
|
20834
|
+
});
|
|
20835
|
+
var DEFAULT_FINDING_TYPES_LIMIT = 50;
|
|
20836
|
+
var MAX_FINDING_TYPES_LIMIT = 100;
|
|
20837
|
+
var ListFindingTypesQuery = external_exports.object({
|
|
20792
20838
|
// NOTE: severity filters by Severity (critical/high/medium/low), not by
|
|
20793
|
-
// FindingAction.
|
|
20839
|
+
// FindingAction. It narrows TYPES: a type's severity is the one its newest
|
|
20840
|
+
// firing version carries, and this list pages types.
|
|
20841
|
+
//
|
|
20842
|
+
// That is NOT a claim the findings of a type share it. A rule can hold several
|
|
20843
|
+
// definition versions at different severities, so a type kept by this filter
|
|
20844
|
+
// can hold findings that individually do not match — see totals.findings on
|
|
20845
|
+
// ListFindingTypesResponse, which counts them all.
|
|
20794
20846
|
severity: external_exports.array(Severity).optional(),
|
|
20795
20847
|
subtype: external_exports.array(external_exports.string()).optional(),
|
|
20796
20848
|
provider: external_exports.array(FindingProvider).optional(),
|
|
20797
20849
|
action: external_exports.array(FindingAction).optional(),
|
|
20798
|
-
// Matches a
|
|
20799
|
-
// individual
|
|
20800
|
-
//
|
|
20850
|
+
// Matches a type's DERIVED status (see FindingGroup.status), not its
|
|
20851
|
+
// individual findings' — so a filtered row's status always reads one of the
|
|
20852
|
+
// requested values.
|
|
20801
20853
|
status: external_exports.array(FindingStatus).optional(),
|
|
20802
20854
|
q: external_exports.string().optional(),
|
|
20803
20855
|
// Scope to findings whose event carries this session id (the Activity page's
|
|
@@ -20807,23 +20859,37 @@ var ListGroupedFindingsQuery = external_exports.object({
|
|
|
20807
20859
|
// from a time-scoped page (Activity's range) can carry that scope. Absent
|
|
20808
20860
|
// means all time — this list has no default window.
|
|
20809
20861
|
from: external_exports.iso.datetime().optional(),
|
|
20810
|
-
// A
|
|
20811
|
-
//
|
|
20812
|
-
//
|
|
20813
|
-
//
|
|
20814
|
-
//
|
|
20862
|
+
// A RULE id that must appear in the page even when the cursor has already
|
|
20863
|
+
// advanced past its sort position. This is what keeps the selected type
|
|
20864
|
+
// visible in the list once it paginates: the target is appended out of sort
|
|
20865
|
+
// order rather than scanned forward for. Never affects totals, facets or the
|
|
20866
|
+
// cursor. Unlike the grouped read this replaces, it names a rule only — an
|
|
20867
|
+
// instance id is resolved by `findingInstance`, which is a primary-key seek
|
|
20868
|
+
// and so is not bounded by what any page happens to hold.
|
|
20815
20869
|
includeId: external_exports.string().optional(),
|
|
20816
|
-
|
|
20817
|
-
limit: external_exports.coerce.number().int().min(1).max(100).optional(),
|
|
20870
|
+
limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
|
|
20818
20871
|
cursor: external_exports.string().optional()
|
|
20819
20872
|
});
|
|
20820
|
-
var
|
|
20873
|
+
var ListFindingTypesResponse = external_exports.object({
|
|
20821
20874
|
totals: external_exports.object({
|
|
20875
|
+
// Findings belonging to the matching TYPES — not findings that each match
|
|
20876
|
+
// the filters. The filters here select types, so a type that survives
|
|
20877
|
+
// contributes its whole instanceCount.
|
|
20878
|
+
//
|
|
20879
|
+
// `status` is the one exception, narrowed per finding via
|
|
20880
|
+
// countInstancesByStatus. `severity`, `provider` and `action` are not, so
|
|
20881
|
+
// this can exceed what the instance read reports for the same filters: a
|
|
20882
|
+
// rule whose severity moved between versions is kept on its newest and
|
|
20883
|
+
// still counts its older findings. Narrowing the other three needs
|
|
20884
|
+
// per-dimension counts the aggregate does not carry today.
|
|
20822
20885
|
findings: external_exports.number().int().nonnegative(),
|
|
20823
|
-
|
|
20886
|
+
// Counts TYPES, which is the unit this read pages. The instance read's
|
|
20887
|
+
// own totals count findings; the two deliberately answer different
|
|
20888
|
+
// questions and are never summed.
|
|
20889
|
+
types: external_exports.number().int().nonnegative()
|
|
20824
20890
|
}),
|
|
20825
20891
|
facets: FindingFacets,
|
|
20826
|
-
items: external_exports.array(
|
|
20892
|
+
items: external_exports.array(FindingTypeSummary),
|
|
20827
20893
|
nextCursor: external_exports.string().nullable(),
|
|
20828
20894
|
// Present only on session-scoped queries (`sessionId` set): per ruleId, how
|
|
20829
20895
|
// many times that rule fired in the session's persisted transcript. Findings
|
|
@@ -20831,7 +20897,7 @@ var ListGroupedFindingsResponse = external_exports.object({
|
|
|
20831
20897
|
// every firing, so the two numbers legitimately differ — this map lets a
|
|
20832
20898
|
// session-scoped view show both.
|
|
20833
20899
|
sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
|
|
20834
|
-
}).meta({ id: "
|
|
20900
|
+
}).meta({ id: "ListFindingTypesResponse" });
|
|
20835
20901
|
var ApplyFindingActionRequest = external_exports.object({
|
|
20836
20902
|
// 'quarantined' is system-assigned (see FindingAction) — clients may not set
|
|
20837
20903
|
// it, so it is excluded from the request contract. The mapping helper
|
|
@@ -20861,16 +20927,19 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
|
|
|
20861
20927
|
var MAX_FLAT_FINDINGS_LIMIT = 200;
|
|
20862
20928
|
var ListFindingInstancesQuery = external_exports.object({
|
|
20863
20929
|
severity: external_exports.array(Severity).optional(),
|
|
20864
|
-
// Rule ids, the same vocabulary the
|
|
20930
|
+
// Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
|
|
20931
|
+
// ONE of them is how the master/detail view scopes its right-hand panel.
|
|
20865
20932
|
subtype: external_exports.array(external_exports.string()).optional(),
|
|
20866
20933
|
provider: external_exports.array(FindingProvider).optional(),
|
|
20867
20934
|
action: external_exports.array(FindingAction).optional(),
|
|
20868
20935
|
// Matches each instance's OWN derived status (deriveFindingStatus), unlike
|
|
20869
|
-
// the
|
|
20936
|
+
// the types query's type-level fold.
|
|
20870
20937
|
status: external_exports.array(FindingStatus).optional(),
|
|
20871
20938
|
// Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
|
|
20872
20939
|
// where the free-text `q` can only match the rendered "via Bash" label.
|
|
20873
20940
|
tool: external_exports.array(external_exports.string()).optional(),
|
|
20941
|
+
// The delivery state of each finding's event (see FindingDelivery).
|
|
20942
|
+
deployment: external_exports.array(FindingDeliveryState).optional(),
|
|
20874
20943
|
// Exact repository / file-path matches, for the drill-down out of the
|
|
20875
20944
|
// locations view. A row whose event carries no repo/file matches neither.
|
|
20876
20945
|
repo: external_exports.string().optional(),
|
|
@@ -20883,37 +20952,51 @@ var ListFindingInstancesQuery = external_exports.object({
|
|
|
20883
20952
|
});
|
|
20884
20953
|
var ListFindingInstancesResponse = external_exports.object({
|
|
20885
20954
|
// Instances matching the filters across the whole scope, not just this
|
|
20886
|
-
// page — cursor-independent, like the
|
|
20955
|
+
// page — cursor-independent, like the types list's totals.
|
|
20887
20956
|
totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
|
|
20888
|
-
// Counts in INSTANCES here, where the
|
|
20957
|
+
// Counts in INSTANCES here, where the types response counts types. Each
|
|
20889
20958
|
// dimension still excludes its own filter.
|
|
20890
20959
|
facets: FindingFacets,
|
|
20891
20960
|
items: external_exports.array(FindingInstanceDetail),
|
|
20892
20961
|
nextCursor: external_exports.string().nullable()
|
|
20893
20962
|
}).meta({ id: "ListFindingInstancesResponse" });
|
|
20894
|
-
var
|
|
20895
|
-
|
|
20896
|
-
|
|
20897
|
-
|
|
20898
|
-
|
|
20899
|
-
|
|
20900
|
-
|
|
20901
|
-
//
|
|
20902
|
-
//
|
|
20903
|
-
|
|
20904
|
-
|
|
20905
|
-
// chips, and the count is what conveys scale.
|
|
20906
|
-
ruleIds: external_exports.array(external_exports.string())
|
|
20907
|
-
}).meta({ id: "FindingLocationFile" });
|
|
20908
|
-
var FindingLocationRepo = external_exports.object({
|
|
20963
|
+
var ListFindingInstancesPage = external_exports.object({
|
|
20964
|
+
items: external_exports.array(FindingInstanceDetail),
|
|
20965
|
+
nextCursor: external_exports.string().nullable()
|
|
20966
|
+
}).meta({ id: "ListFindingInstancesPage" });
|
|
20967
|
+
var FindingLocationSummary = external_exports.object({
|
|
20968
|
+
// Opaque, stable, minted from the pair by encodeLocationId. It exists
|
|
20969
|
+
// because a location's identity is two values and a URL param carries one:
|
|
20970
|
+
// `?loc=` names a location the way `?rule=` names a type. Only ever compared
|
|
20971
|
+
// for EQUALITY — the page's selection check, this read's `includeId`, the
|
|
20972
|
+
// client's page dedupe — never decoded, and never a sort key.
|
|
20973
|
+
id: external_exports.string(),
|
|
20909
20974
|
/** Empty when the instances carried no repo attribute. */
|
|
20910
20975
|
repo: external_exports.string(),
|
|
20976
|
+
// Empty when the instances carried no file path (a prompt, or a tool call
|
|
20977
|
+
// with no file attribution). Both halves empty is a real location — usually
|
|
20978
|
+
// the largest one in a store — and is selectable like any other.
|
|
20979
|
+
file: external_exports.string(),
|
|
20911
20980
|
instanceCount: external_exports.number().int().nonnegative(),
|
|
20981
|
+
// The WORST severity present, not the first row's. It is this list's primary
|
|
20982
|
+
// sort key, so it is also what explains why a row is where it is, and it is
|
|
20983
|
+
// how a reader decides what to open without opening everything.
|
|
20912
20984
|
maxSeverity: Severity,
|
|
20913
20985
|
latestDetectedAt: external_exports.iso.datetime(),
|
|
20986
|
+
// Folded from the instances' derived statuses with the same open-dominates
|
|
20987
|
+
// precedence a group uses, so it answers "is anything left to do here" and
|
|
20988
|
+
// not much more: a location holding 1 open among 40 resolved reads like one
|
|
20989
|
+
// holding 40 open. That loss is accepted — the panel beside this list
|
|
20990
|
+
// carries each finding's own status, and instanceCount sits next to the
|
|
20991
|
+
// badge.
|
|
20914
20992
|
status: FindingStatus.optional(),
|
|
20915
|
-
|
|
20916
|
-
|
|
20993
|
+
// Every distinct rule seen at this location, UNCAPPED — so the length is a
|
|
20994
|
+
// tally rather than a sample and a row can say how many there are. Bounded
|
|
20995
|
+
// by the ruleset, not by the store. The view bounds what it DISPLAYS.
|
|
20996
|
+
ruleIds: external_exports.array(external_exports.string())
|
|
20997
|
+
}).meta({ id: "FindingLocationSummary" });
|
|
20998
|
+
var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
|
|
20999
|
+
var MAX_FINDING_LOCATIONS_LIMIT = 100;
|
|
20917
21000
|
var ListFindingLocationsQuery = external_exports.object({
|
|
20918
21001
|
severity: external_exports.array(Severity).optional(),
|
|
20919
21002
|
subtype: external_exports.array(external_exports.string()).optional(),
|
|
@@ -20923,21 +21006,47 @@ var ListFindingLocationsQuery = external_exports.object({
|
|
|
20923
21006
|
// instances that match, and folds its status from those.
|
|
20924
21007
|
status: external_exports.array(FindingStatus).optional(),
|
|
20925
21008
|
tool: external_exports.array(external_exports.string()).optional(),
|
|
21009
|
+
// The delivery state of each finding's event (see FindingDelivery).
|
|
21010
|
+
deployment: external_exports.array(FindingDeliveryState).optional(),
|
|
20926
21011
|
q: external_exports.string().optional(),
|
|
20927
21012
|
sessionId: external_exports.string().optional(),
|
|
20928
21013
|
from: external_exports.iso.datetime().optional(),
|
|
20929
|
-
|
|
21014
|
+
// A LOCATION id (see FindingLocationSummary.id) that must appear in the page
|
|
21015
|
+
// even when the cursor has already advanced past its sort position — the
|
|
21016
|
+
// counterpart of ListFindingTypesQuery.includeId, and needed far more often
|
|
21017
|
+
// here. Selecting a row pushes the URL, which re-renders the server and resets
|
|
21018
|
+
// the client's page cache to page 0; with distinct (repo, file) pairs running
|
|
21019
|
+
// into the thousands, a selection sitting off page 0 is the ordinary case
|
|
21020
|
+
// rather than a deep-link corner. Never affects totals, facets or the cursor.
|
|
21021
|
+
includeId: external_exports.string().optional(),
|
|
21022
|
+
limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
|
|
21023
|
+
cursor: external_exports.string().optional()
|
|
20930
21024
|
});
|
|
20931
21025
|
var ListFindingLocationsResponse = external_exports.object({
|
|
20932
21026
|
totals: external_exports.object({
|
|
21027
|
+
// Findings matching the filters across the whole scope. Unlike the types
|
|
21028
|
+
// read's same-named field this needs no caveat: the filters here narrow
|
|
21029
|
+
// per finding, so this is the sum of every row's instanceCount.
|
|
20933
21030
|
findings: external_exports.number().int().nonnegative(),
|
|
20934
|
-
|
|
20935
|
-
|
|
21031
|
+
// Counts LOCATIONS, the unit this read pages — the number the paginator
|
|
21032
|
+
// states. The facets beside it count FINDINGS (see below); a surface
|
|
21033
|
+
// showing both says which is which.
|
|
21034
|
+
locations: external_exports.number().int().nonnegative()
|
|
20936
21035
|
}),
|
|
20937
|
-
|
|
20938
|
-
|
|
20939
|
-
|
|
20940
|
-
|
|
21036
|
+
// Counts in FINDINGS, where the types response counts types, each dimension
|
|
21037
|
+
// still excluding its own filter. Deliberately not locations: counting those
|
|
21038
|
+
// needs a set of location keys per dimension per value — memory tracking the
|
|
21039
|
+
// store times the vocabulary, in a read whose scan promises flat memory —
|
|
21040
|
+
// and the cheap per-location version is not an approximation but WRONG. A
|
|
21041
|
+
// location holding {claudecode, block} and {codex, warn} would survive
|
|
21042
|
+
// provider=claudecode AND action=warn, under which no single finding
|
|
21043
|
+
// matches, so the facet would contradict the instanceCount this whole view
|
|
21044
|
+
// rests on. Findings also keep the toolbar in the same unit as the page
|
|
21045
|
+
// tally and the panel it sits above.
|
|
21046
|
+
facets: FindingFacets,
|
|
21047
|
+
/** Sorted by max severity, then most recent, then (repo, file). */
|
|
21048
|
+
items: external_exports.array(FindingLocationSummary),
|
|
21049
|
+
nextCursor: external_exports.string().nullable()
|
|
20941
21050
|
}).meta({ id: "ListFindingLocationsResponse" });
|
|
20942
21051
|
|
|
20943
21052
|
// ../../packages/schema/src/zod/meta.ts
|
|
@@ -21101,6 +21210,10 @@ var CaptureAttributes = external_exports.object({
|
|
|
21101
21210
|
// to 'allow' — the enforcement audit trail's link back to the grant that
|
|
21102
21211
|
// authorized the bypass.
|
|
21103
21212
|
exception_ids: external_exports.array(external_exports.guid()).optional(),
|
|
21213
|
+
// The persisted spellings of EventMetadata's messageId/conversationId — the
|
|
21214
|
+
// join back to the `llm_call` leaf for the same assistant turn.
|
|
21215
|
+
message_id: external_exports.string().optional(),
|
|
21216
|
+
conversation_id: external_exports.string().optional(),
|
|
21104
21217
|
// Whole milliseconds this capture's inspection blocked its caller — the
|
|
21105
21218
|
// plugin's own added latency (see EventMetadata.inspectionMs, whose value
|
|
21106
21219
|
// this is). Promoted to the `inspection_ms` generated column so the facet is
|
|
@@ -21109,7 +21222,19 @@ var CaptureAttributes = external_exports.object({
|
|
|
21109
21222
|
// inline json_extract and is not itself an optimization.
|
|
21110
21223
|
// ABSENT on replayed captures (backfill / worktree scan) and on rows written
|
|
21111
21224
|
// before the measurement shipped — never present as a placeholder 0.
|
|
21112
|
-
inspection_ms: external_exports.number().int().nonnegative().optional()
|
|
21225
|
+
inspection_ms: external_exports.number().int().nonnegative().optional(),
|
|
21226
|
+
// What a `redact` this capture could not carry out became instead (see
|
|
21227
|
+
// EventMetadata.redactDegradedTo, whose value this is). Present only when a
|
|
21228
|
+
// degrade actually happened, so absence is the ordinary case rather than a
|
|
21229
|
+
// reader having to distinguish it from a zero.
|
|
21230
|
+
//
|
|
21231
|
+
// PER CAPTURE, while `inspection_findings.action_taken` is per finding —
|
|
21232
|
+
// so on a multi-finding row this does not say which finding degraded, and
|
|
21233
|
+
// its presence does not mean the fallback decided the capture's action. A
|
|
21234
|
+
// capture denied by another finding's own Block policy carries `block`
|
|
21235
|
+
// here too. The full statement is on EventMetadata.redactDegradedTo; it is
|
|
21236
|
+
// repeated rather than referenced because a store reader opens this file.
|
|
21237
|
+
redact_degraded_to: ActionTaken.optional()
|
|
21113
21238
|
}).catchall(external_exports.unknown());
|
|
21114
21239
|
var ToolCallInspection = external_exports.object({
|
|
21115
21240
|
ruleId: external_exports.string().min(1),
|
|
@@ -21308,7 +21433,17 @@ var AuditEvent = external_exports.object({
|
|
|
21308
21433
|
/** `share` to a first-party/internal destination. */
|
|
21309
21434
|
internal: external_exports.boolean(),
|
|
21310
21435
|
/** Event needs review (e.g. unverified egress). */
|
|
21311
|
-
flagged: external_exports.boolean()
|
|
21436
|
+
flagged: external_exports.boolean(),
|
|
21437
|
+
/**
|
|
21438
|
+
* The body this event's `title` is drawn from was cleared by local body
|
|
21439
|
+
* expiry, so an EMPTY title here means "gone", not "never had one".
|
|
21440
|
+
*
|
|
21441
|
+
* A separate flag rather than a sentinel written into `title`: the title is
|
|
21442
|
+
* rendered text, and a store-layer module that invented display copy for it
|
|
21443
|
+
* would be choosing words the view is supposed to choose. Additive and
|
|
21444
|
+
* defaulted, so an older producer still validates.
|
|
21445
|
+
*/
|
|
21446
|
+
bodyExpired: external_exports.boolean().default(false)
|
|
21312
21447
|
}).meta({ id: "ActivityAuditEvent" });
|
|
21313
21448
|
var ActivitySessionSummary = external_exports.object({
|
|
21314
21449
|
id: external_exports.string(),
|
|
@@ -22106,6 +22241,14 @@ var ControlPlaneErrorBody = external_exports.object({
|
|
|
22106
22241
|
message: external_exports.string().optional()
|
|
22107
22242
|
}).optional()
|
|
22108
22243
|
});
|
|
22244
|
+
var RemoteFailureKind = external_exports.enum([
|
|
22245
|
+
"unauthorized",
|
|
22246
|
+
"forbidden",
|
|
22247
|
+
"route-absent",
|
|
22248
|
+
"invalid-request",
|
|
22249
|
+
"rejected",
|
|
22250
|
+
"unreachable"
|
|
22251
|
+
]);
|
|
22109
22252
|
var AttachDeviceRequest = external_exports.object({
|
|
22110
22253
|
// This machine's own continuity id, so re-attaching ROTATES the credential
|
|
22111
22254
|
// on one machine record instead of producing a second one. Client-minted
|
|
@@ -22641,6 +22784,12 @@ var EventMetadata = external_exports.object({
|
|
|
22641
22784
|
// to 'allow' — the enforcement audit trail's link back to the grant that
|
|
22642
22785
|
// authorized the bypass. Absent on captures where no exception applied.
|
|
22643
22786
|
exceptionIds: external_exports.array(external_exports.guid()).optional(),
|
|
22787
|
+
// The assistant message this capture belongs to, and the conversation it sits
|
|
22788
|
+
// in — set by the browser extension's network capture so a stored `response`
|
|
22789
|
+
// row can be joined to the `llm_call` leaf describing the same turn. Absent
|
|
22790
|
+
// on every other capture path, which has no such id.
|
|
22791
|
+
messageId: external_exports.string().optional(),
|
|
22792
|
+
conversationId: external_exports.string().optional(),
|
|
22644
22793
|
// How long THIS capture's inspection blocked its caller, in whole
|
|
22645
22794
|
// milliseconds — the plugin's own added latency, NOT the LLM call it sat in
|
|
22646
22795
|
// front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
|
|
@@ -22653,7 +22802,37 @@ var EventMetadata = external_exports.object({
|
|
|
22653
22802
|
// Absent is also what every pre-measurement client writes, and what a
|
|
22654
22803
|
// clock failure degrades to — a reader must treat absence as "not measured"
|
|
22655
22804
|
// and never as a zero, which would read as "inspection is free".
|
|
22656
|
-
inspectionMs: external_exports.number().int().nonnegative().optional()
|
|
22805
|
+
inspectionMs: external_exports.number().int().nonnegative().optional(),
|
|
22806
|
+
// What a `redact` this capture COULD NOT CARRY OUT became instead — the
|
|
22807
|
+
// workspace's `redactFallback`, applied because the field could not be
|
|
22808
|
+
// masked in place (a shell command, a URL, or any argument on a host whose
|
|
22809
|
+
// hook contract offers no rewrite channel).
|
|
22810
|
+
//
|
|
22811
|
+
// It exists because the action alone cannot say why. A finding recorded as
|
|
22812
|
+
// `warn` reads identically whether its detection was ASSIGNED Warn or was
|
|
22813
|
+
// assigned Redact on a field that could not take one — and those are
|
|
22814
|
+
// different facts about the same row: the first is a policy the user chose,
|
|
22815
|
+
// the second is a masking the host could not perform. Absent means no
|
|
22816
|
+
// degrade happened, which is every ordinary capture.
|
|
22817
|
+
//
|
|
22818
|
+
// TWO LIMITS a reader of a stored row has to know, because the grain here
|
|
22819
|
+
// is the CAPTURE while `actionTaken` is per FINDING:
|
|
22820
|
+
//
|
|
22821
|
+
// - It does not say WHICH finding degraded. A capture carrying a degraded
|
|
22822
|
+
// `redact` alongside a finding ASSIGNED the same action stores both
|
|
22823
|
+
// identically and one reason for the pair; attributing it to both
|
|
22824
|
+
// describes the assigned one wrongly, and to neither loses the degrade.
|
|
22825
|
+
// - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
|
|
22826
|
+
// became, not the reason the capture ended as it did — a capture denied
|
|
22827
|
+
// by some other finding's own Block policy still carries `block` here,
|
|
22828
|
+
// and clearing the workspace's fallback would not have let it through.
|
|
22829
|
+
// Gate on the value against what a fallback can produce; never read the
|
|
22830
|
+
// field's presence as "this was the fallback's doing".
|
|
22831
|
+
//
|
|
22832
|
+
// Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
|
|
22833
|
+
// Closing either means moving the reason onto the finding row, which
|
|
22834
|
+
// already carries its own action.
|
|
22835
|
+
redactDegradedTo: ActionTaken.optional()
|
|
22657
22836
|
}).meta({ id: "EventMetadata" });
|
|
22658
22837
|
var Event = external_exports.object({
|
|
22659
22838
|
id: external_exports.guid(),
|
|
@@ -22763,7 +22942,32 @@ var RotateKeyInput = external_exports.object({
|
|
|
22763
22942
|
confirmation: external_exports.string()
|
|
22764
22943
|
});
|
|
22765
22944
|
|
|
22945
|
+
// ../../packages/schema/src/zod/finding-delivery.ts
|
|
22946
|
+
var KNOWN_REASONS = SyncFailureReason.options;
|
|
22947
|
+
function knownReason(value) {
|
|
22948
|
+
return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
|
|
22949
|
+
}
|
|
22950
|
+
function deriveFindingDelivery(row) {
|
|
22951
|
+
if (row.kind === "code_change") return { state: "local_scan" };
|
|
22952
|
+
if (row.syncedAt !== null && row.syncedAt > 0) {
|
|
22953
|
+
return { state: "sent", at: epochMillisToIso(row.syncedAt) };
|
|
22954
|
+
}
|
|
22955
|
+
if (row.syncedAt !== null) {
|
|
22956
|
+
const reason = knownReason(row.syncFailure);
|
|
22957
|
+
return {
|
|
22958
|
+
state: "not_sent",
|
|
22959
|
+
...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
|
|
22960
|
+
...reason === void 0 ? {} : { reason }
|
|
22961
|
+
};
|
|
22962
|
+
}
|
|
22963
|
+
if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
|
|
22964
|
+
return { state: "never_offered" };
|
|
22965
|
+
}
|
|
22966
|
+
|
|
22766
22967
|
// ../../packages/schema/src/zod/findings-group-build.ts
|
|
22968
|
+
function lookupOwn(map2, key) {
|
|
22969
|
+
return Object.hasOwn(map2, key) ? map2[key] : void 0;
|
|
22970
|
+
}
|
|
22767
22971
|
function toApiAction(dbVal) {
|
|
22768
22972
|
const map2 = {
|
|
22769
22973
|
log: "monitored",
|
|
@@ -22772,7 +22976,7 @@ function toApiAction(dbVal) {
|
|
|
22772
22976
|
warn: "warned",
|
|
22773
22977
|
allow: "allowed"
|
|
22774
22978
|
};
|
|
22775
|
-
return map2
|
|
22979
|
+
return lookupOwn(map2, dbVal) ?? "allowed";
|
|
22776
22980
|
}
|
|
22777
22981
|
function toApiCategory(dbVal) {
|
|
22778
22982
|
if (dbVal === "code_context") return "source_code";
|
|
@@ -22780,13 +22984,18 @@ function toApiCategory(dbVal) {
|
|
|
22780
22984
|
return parsed2.success ? parsed2.data : "custom";
|
|
22781
22985
|
}
|
|
22782
22986
|
function toApiProvider(sourceTool) {
|
|
22783
|
-
return TOOL_TO_HARNESS
|
|
22987
|
+
return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
|
|
22784
22988
|
}
|
|
22785
|
-
var
|
|
22989
|
+
var FINDING_STATUS_PRECEDENCE = [
|
|
22990
|
+
"open",
|
|
22991
|
+
"handled",
|
|
22992
|
+
"dismissed",
|
|
22993
|
+
"resolved"
|
|
22994
|
+
];
|
|
22786
22995
|
function foldGroupStatus(instanceStatuses) {
|
|
22787
22996
|
const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
|
|
22788
22997
|
if (statuses.size === 0) return void 0;
|
|
22789
|
-
for (const candidate of
|
|
22998
|
+
for (const candidate of FINDING_STATUS_PRECEDENCE) {
|
|
22790
22999
|
if (statuses.has(candidate)) return candidate;
|
|
22791
23000
|
}
|
|
22792
23001
|
return void 0;
|
|
@@ -22799,139 +23008,62 @@ function deriveFindingStatus(row) {
|
|
|
22799
23008
|
if (row.latestResolutionStatus === "dismissed") return "dismissed";
|
|
22800
23009
|
return "open";
|
|
22801
23010
|
}
|
|
22802
|
-
function distinctUsers(instances) {
|
|
22803
|
-
const seen = /* @__PURE__ */ new Set();
|
|
22804
|
-
const users = [];
|
|
22805
|
-
for (const i of instances) {
|
|
22806
|
-
if (i.user === void 0 || seen.has(i.user.id)) continue;
|
|
22807
|
-
seen.add(i.user.id);
|
|
22808
|
-
users.push(i.user);
|
|
22809
|
-
}
|
|
22810
|
-
return users;
|
|
22811
|
-
}
|
|
22812
23011
|
function sortUsers(users) {
|
|
22813
23012
|
return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
|
|
22814
23013
|
}
|
|
22815
|
-
function
|
|
22816
|
-
const overrides = opts.overrides;
|
|
23014
|
+
function buildFindingTypes(aggregates, opts = {}) {
|
|
22817
23015
|
const packNames = opts.packNames;
|
|
22818
|
-
const
|
|
22819
|
-
const
|
|
22820
|
-
|
|
22821
|
-
const
|
|
22822
|
-
|
|
22823
|
-
else byRuleId.set(row.ruleId, [row]);
|
|
22824
|
-
}
|
|
22825
|
-
const groups = [];
|
|
22826
|
-
for (const [ruleId, ruleRows] of byRuleId) {
|
|
22827
|
-
const instances = ruleRows.map((r) => {
|
|
22828
|
-
const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
|
|
22829
|
-
return {
|
|
22830
|
-
id: r.id,
|
|
22831
|
-
provider: toApiProvider(r.sourceTool),
|
|
22832
|
-
repo: r.repo,
|
|
22833
|
-
file: r.file,
|
|
22834
|
-
...r.toolName === void 0 ? {} : { toolName: r.toolName },
|
|
22835
|
-
...r.eventId === void 0 ? {} : { eventId: r.eventId },
|
|
22836
|
-
...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
|
|
22837
|
-
...r.user === void 0 ? {} : { user: r.user },
|
|
22838
|
-
action: toApiAction(effectiveDbAction),
|
|
22839
|
-
detectedAt: r.occurredAt,
|
|
22840
|
-
confidence: r.confidence,
|
|
22841
|
-
status: r.status
|
|
22842
|
-
};
|
|
22843
|
-
});
|
|
22844
|
-
const agg = aggregates?.get(ruleId);
|
|
22845
|
-
const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
|
|
22846
|
-
const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
|
|
22847
|
-
(max, r) => r.occurredAt > max ? r.occurredAt : max,
|
|
22848
|
-
ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
|
|
22849
|
-
);
|
|
22850
|
-
const seenProviders = /* @__PURE__ */ new Set();
|
|
22851
|
-
const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
|
|
22852
|
-
if (seenProviders.has(p)) return false;
|
|
22853
|
-
seenProviders.add(p);
|
|
22854
|
-
return true;
|
|
22855
|
-
});
|
|
22856
|
-
const actionSet = new Set(
|
|
22857
|
-
agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
|
|
22858
|
-
);
|
|
23016
|
+
const types = [];
|
|
23017
|
+
for (const [ruleId, agg] of aggregates) {
|
|
23018
|
+
const users = sortUsers(agg.users ?? []);
|
|
23019
|
+
const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
|
|
23020
|
+
const actionSet = new Set(agg.actionsTaken.map(toApiAction));
|
|
22859
23021
|
const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
|
|
22860
|
-
const
|
|
22861
|
-
const
|
|
22862
|
-
id: ruleId,
|
|
22863
|
-
name: packNames?.get(ruleId) ?? null
|
|
22864
|
-
};
|
|
22865
|
-
const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
|
|
22866
|
-
const policy = { id: `category:${apiCategory}`, name: apiCategory };
|
|
22867
|
-
const match = {
|
|
22868
|
-
maskedValue: ruleRows[0]?.maskedMatch ?? "",
|
|
22869
|
-
contextPrefix: ""
|
|
22870
|
-
// empty (pending privacy review)
|
|
22871
|
-
};
|
|
22872
|
-
const status = foldGroupStatus(
|
|
22873
|
-
agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
|
|
22874
|
-
);
|
|
22875
|
-
const group = {
|
|
23022
|
+
const apiCategory = toApiCategory(agg.category ?? "custom");
|
|
23023
|
+
const type = {
|
|
22876
23024
|
id: ruleId,
|
|
22877
23025
|
category: apiCategory,
|
|
22878
23026
|
subtype: ruleId,
|
|
22879
23027
|
// human label comes with pack metadata later
|
|
22880
|
-
severity,
|
|
22881
|
-
|
|
22882
|
-
|
|
22883
|
-
|
|
22884
|
-
instanceCount: agg?.instanceCount ?? instances.length,
|
|
23028
|
+
severity: agg.severity ?? "low",
|
|
23029
|
+
detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
|
|
23030
|
+
policy: { id: `category:${apiCategory}`, name: apiCategory },
|
|
23031
|
+
instanceCount: agg.instanceCount,
|
|
22885
23032
|
providers,
|
|
22886
23033
|
aggregateAction,
|
|
22887
|
-
latestDetectedAt,
|
|
22888
|
-
|
|
22889
|
-
status,
|
|
23034
|
+
latestDetectedAt: agg.latestDetectedAt,
|
|
23035
|
+
status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
|
|
22890
23036
|
...users.length > 0 ? { users } : {}
|
|
22891
23037
|
};
|
|
22892
|
-
|
|
22893
|
-
|
|
22894
|
-
|
|
22895
|
-
haystackCache.set(group, buildHaystack(group, agg.searchText));
|
|
22896
|
-
}
|
|
23038
|
+
actionsCache.set(type, [...actionSet]);
|
|
23039
|
+
if (agg.searchText !== void 0) {
|
|
23040
|
+
haystackCache.set(type, buildHaystack(type, agg.searchText));
|
|
22897
23041
|
}
|
|
22898
|
-
|
|
23042
|
+
types.push(type);
|
|
22899
23043
|
}
|
|
22900
|
-
return
|
|
23044
|
+
return types;
|
|
22901
23045
|
}
|
|
22902
23046
|
var haystackCache = /* @__PURE__ */ new WeakMap();
|
|
22903
|
-
function buildHaystack(
|
|
23047
|
+
function buildHaystack(t, extra) {
|
|
22904
23048
|
return [
|
|
22905
|
-
|
|
22906
|
-
|
|
22907
|
-
|
|
22908
|
-
|
|
22909
|
-
|
|
22910
|
-
...g.instances.map((i) => i.repo),
|
|
22911
|
-
...g.instances.map((i) => i.file),
|
|
22912
|
-
...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
|
|
22913
|
-
...g.instances.map((i) => i.id),
|
|
22914
|
-
// The people: the whole group's list when the store folded one, plus the
|
|
22915
|
-
// preview's own — the two overlap, and a haystack does not mind.
|
|
22916
|
-
...(g.users ?? []).map((u) => u.name),
|
|
22917
|
-
...g.instances.map((i) => i.user?.name ?? ""),
|
|
23049
|
+
t.subtype,
|
|
23050
|
+
t.category,
|
|
23051
|
+
t.policy.name,
|
|
23052
|
+
t.id,
|
|
23053
|
+
...(t.users ?? []).map((u) => u.name),
|
|
22918
23054
|
...extra === void 0 ? [] : [extra]
|
|
22919
23055
|
].join(" ").toLowerCase();
|
|
22920
23056
|
}
|
|
22921
|
-
function
|
|
22922
|
-
const cached2 = haystackCache.get(
|
|
23057
|
+
function typeHaystack(t) {
|
|
23058
|
+
const cached2 = haystackCache.get(t);
|
|
22923
23059
|
if (cached2 !== void 0) return cached2;
|
|
22924
|
-
const haystack = buildHaystack(
|
|
22925
|
-
haystackCache.set(
|
|
23060
|
+
const haystack = buildHaystack(t);
|
|
23061
|
+
haystackCache.set(t, haystack);
|
|
22926
23062
|
return haystack;
|
|
22927
23063
|
}
|
|
22928
23064
|
var actionsCache = /* @__PURE__ */ new WeakMap();
|
|
22929
|
-
function
|
|
22930
|
-
|
|
22931
|
-
if (cached2 !== void 0) return cached2;
|
|
22932
|
-
const actions = [...new Set(g.instances.map((i) => i.action))];
|
|
22933
|
-
actionsCache.set(g, actions);
|
|
22934
|
-
return actions;
|
|
23065
|
+
function typeActions(t) {
|
|
23066
|
+
return actionsCache.get(t) ?? [];
|
|
22935
23067
|
}
|
|
22936
23068
|
function countInstancesByStatus(statusInputs, statuses) {
|
|
22937
23069
|
const statusSet = new Set(statuses);
|
|
@@ -22942,8 +23074,8 @@ function countInstancesByStatus(statusInputs, statuses) {
|
|
|
22942
23074
|
}
|
|
22943
23075
|
return sum;
|
|
22944
23076
|
}
|
|
22945
|
-
function applyFindingFilters(
|
|
22946
|
-
let filtered =
|
|
23077
|
+
function applyFindingFilters(types, opts) {
|
|
23078
|
+
let filtered = types;
|
|
22947
23079
|
if (opts.severity && opts.severity.length > 0) {
|
|
22948
23080
|
const sevSet = new Set(opts.severity);
|
|
22949
23081
|
filtered = filtered.filter((g) => sevSet.has(g.severity));
|
|
@@ -22954,7 +23086,7 @@ function applyFindingFilters(groups, opts) {
|
|
|
22954
23086
|
}
|
|
22955
23087
|
if (opts.actions && opts.actions.length > 0) {
|
|
22956
23088
|
const actionSet = new Set(opts.actions);
|
|
22957
|
-
filtered = filtered.filter((
|
|
23089
|
+
filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
|
|
22958
23090
|
}
|
|
22959
23091
|
if (opts.subtype && opts.subtype.length > 0) {
|
|
22960
23092
|
const subtypeSet = new Set(opts.subtype);
|
|
@@ -22966,26 +23098,31 @@ function applyFindingFilters(groups, opts) {
|
|
|
22966
23098
|
}
|
|
22967
23099
|
if (opts.q) {
|
|
22968
23100
|
const q = opts.q.toLowerCase();
|
|
22969
|
-
filtered = filtered.filter((
|
|
23101
|
+
filtered = filtered.filter((t) => typeHaystack(t).includes(q));
|
|
22970
23102
|
}
|
|
22971
23103
|
return filtered;
|
|
22972
23104
|
}
|
|
22973
|
-
|
|
22974
|
-
|
|
23105
|
+
function rankByOrder(members2) {
|
|
23106
|
+
return Object.fromEntries(members2.map((member, index) => [member, index]));
|
|
23107
|
+
}
|
|
23108
|
+
var SEVERITY_RANK = rankByOrder(Severity.options);
|
|
23109
|
+
function severityRank(severity) {
|
|
23110
|
+
return lookupOwn(SEVERITY_RANK, severity);
|
|
23111
|
+
}
|
|
22975
23112
|
function compareFindingGroupOrder(a, b) {
|
|
22976
|
-
const rankA =
|
|
22977
|
-
const rankB =
|
|
23113
|
+
const rankA = severityRank(a.severity) ?? -1;
|
|
23114
|
+
const rankB = severityRank(b.severity) ?? -1;
|
|
22978
23115
|
const severityDiff = rankA - rankB;
|
|
22979
23116
|
if (severityDiff !== 0) return severityDiff;
|
|
22980
23117
|
const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
|
|
22981
23118
|
if (recencyDiff !== 0) return recencyDiff;
|
|
22982
23119
|
return a.id.localeCompare(b.id);
|
|
22983
23120
|
}
|
|
22984
|
-
function
|
|
22985
|
-
return [...
|
|
23121
|
+
function sortFindingTypes(types) {
|
|
23122
|
+
return [...types].sort(compareFindingGroupOrder);
|
|
22986
23123
|
}
|
|
22987
|
-
function computeFindingFacets(
|
|
22988
|
-
const forSeverity = applyFindingFilters(
|
|
23124
|
+
function computeFindingFacets(allTypes, opts) {
|
|
23125
|
+
const forSeverity = applyFindingFilters(allTypes, {
|
|
22989
23126
|
providers: opts.providers,
|
|
22990
23127
|
actions: opts.actions,
|
|
22991
23128
|
statuses: opts.statuses,
|
|
@@ -22996,7 +23133,7 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
22996
23133
|
for (const g of forSeverity) {
|
|
22997
23134
|
severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
|
|
22998
23135
|
}
|
|
22999
|
-
const forProvider = applyFindingFilters(
|
|
23136
|
+
const forProvider = applyFindingFilters(allTypes, {
|
|
23000
23137
|
actions: opts.actions,
|
|
23001
23138
|
statuses: opts.statuses,
|
|
23002
23139
|
q: opts.q,
|
|
@@ -23007,7 +23144,7 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
23007
23144
|
for (const g of forProvider) {
|
|
23008
23145
|
for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
|
|
23009
23146
|
}
|
|
23010
|
-
const forAction = applyFindingFilters(
|
|
23147
|
+
const forAction = applyFindingFilters(allTypes, {
|
|
23011
23148
|
providers: opts.providers,
|
|
23012
23149
|
statuses: opts.statuses,
|
|
23013
23150
|
q: opts.q,
|
|
@@ -23016,9 +23153,9 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
23016
23153
|
});
|
|
23017
23154
|
const actionMap = /* @__PURE__ */ new Map();
|
|
23018
23155
|
for (const g of forAction) {
|
|
23019
|
-
for (const a of
|
|
23156
|
+
for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
|
|
23020
23157
|
}
|
|
23021
|
-
const forSubtype = applyFindingFilters(
|
|
23158
|
+
const forSubtype = applyFindingFilters(allTypes, {
|
|
23022
23159
|
providers: opts.providers,
|
|
23023
23160
|
actions: opts.actions,
|
|
23024
23161
|
statuses: opts.statuses,
|
|
@@ -23027,7 +23164,7 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
23027
23164
|
});
|
|
23028
23165
|
const subtypeMap = /* @__PURE__ */ new Map();
|
|
23029
23166
|
for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
|
|
23030
|
-
const forStatus = applyFindingFilters(
|
|
23167
|
+
const forStatus = applyFindingFilters(allTypes, {
|
|
23031
23168
|
providers: opts.providers,
|
|
23032
23169
|
actions: opts.actions,
|
|
23033
23170
|
q: opts.q,
|
|
@@ -23049,6 +23186,20 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
23049
23186
|
}
|
|
23050
23187
|
|
|
23051
23188
|
// ../../packages/schema/src/zod/findings-flat-build.ts
|
|
23189
|
+
function compareCodePoints(a, b) {
|
|
23190
|
+
const aIter = a[Symbol.iterator]();
|
|
23191
|
+
const bIter = b[Symbol.iterator]();
|
|
23192
|
+
for (; ; ) {
|
|
23193
|
+
const aNext = aIter.next();
|
|
23194
|
+
const bNext = bIter.next();
|
|
23195
|
+
if (aNext.done && bNext.done) return 0;
|
|
23196
|
+
if (aNext.done) return -1;
|
|
23197
|
+
if (bNext.done) return 1;
|
|
23198
|
+
const aPoint = aNext.value.codePointAt(0) ?? 0;
|
|
23199
|
+
const bPoint = bNext.value.codePointAt(0) ?? 0;
|
|
23200
|
+
if (aPoint !== bPoint) return aPoint - bPoint;
|
|
23201
|
+
}
|
|
23202
|
+
}
|
|
23052
23203
|
function rowHaystack(row) {
|
|
23053
23204
|
return [
|
|
23054
23205
|
row.ruleId,
|
|
@@ -23073,12 +23224,24 @@ function matchesDimension(row, opts, dimension) {
|
|
|
23073
23224
|
return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
|
|
23074
23225
|
case "statuses":
|
|
23075
23226
|
return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
|
|
23227
|
+
case "deliveries":
|
|
23228
|
+
return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
|
|
23076
23229
|
case "tools":
|
|
23077
23230
|
return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
|
|
23231
|
+
// An EMPTY value is a real filter here, not an absent one. The location
|
|
23232
|
+
// list buckets a finding whose event recorded no repo — or no file — under
|
|
23233
|
+
// the empty string, and selecting that bucket has to narrow the panel to
|
|
23234
|
+
// exactly it. Only `undefined` means "no filter"; a caller that wants every
|
|
23235
|
+
// row omits the key, which every call site already does.
|
|
23236
|
+
//
|
|
23237
|
+
// Reading '' as unset is what this replaced, and it failed in the one place
|
|
23238
|
+
// it mattered: the no-repo/no-file bucket is often the largest in a real
|
|
23239
|
+
// store, and its panel dropped both predicates and returned the WHOLE scope
|
|
23240
|
+
// — a row reading 3 findings beside a panel listing every finding there is.
|
|
23078
23241
|
case "repo":
|
|
23079
|
-
return opts.repo === void 0 ||
|
|
23242
|
+
return opts.repo === void 0 || row.repo === opts.repo;
|
|
23080
23243
|
case "file":
|
|
23081
|
-
return opts.file === void 0 ||
|
|
23244
|
+
return opts.file === void 0 || row.file === opts.file;
|
|
23082
23245
|
case "q":
|
|
23083
23246
|
return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
|
|
23084
23247
|
}
|
|
@@ -23089,6 +23252,7 @@ var DIMENSIONS = [
|
|
|
23089
23252
|
"providers",
|
|
23090
23253
|
"actions",
|
|
23091
23254
|
"statuses",
|
|
23255
|
+
"deliveries",
|
|
23092
23256
|
"tools",
|
|
23093
23257
|
"repo",
|
|
23094
23258
|
"file",
|
|
@@ -23102,10 +23266,19 @@ function matchesInstanceFilters(row, opts, except) {
|
|
|
23102
23266
|
return true;
|
|
23103
23267
|
}
|
|
23104
23268
|
function toItems(counts) {
|
|
23105
|
-
return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
|
|
23269
|
+
return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
|
|
23270
|
+
(a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
|
|
23271
|
+
// NFD spelling of the same text) as equal, so a count tie between
|
|
23272
|
+
// them would otherwise be ordered by whichever the Map iteration
|
|
23273
|
+
// produced. compareCodePoints breaks that tie deterministically, which
|
|
23274
|
+
// makes this a TOTAL order — not one that agrees with SQL collation,
|
|
23275
|
+
// which it need not: foldFacetTuples runs this same sort over grouped
|
|
23276
|
+
// tuples, so both paths order facets identically by construction.
|
|
23277
|
+
compareCodePoints(a.value, b.value)
|
|
23278
|
+
);
|
|
23106
23279
|
}
|
|
23107
|
-
function bump(counts, value) {
|
|
23108
|
-
counts.set(value, (counts.get(value) ?? 0) +
|
|
23280
|
+
function bump(counts, value, by = 1) {
|
|
23281
|
+
counts.set(value, (counts.get(value) ?? 0) + by);
|
|
23109
23282
|
}
|
|
23110
23283
|
function createInstanceFacetAccumulator(opts) {
|
|
23111
23284
|
const severity = /* @__PURE__ */ new Map();
|
|
@@ -23114,6 +23287,7 @@ function createInstanceFacetAccumulator(opts) {
|
|
|
23114
23287
|
const action = /* @__PURE__ */ new Map();
|
|
23115
23288
|
const status = /* @__PURE__ */ new Map();
|
|
23116
23289
|
const tool = /* @__PURE__ */ new Map();
|
|
23290
|
+
const deployment = /* @__PURE__ */ new Map();
|
|
23117
23291
|
return {
|
|
23118
23292
|
add(row) {
|
|
23119
23293
|
if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
|
|
@@ -23128,6 +23302,9 @@ function createInstanceFacetAccumulator(opts) {
|
|
|
23128
23302
|
if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
|
|
23129
23303
|
bump(tool, row.toolName);
|
|
23130
23304
|
}
|
|
23305
|
+
if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
|
|
23306
|
+
bump(deployment, row.delivery.state);
|
|
23307
|
+
}
|
|
23131
23308
|
},
|
|
23132
23309
|
facets: () => ({
|
|
23133
23310
|
severity: toItems(severity),
|
|
@@ -23135,7 +23312,8 @@ function createInstanceFacetAccumulator(opts) {
|
|
|
23135
23312
|
provider: toItems(provider),
|
|
23136
23313
|
action: toItems(action),
|
|
23137
23314
|
status: toItems(status),
|
|
23138
|
-
tool: toItems(tool)
|
|
23315
|
+
tool: toItems(tool),
|
|
23316
|
+
deployment: toItems(deployment)
|
|
23139
23317
|
})
|
|
23140
23318
|
};
|
|
23141
23319
|
}
|
|
@@ -23149,6 +23327,7 @@ function toInstanceDetail(row) {
|
|
|
23149
23327
|
...row.toolName === void 0 ? {} : { toolName: row.toolName },
|
|
23150
23328
|
eventId: row.eventId,
|
|
23151
23329
|
...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
|
|
23330
|
+
...row.delivery === void 0 ? {} : { delivery: row.delivery },
|
|
23152
23331
|
...row.user === void 0 ? {} : { user: row.user },
|
|
23153
23332
|
action: toApiAction(row.actionTaken),
|
|
23154
23333
|
detectedAt: row.occurredAt,
|
|
@@ -23163,12 +23342,6 @@ function toInstanceDetail(row) {
|
|
|
23163
23342
|
policy: { id: `category:${category}`, name: category }
|
|
23164
23343
|
};
|
|
23165
23344
|
}
|
|
23166
|
-
var SEVERITY_ORDER2 = {
|
|
23167
|
-
critical: 0,
|
|
23168
|
-
high: 1,
|
|
23169
|
-
medium: 2,
|
|
23170
|
-
low: 3
|
|
23171
|
-
};
|
|
23172
23345
|
function newLocationAccumulator() {
|
|
23173
23346
|
return {
|
|
23174
23347
|
instanceCount: 0,
|
|
@@ -23183,7 +23356,7 @@ function newLocationAccumulator() {
|
|
|
23183
23356
|
}
|
|
23184
23357
|
function addToLocation(acc, row) {
|
|
23185
23358
|
acc.instanceCount += 1;
|
|
23186
|
-
const rank =
|
|
23359
|
+
const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
|
|
23187
23360
|
if (rank < acc.maxSeverityRank) {
|
|
23188
23361
|
acc.maxSeverityRank = rank;
|
|
23189
23362
|
acc.maxSeverity = row.severity;
|
|
@@ -23192,6 +23365,23 @@ function addToLocation(acc, row) {
|
|
|
23192
23365
|
acc.statuses.push(row.status);
|
|
23193
23366
|
acc.ruleIds.add(row.ruleId);
|
|
23194
23367
|
}
|
|
23368
|
+
function compareLocationOrder(a, b) {
|
|
23369
|
+
const rankA = severityRank(a.maxSeverity) ?? -1;
|
|
23370
|
+
const rankB = severityRank(b.maxSeverity) ?? -1;
|
|
23371
|
+
if (rankA !== rankB) return rankA - rankB;
|
|
23372
|
+
if (a.latestDetectedAt !== b.latestDetectedAt) {
|
|
23373
|
+
return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
|
|
23374
|
+
}
|
|
23375
|
+
const repoDiff = compareCodePoints(a.repo, b.repo);
|
|
23376
|
+
if (repoDiff !== 0) return repoDiff;
|
|
23377
|
+
return compareCodePoints(a.file, b.file);
|
|
23378
|
+
}
|
|
23379
|
+
function encodeLocationId(repo, file2) {
|
|
23380
|
+
return `${encodePart(repo)}/${encodePart(file2)}`;
|
|
23381
|
+
}
|
|
23382
|
+
function encodePart(value) {
|
|
23383
|
+
return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
|
|
23384
|
+
}
|
|
23195
23385
|
|
|
23196
23386
|
// ../../packages/schema/src/zod/installed-pack.ts
|
|
23197
23387
|
var InstalledPack = external_exports.object({
|
|
@@ -23259,6 +23449,11 @@ var Policy = external_exports.object({
|
|
|
23259
23449
|
// test `prohibitedModels` passes and `reversibleRuleIds` fails.
|
|
23260
23450
|
provenance: PolicyProvenance.optional()
|
|
23261
23451
|
}).meta({ id: "Policy" });
|
|
23452
|
+
var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
|
|
23453
|
+
var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
|
|
23454
|
+
var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
|
|
23455
|
+
id: "RedactFallback"
|
|
23456
|
+
});
|
|
23262
23457
|
var PolicyBundle = external_exports.object({
|
|
23263
23458
|
version: external_exports.string(),
|
|
23264
23459
|
policies: external_exports.array(Policy),
|
|
@@ -23306,6 +23501,16 @@ var PolicyBundle = external_exports.object({
|
|
|
23306
23501
|
// control plane), so no name resolution stands between the decision and the
|
|
23307
23502
|
// comparison.
|
|
23308
23503
|
prohibitedModels: external_exports.array(external_exports.string()).optional(),
|
|
23504
|
+
// What a resolved `redact` becomes on a field the host cannot rewrite, as
|
|
23505
|
+
// the ORGANIZATION would have it. Merged raise-only against the device's own
|
|
23506
|
+
// `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
|
|
23507
|
+
// a control plane can tighten a machine and never loosen one — the same
|
|
23508
|
+
// direction `mergeRaiseOnly` enforces for policies.
|
|
23509
|
+
//
|
|
23510
|
+
// Optional so an older backend, and an older on-disk cache, still parses;
|
|
23511
|
+
// absent leaves the device's own setting in force, which is the behaviour
|
|
23512
|
+
// that predates the field and the safe direction to default.
|
|
23513
|
+
redactFallback: RedactFallback.optional(),
|
|
23309
23514
|
customKeywords: external_exports.array(external_exports.string()),
|
|
23310
23515
|
fetchedAt: external_exports.iso.datetime()
|
|
23311
23516
|
}).meta({ id: "PolicyBundle" });
|
|
@@ -23335,11 +23540,6 @@ function severityFloorPolicy(category) {
|
|
|
23335
23540
|
const peak = CATEGORY_PEAK_SEVERITY[category];
|
|
23336
23541
|
return peak === "critical" || peak === "high" ? "warn" : "monitor";
|
|
23337
23542
|
}
|
|
23338
|
-
var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
|
|
23339
|
-
var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
|
|
23340
|
-
var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
|
|
23341
|
-
id: "RedactFallback"
|
|
23342
|
-
});
|
|
23343
23543
|
var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
|
|
23344
23544
|
var BUILTIN_POLICY_SPECS = {
|
|
23345
23545
|
monitor: {
|
|
@@ -23395,6 +23595,11 @@ function isActionAtLeast(action, floor) {
|
|
|
23395
23595
|
function strongerAction(a, b) {
|
|
23396
23596
|
return actionRank(a) >= actionRank(b) ? a : b;
|
|
23397
23597
|
}
|
|
23598
|
+
function strongerRedactFallback(local, remote) {
|
|
23599
|
+
if (remote === void 0) return local;
|
|
23600
|
+
const localAction = builtinPolicyToAction(local);
|
|
23601
|
+
return localAction === strongerAction(localAction, builtinPolicyToAction(remote)) ? local : remote;
|
|
23602
|
+
}
|
|
23398
23603
|
function weakestBuiltinAtLeast(floor) {
|
|
23399
23604
|
return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
|
|
23400
23605
|
}
|
|
@@ -23642,7 +23847,7 @@ function isVaultConsentValid(consent) {
|
|
|
23642
23847
|
}
|
|
23643
23848
|
|
|
23644
23849
|
// ../../packages/schema/src/zod/local.ts
|
|
23645
|
-
var WORKSPACE_SETTINGS_SPEC_VERSION =
|
|
23850
|
+
var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
|
|
23646
23851
|
var MODEL_JUDGE_PAYLOAD_VERSION = 1;
|
|
23647
23852
|
var RunMode = external_exports.enum(["standalone", "attached"]);
|
|
23648
23853
|
var ControlPlaneConnection = external_exports.object({
|
|
@@ -23662,6 +23867,15 @@ var HistorySyncConsent = external_exports.object({
|
|
|
23662
23867
|
payloadVersion: external_exports.number().int().positive(),
|
|
23663
23868
|
endpoint: external_exports.string()
|
|
23664
23869
|
});
|
|
23870
|
+
var BODY_RETENTION_DEFAULT_DAYS = 30;
|
|
23871
|
+
var BodyRetention = external_exports.object({
|
|
23872
|
+
enabled: external_exports.boolean().default(false),
|
|
23873
|
+
// Never 0, and the ceiling is a fat-finger guard rather than a policy
|
|
23874
|
+
// limit — `enabled` is the real gate. A low value cannot reach a row the
|
|
23875
|
+
// sync ledger still owes: the sweep's age filter only ever NARROWS a
|
|
23876
|
+
// candidate set that is already bounded by "delivered, or never owed".
|
|
23877
|
+
retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
|
|
23878
|
+
}).meta({ id: "BodyRetention" });
|
|
23665
23879
|
var WorkspaceSettings = external_exports.object({
|
|
23666
23880
|
specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
|
|
23667
23881
|
runMode: RunMode.default("standalone"),
|
|
@@ -23705,12 +23919,18 @@ var WorkspaceSettings = external_exports.object({
|
|
|
23705
23919
|
// covers the current payload and must be re-granted.
|
|
23706
23920
|
modelJudgeConsent: ModelJudgeConsent.optional(),
|
|
23707
23921
|
// Records that the user consented to the DEFERRED send — the outbox — along
|
|
23708
|
-
// with the payload shape and the endpoint they agreed to. Since payload
|
|
23709
|
-
// that covers
|
|
23710
|
-
// carry prompt/reply text in `content
|
|
23711
|
-
// Absent until granted, and a grant for a different endpoint
|
|
23712
|
-
// payload no longer counts.
|
|
23713
|
-
historySyncConsent: HistorySyncConsent.optional()
|
|
23922
|
+
// with the payload shape and the endpoint they agreed to. Since payload v3
|
|
23923
|
+
// that covers the pre-attach backlog AND undelivered captures alike, and both
|
|
23924
|
+
// carry prompt/reply/tool-output text in `content`; the key name predates
|
|
23925
|
+
// both widenings. Absent until granted, and a grant for a different endpoint
|
|
23926
|
+
// or an older payload no longer counts.
|
|
23927
|
+
historySyncConsent: HistorySyncConsent.optional(),
|
|
23928
|
+
// Local body expiry (see BodyRetention). Off until switched on; expiring a
|
|
23929
|
+
// body never removes the row or its findings.
|
|
23930
|
+
bodyRetention: BodyRetention.default({
|
|
23931
|
+
enabled: false,
|
|
23932
|
+
retainDays: BODY_RETENTION_DEFAULT_DAYS
|
|
23933
|
+
})
|
|
23714
23934
|
});
|
|
23715
23935
|
function defaultWorkspaceSettings() {
|
|
23716
23936
|
return WorkspaceSettings.parse({});
|
|
@@ -23805,12 +24025,15 @@ function toCaptureAttributes(event) {
|
|
|
23805
24025
|
...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
|
|
23806
24026
|
...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
|
|
23807
24027
|
...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
|
|
24028
|
+
...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
|
|
23808
24029
|
// `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
|
|
23809
24030
|
// has ever populated either), but every legacy metadata key still rides
|
|
23810
24031
|
// the bag rather than being silently dropped — CaptureAttributes'
|
|
23811
24032
|
// `.catchall(z.unknown())` carries the long tail.
|
|
23812
24033
|
...metadata?.model !== void 0 ? { model: metadata.model } : {},
|
|
23813
|
-
...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
|
|
24034
|
+
...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
|
|
24035
|
+
...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
|
|
24036
|
+
...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
|
|
23814
24037
|
};
|
|
23815
24038
|
}
|
|
23816
24039
|
function captureDefinitionVersion(finding) {
|
|
@@ -23838,10 +24061,22 @@ var ManagedSettingKey = external_exports.enum([
|
|
|
23838
24061
|
"vaultInlineReveal",
|
|
23839
24062
|
"modelJudgeConsent",
|
|
23840
24063
|
"dataSharesInPlace",
|
|
23841
|
-
"redactFallback"
|
|
24064
|
+
"redactFallback",
|
|
24065
|
+
// Pins the toggle and the day count together — see BodyRetention on why the
|
|
24066
|
+
// two are one unit. An administrator mandating a window wants the count
|
|
24067
|
+
// enforced with it, not one a user can widen while the toggle stays on.
|
|
24068
|
+
"bodyRetention"
|
|
23842
24069
|
]).meta({ id: "ManagedSettingKey" });
|
|
24070
|
+
function isManagedSettingKey(value) {
|
|
24071
|
+
return ManagedSettingKey.safeParse(value).success;
|
|
24072
|
+
}
|
|
23843
24073
|
var ManagedSettingsValues = external_exports.object({
|
|
23844
24074
|
runMode: external_exports.enum(["standalone", "attached"]).optional(),
|
|
24075
|
+
// `controlPlane` and `bodyRetention` are the two nested values, and both are
|
|
24076
|
+
// plain, non-strict objects: a key under either that this build does not know
|
|
24077
|
+
// is stripped and nothing reports it. The unknown-value split in
|
|
24078
|
+
// ManagedSettings below classifies top-level names only, so it stops at
|
|
24079
|
+
// these boundaries.
|
|
23845
24080
|
controlPlane: external_exports.object({
|
|
23846
24081
|
endpoint: external_exports.string().min(1),
|
|
23847
24082
|
label: external_exports.string().min(1).optional()
|
|
@@ -23852,7 +24087,8 @@ var ManagedSettingsValues = external_exports.object({
|
|
|
23852
24087
|
vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
|
|
23853
24088
|
modelJudgeConsent: external_exports.boolean().optional(),
|
|
23854
24089
|
dataSharesInPlace: external_exports.boolean().optional(),
|
|
23855
|
-
redactFallback: RedactFallback.optional()
|
|
24090
|
+
redactFallback: RedactFallback.optional(),
|
|
24091
|
+
bodyRetention: BodyRetention.optional()
|
|
23856
24092
|
}).meta({ id: "ManagedSettingsValues" });
|
|
23857
24093
|
var ManagedSettings = external_exports.object({
|
|
23858
24094
|
specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
|
|
@@ -23860,11 +24096,59 @@ var ManagedSettings = external_exports.object({
|
|
|
23860
24096
|
// decision from a bug. Absent renders as a generic "your organization".
|
|
23861
24097
|
organization: external_exports.string().min(1).optional(),
|
|
23862
24098
|
// What the administrator pinned.
|
|
23863
|
-
|
|
24099
|
+
//
|
|
24100
|
+
// Parsed as a RECORD rather than as the nested schema, and split below for
|
|
24101
|
+
// the same reason `lockedFields` is parsed as names: a plain `z.object`
|
|
24102
|
+
// drops an unrecognised key and succeeds, so a pin this build does not know
|
|
24103
|
+
// vanished and nothing anywhere said so. A pin with no lock is a supported
|
|
24104
|
+
// shape — it is a DEFAULT the user may still change — so that silence hit
|
|
24105
|
+
// exactly the file an administrator is most likely to write while a fleet
|
|
24106
|
+
// is mid-upgrade.
|
|
24107
|
+
//
|
|
24108
|
+
// Splitting here rather than calling `.strict()`: strict would REFUSE the
|
|
24109
|
+
// file, which is the outcome the lock half already rejected — an older
|
|
24110
|
+
// build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
|
|
24111
|
+
// value still fails, because the nested schema is re-run over the known
|
|
24112
|
+
// subset and its issues are re-raised on this parse.
|
|
24113
|
+
values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
|
|
23864
24114
|
// Which of those the user may not change. A key here with no matching value
|
|
23865
24115
|
// freezes whatever the user last chose; a value with no lock is a DEFAULT
|
|
23866
24116
|
// the user may still override. The two are separable on purpose.
|
|
23867
|
-
|
|
24117
|
+
//
|
|
24118
|
+
// Parsed as NAMES rather than as the enum, and split below: a name this
|
|
24119
|
+
// build does not know is dropped from the locked set and reported, never a
|
|
24120
|
+
// reason to refuse the file. The same shape reaches an older build whenever
|
|
24121
|
+
// an administrator locks a key a newer build added, and refusing it there
|
|
24122
|
+
// ran that build entirely unmanaged — every pin and lock gone — on exactly
|
|
24123
|
+
// the fleets most likely to carry a version skew. A name outside the enum
|
|
24124
|
+
// is still never HONOURED: the lockable set stays explicit above.
|
|
24125
|
+
lockedFields: external_exports.array(external_exports.string()).default([])
|
|
24126
|
+
}).transform(({ lockedFields, values, ...rest }, ctx) => {
|
|
24127
|
+
const known = [];
|
|
24128
|
+
const unknown2 = [];
|
|
24129
|
+
for (const name of lockedFields) {
|
|
24130
|
+
if (isManagedSettingKey(name)) known.push(name);
|
|
24131
|
+
else unknown2.push(name);
|
|
24132
|
+
}
|
|
24133
|
+
const knownValues = /* @__PURE__ */ Object.create(null);
|
|
24134
|
+
const unknownValues = [];
|
|
24135
|
+
for (const [name, value] of Object.entries(values)) {
|
|
24136
|
+
if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
|
|
24137
|
+
else unknownValues.push(name);
|
|
24138
|
+
}
|
|
24139
|
+
const pinned = ManagedSettingsValues.safeParse(knownValues);
|
|
24140
|
+
if (!pinned.success) {
|
|
24141
|
+
for (const issue2 of pinned.error.issues)
|
|
24142
|
+
ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
|
|
24143
|
+
return external_exports.NEVER;
|
|
24144
|
+
}
|
|
24145
|
+
return {
|
|
24146
|
+
...rest,
|
|
24147
|
+
values: pinned.data,
|
|
24148
|
+
lockedFields: known,
|
|
24149
|
+
...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
|
|
24150
|
+
...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
|
|
24151
|
+
};
|
|
23868
24152
|
}).meta({ id: "ManagedSettings" });
|
|
23869
24153
|
|
|
23870
24154
|
// ../../packages/schema/src/zod/project-files.ts
|
|
@@ -23988,7 +24272,11 @@ var FindingsTimeseriesPoint = external_exports.object({
|
|
|
23988
24272
|
timestamp: external_exports.iso.date(),
|
|
23989
24273
|
critical: external_exports.number().int().nonnegative(),
|
|
23990
24274
|
high: external_exports.number().int().nonnegative(),
|
|
23991
|
-
medium: external_exports.number().int().nonnegative()
|
|
24275
|
+
medium: external_exports.number().int().nonnegative(),
|
|
24276
|
+
// Optional and additive, so a producer written against the earlier
|
|
24277
|
+
// three-series contract keeps validating. A consumer plotting it resolves the
|
|
24278
|
+
// absent case itself — the chart point requires a number.
|
|
24279
|
+
low: external_exports.number().int().nonnegative().optional()
|
|
23992
24280
|
}).meta({ id: "FindingsTimeseriesPoint" });
|
|
23993
24281
|
var FindingsTimeseriesResponse = external_exports.object({
|
|
23994
24282
|
range: TimeRange,
|
|
@@ -24014,6 +24302,10 @@ var ResolvedFeedItem = external_exports.object({
|
|
|
24014
24302
|
findingKey: external_exports.string(),
|
|
24015
24303
|
ruleId: external_exports.string(),
|
|
24016
24304
|
severity: Severity,
|
|
24305
|
+
// Repository slug, and the file path RELATIVE to it. The pair is what
|
|
24306
|
+
// identifies the file: a bare path matches the same name in every repo.
|
|
24307
|
+
// Optional and additive; empty when the event carried no repo.
|
|
24308
|
+
repo: external_exports.string().optional(),
|
|
24017
24309
|
path: external_exports.string(),
|
|
24018
24310
|
// ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
|
|
24019
24311
|
// findings domain). The reader `.toISOString()`s the DB epoch-ms values.
|
|
@@ -24119,7 +24411,23 @@ var SaveSettingsInput = external_exports.object({
|
|
|
24119
24411
|
modelJudgeConsent: ModelJudgeConsentChoice,
|
|
24120
24412
|
historySyncConsent: HistorySyncConsentChoice,
|
|
24121
24413
|
vaultConsent: external_exports.string(),
|
|
24122
|
-
vaultInlineReveal: external_exports.string()
|
|
24414
|
+
vaultInlineReveal: external_exports.string(),
|
|
24415
|
+
// Widened to `string` like its neighbours rather than typed as
|
|
24416
|
+
// `RedactFallback`, on this module's own layering rule: shape here, VALUE at
|
|
24417
|
+
// the call site, so the domain check receives the type it was written for.
|
|
24418
|
+
//
|
|
24419
|
+
// NOT because a narrower schema would reject differently. `parseActionInput`
|
|
24420
|
+
// is a `safeParse` wrapper and throws for no field schema, so either spelling
|
|
24421
|
+
// reaches a recoverable `{ ok: false }` and there is no rejected promise to
|
|
24422
|
+
// trade against. The real cost runs the other way and is the part worth
|
|
24423
|
+
// knowing: a value this schema admits and the domain enum then rejects lands
|
|
24424
|
+
// on the action's shared refusal, which names NO field, where a shape
|
|
24425
|
+
// rejection reaches `malformedInput` and names the schema key.
|
|
24426
|
+
redactFallback: external_exports.string(),
|
|
24427
|
+
// Shape only, the way the enum fields above are strings only: the RANGE is
|
|
24428
|
+
// `BodyRetention`'s and the action checks it there, so there is one place
|
|
24429
|
+
// that decides what a legal horizon is rather than two that can drift.
|
|
24430
|
+
bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
|
|
24123
24431
|
});
|
|
24124
24432
|
var AttachInput = external_exports.object({
|
|
24125
24433
|
endpoint: external_exports.string(),
|
|
@@ -24291,6 +24599,52 @@ function reviewSeverityRank(reasons) {
|
|
|
24291
24599
|
return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
|
|
24292
24600
|
}
|
|
24293
24601
|
|
|
24602
|
+
// ../../packages/schema/src/zod/web-capture.ts
|
|
24603
|
+
var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
|
|
24604
|
+
var WebUsage = external_exports.object({
|
|
24605
|
+
inputTokens: external_exports.number().int().nonnegative().optional(),
|
|
24606
|
+
outputTokens: external_exports.number().int().nonnegative().optional(),
|
|
24607
|
+
cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
|
|
24608
|
+
cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
|
|
24609
|
+
});
|
|
24610
|
+
var WebToolCall = external_exports.object({
|
|
24611
|
+
toolUseId: external_exports.string().min(1),
|
|
24612
|
+
toolName: external_exports.string().min(1),
|
|
24613
|
+
target: external_exports.string().optional(),
|
|
24614
|
+
isError: external_exports.boolean().optional(),
|
|
24615
|
+
inputSize: external_exports.number().int().nonnegative().optional(),
|
|
24616
|
+
outputSize: external_exports.number().int().nonnegative().optional()
|
|
24617
|
+
});
|
|
24618
|
+
var WebExchange = external_exports.object({
|
|
24619
|
+
messageId: external_exports.string().min(1),
|
|
24620
|
+
startedAt: external_exports.iso.datetime(),
|
|
24621
|
+
model: external_exports.string().optional(),
|
|
24622
|
+
usage: WebUsage.optional(),
|
|
24623
|
+
usageSource: WebUsageSource,
|
|
24624
|
+
stopReason: external_exports.string().optional(),
|
|
24625
|
+
conversationId: external_exports.string().optional(),
|
|
24626
|
+
turnIndex: external_exports.number().int().nonnegative().optional(),
|
|
24627
|
+
toolCalls: external_exports.array(WebToolCall).default([]),
|
|
24628
|
+
// Absent when the adapter recovered no text. Capped by the caller at
|
|
24629
|
+
// RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
|
|
24630
|
+
// short capture is never mistaken for a short reply.
|
|
24631
|
+
responseText: external_exports.string().optional(),
|
|
24632
|
+
truncated: external_exports.boolean().default(false)
|
|
24633
|
+
});
|
|
24634
|
+
var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
|
|
24635
|
+
var WebCaptureStatus = external_exports.object({
|
|
24636
|
+
patched: external_exports.boolean(),
|
|
24637
|
+
live: external_exports.boolean(),
|
|
24638
|
+
blind: external_exports.boolean(),
|
|
24639
|
+
sendsSeenDom: external_exports.number().int().nonnegative(),
|
|
24640
|
+
exchangesSeenNet: external_exports.number().int().nonnegative(),
|
|
24641
|
+
parseFailures: external_exports.number().int().nonnegative(),
|
|
24642
|
+
unparsedBodies: external_exports.number().int().nonnegative(),
|
|
24643
|
+
// The adapter-declared JSON key paths that were absent from a real payload —
|
|
24644
|
+
// the earliest signal that a site's contract moved.
|
|
24645
|
+
shapeMisses: external_exports.array(external_exports.string()).default([])
|
|
24646
|
+
});
|
|
24647
|
+
|
|
24294
24648
|
// ../../packages/persistence/src/paths.ts
|
|
24295
24649
|
import {
|
|
24296
24650
|
chmodSync,
|
|
@@ -24651,6 +25005,22 @@ function discardStore(file2, backup) {
|
|
|
24651
25005
|
}
|
|
24652
25006
|
}
|
|
24653
25007
|
|
|
25008
|
+
// ../../packages/persistence/src/internal/sql-functions.ts
|
|
25009
|
+
var utf8 = new TextDecoder();
|
|
25010
|
+
function akaLower(value) {
|
|
25011
|
+
if (value === null) return null;
|
|
25012
|
+
if (typeof value === "string") return value.toLowerCase();
|
|
25013
|
+
if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
|
|
25014
|
+
return utf8.decode(value).toLowerCase();
|
|
25015
|
+
}
|
|
25016
|
+
function registerSqlFunctions(db) {
|
|
25017
|
+
db.function(
|
|
25018
|
+
"aka_lower",
|
|
25019
|
+
{ deterministic: true, directOnly: true, useBigIntArguments: true },
|
|
25020
|
+
akaLower
|
|
25021
|
+
);
|
|
25022
|
+
}
|
|
25023
|
+
|
|
24654
25024
|
// ../../packages/persistence/src/internal/sql-text.ts
|
|
24655
25025
|
function escapeLikePattern(s) {
|
|
24656
25026
|
return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
|
|
@@ -24735,6 +25105,11 @@ function schemaObjectExists(db, kind, name) {
|
|
|
24735
25105
|
function indexExists(db, name) {
|
|
24736
25106
|
return schemaObjectExists(db, "index", name);
|
|
24737
25107
|
}
|
|
25108
|
+
function indexColumns(db, name) {
|
|
25109
|
+
if (!indexExists(db, name)) return [];
|
|
25110
|
+
const columns = db.prepare(`PRAGMA index_info(${name})`).all();
|
|
25111
|
+
return columns.map((c) => c.name).filter((c) => c !== null);
|
|
25112
|
+
}
|
|
24738
25113
|
function columnNames(db, table, opts) {
|
|
24739
25114
|
const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
|
|
24740
25115
|
const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
|
|
@@ -24796,138 +25171,780 @@ function mapRowsTolerant(rows, map2) {
|
|
|
24796
25171
|
return out;
|
|
24797
25172
|
}
|
|
24798
25173
|
|
|
24799
|
-
// ../../packages/persistence/src/
|
|
24800
|
-
|
|
24801
|
-
|
|
24802
|
-
|
|
24803
|
-
|
|
24804
|
-
|
|
24805
|
-
|
|
24806
|
-
|
|
24807
|
-
|
|
24808
|
-
return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
|
|
25174
|
+
// ../../packages/persistence/src/internal/outbox-lane.ts
|
|
25175
|
+
var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
|
|
25176
|
+
var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
25177
|
+
|
|
25178
|
+
// ../../packages/persistence/src/sync-failure.ts
|
|
25179
|
+
var SYNC_FAILURE_REASONS = SyncFailureReason.options;
|
|
25180
|
+
function syncFailureRejectCondition(column = "sync_failure") {
|
|
25181
|
+
const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
|
|
25182
|
+
return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
|
|
24809
25183
|
}
|
|
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
|
-
|
|
24861
|
-
|
|
24862
|
-
)
|
|
24863
|
-
|
|
24864
|
-
|
|
24865
|
-
|
|
25184
|
+
|
|
25185
|
+
// ../../packages/persistence/src/repositories/history-sync.ts
|
|
25186
|
+
var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
|
|
25187
|
+
var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
25188
|
+
var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
|
|
25189
|
+
var COUNTED_EVENT_TYPES = [
|
|
25190
|
+
...STRUCTURAL_EVENT_TYPES,
|
|
25191
|
+
...OUTBOX_CAPTURE_EVENT_TYPES
|
|
25192
|
+
];
|
|
25193
|
+
var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
25194
|
+
var PARTITION_BUCKETS = `
|
|
25195
|
+
SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
|
|
25196
|
+
SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
|
|
25197
|
+
SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
|
|
25198
|
+
SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
|
|
25199
|
+
AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
|
|
25200
|
+
SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
|
|
25201
|
+
AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
|
|
25202
|
+
-- Spelled as what it INCLUDES rather than what it excludes, so a reason
|
|
25203
|
+
-- added later lands in no bucket and fails the sum assertion, instead
|
|
25204
|
+
-- of silently joining this one.
|
|
25205
|
+
SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
|
|
25206
|
+
AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
|
|
25207
|
+
THEN 1 ELSE 0 END) AS failed,
|
|
25208
|
+
COUNT(*) AS total`;
|
|
25209
|
+
var COUNTED_SCOPE = `
|
|
25210
|
+
WHERE event_type IN (${COUNTED_TYPE_LIST})
|
|
25211
|
+
AND (
|
|
25212
|
+
event_type IN (${TYPE_LIST})
|
|
25213
|
+
OR synced_at IS NOT NULL
|
|
25214
|
+
OR outbox_owed = 1
|
|
25215
|
+
)`;
|
|
25216
|
+
var SKIPPED = -1;
|
|
25217
|
+
var ROW_COLUMNS = `id,
|
|
25218
|
+
parent_id AS parentId,
|
|
25219
|
+
root_session_id AS rootSessionId,
|
|
25220
|
+
event_type AS eventType,
|
|
25221
|
+
host_id AS hostId,
|
|
25222
|
+
harness_id AS harnessId,
|
|
25223
|
+
source_project_id AS sourceProjectId,
|
|
25224
|
+
started_at AS startedAt,
|
|
25225
|
+
ended_at AS endedAt,
|
|
25226
|
+
severity,
|
|
25227
|
+
priority,
|
|
25228
|
+
content,
|
|
25229
|
+
content_hash AS contentHash,
|
|
25230
|
+
attributes`;
|
|
25231
|
+
var SqliteHistorySyncRepository = class {
|
|
25232
|
+
constructor(db) {
|
|
25233
|
+
this.db = db;
|
|
25234
|
+
this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
|
|
25235
|
+
this.sessionsStmt = db.prepare(
|
|
25236
|
+
`SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
|
|
25237
|
+
FROM audit_events
|
|
25238
|
+
WHERE synced_at IS NULL
|
|
25239
|
+
AND event_type IN (${TYPE_LIST})
|
|
25240
|
+
AND started_at < :before
|
|
25241
|
+
GROUP BY sessionId
|
|
25242
|
+
ORDER BY earliest
|
|
25243
|
+
LIMIT :limit`
|
|
25244
|
+
);
|
|
25245
|
+
this.rowsStmt = db.prepare(
|
|
25246
|
+
`SELECT ${ROW_COLUMNS}
|
|
25247
|
+
FROM audit_events
|
|
25248
|
+
WHERE synced_at IS NULL
|
|
25249
|
+
AND event_type IN (${TYPE_LIST})
|
|
25250
|
+
AND started_at < :before
|
|
25251
|
+
AND COALESCE(root_session_id, id) = :sessionId
|
|
25252
|
+
ORDER BY (event_type = 'session') DESC, started_at
|
|
25253
|
+
LIMIT :limit`
|
|
25254
|
+
);
|
|
25255
|
+
this.captureRowsStmt = db.prepare(
|
|
25256
|
+
`SELECT ${ROW_COLUMNS}
|
|
25257
|
+
FROM audit_events
|
|
25258
|
+
WHERE synced_at IS NULL
|
|
25259
|
+
AND sync_claimed_at IS NULL
|
|
25260
|
+
AND outbox_owed = 1
|
|
25261
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})
|
|
25262
|
+
AND started_at < :before
|
|
25263
|
+
ORDER BY started_at
|
|
25264
|
+
LIMIT :limit`
|
|
25265
|
+
);
|
|
25266
|
+
this.markOwedStmt = db.prepare(
|
|
25267
|
+
`UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
|
|
25268
|
+
);
|
|
25269
|
+
this.markCaptureBacklogOwedStmt = db.prepare(
|
|
25270
|
+
`UPDATE audit_events SET outbox_owed = 1
|
|
25271
|
+
WHERE synced_at IS NULL
|
|
25272
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})
|
|
25273
|
+
AND started_at < :before`
|
|
25274
|
+
);
|
|
25275
|
+
this.stampStmt = db.prepare(
|
|
25276
|
+
`UPDATE audit_events
|
|
25277
|
+
SET synced_at = :at,
|
|
25278
|
+
sync_claimed_at = NULL,
|
|
25279
|
+
sync_failed_at = :failedAt,
|
|
25280
|
+
sync_failure = :failure
|
|
25281
|
+
WHERE id = :id`
|
|
25282
|
+
);
|
|
25283
|
+
this.claimRowStmt = db.prepare(
|
|
25284
|
+
`UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
|
|
25285
|
+
);
|
|
25286
|
+
this.releaseRowStmt = db.prepare(
|
|
25287
|
+
`UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
|
|
25288
|
+
);
|
|
25289
|
+
this.releaseStaleClaimsStmt = db.prepare(
|
|
25290
|
+
`UPDATE audit_events SET sync_claimed_at = NULL
|
|
25291
|
+
WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
|
|
25292
|
+
);
|
|
25293
|
+
this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
|
|
25294
|
+
FROM audit_events${COUNTED_SCOPE}`);
|
|
25295
|
+
this.partitionByKindStmt = db.prepare(
|
|
25296
|
+
`SELECT event_type AS kind,${PARTITION_BUCKETS}
|
|
25297
|
+
FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
|
|
25298
|
+
GROUP BY event_type`
|
|
25299
|
+
);
|
|
25300
|
+
this.countsStmt = db.prepare(
|
|
25301
|
+
`SELECT
|
|
25302
|
+
SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
|
|
25303
|
+
SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
|
|
25304
|
+
SUM(CASE WHEN synced_at = ${String(SKIPPED)}
|
|
25305
|
+
AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
|
|
25306
|
+
THEN 1 ELSE 0 END) AS skipped,
|
|
25307
|
+
SUM(CASE WHEN synced_at = ${String(SKIPPED)}
|
|
25308
|
+
AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
|
|
25309
|
+
SUM(CASE WHEN synced_at = ${String(SKIPPED)}
|
|
25310
|
+
AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
|
|
25311
|
+
FROM audit_events
|
|
25312
|
+
WHERE event_type IN (${TYPE_LIST})`
|
|
25313
|
+
);
|
|
25314
|
+
this.captureSkipCountStmt = db.prepare(
|
|
25315
|
+
// EVERY sentinel capture, whatever the reason — deliberately NOT split the
|
|
25316
|
+
// way the structural totals are. The split exists because a refusal is
|
|
25317
|
+
// terminal only against the deployment that gave it, and the structural
|
|
25318
|
+
// re-arm frees it on a change of deployment. The capture lane has no such
|
|
25319
|
+
// escape: re-arming a capture would offer one deployment's undelivered
|
|
25320
|
+
// prompts, with their text, to a deployment that never saw them, which is
|
|
25321
|
+
// exactly what disownCapturesStmt exists to prevent. So on this lane both
|
|
25322
|
+
// reasons mean the same thing — this row will not be sent — and splitting
|
|
25323
|
+
// them would put refused captures in a bucket nothing reads and nothing
|
|
25324
|
+
// frees.
|
|
25325
|
+
`SELECT COUNT(*) AS skipped
|
|
25326
|
+
FROM audit_events
|
|
25327
|
+
WHERE synced_at = ${String(SKIPPED)}
|
|
25328
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})`
|
|
25329
|
+
);
|
|
25330
|
+
this.fingerprintStmt = db.prepare(
|
|
25331
|
+
`SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
|
|
25332
|
+
FROM history_sync WHERE id = 1`
|
|
25333
|
+
);
|
|
25334
|
+
this.setFingerprintStmt = db.prepare(
|
|
25335
|
+
`UPDATE history_sync
|
|
25336
|
+
SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
|
|
25337
|
+
WHERE id = 1`
|
|
25338
|
+
);
|
|
25339
|
+
this.disownCapturesStmt = db.prepare(
|
|
25340
|
+
`UPDATE audit_events SET outbox_owed = NULL
|
|
25341
|
+
WHERE outbox_owed IS NOT NULL
|
|
25342
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})
|
|
25343
|
+
AND started_at < :attachedAt`
|
|
25344
|
+
);
|
|
25345
|
+
this.rearmStmt = db.prepare(
|
|
25346
|
+
`UPDATE audit_events
|
|
25347
|
+
SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
|
|
25348
|
+
WHERE (synced_at > 0
|
|
25349
|
+
OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
|
|
25350
|
+
AND event_type IN (${TYPE_LIST})`
|
|
25351
|
+
);
|
|
25352
|
+
this.claimStmt = db.prepare(
|
|
25353
|
+
`UPDATE history_sync
|
|
25354
|
+
SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
|
|
25355
|
+
WHERE id = 1
|
|
25356
|
+
AND (owner_pid IS NULL
|
|
25357
|
+
OR heartbeat_at IS NULL
|
|
25358
|
+
OR heartbeat_at < :staleBefore
|
|
25359
|
+
OR heartbeat_at > :now)`
|
|
25360
|
+
);
|
|
25361
|
+
this.heartbeatStmt = db.prepare(
|
|
25362
|
+
`UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
|
|
25363
|
+
);
|
|
25364
|
+
this.releaseStmt = db.prepare(
|
|
25365
|
+
`UPDATE history_sync
|
|
25366
|
+
SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
|
|
25367
|
+
WHERE id = 1 AND owner_pid = :pid`
|
|
25368
|
+
);
|
|
25369
|
+
this.closeWindowStmt = db.prepare(
|
|
25370
|
+
`UPDATE audit_events
|
|
25371
|
+
SET synced_at = ${String(SKIPPED)},
|
|
25372
|
+
sync_failed_at = :at,
|
|
25373
|
+
sync_failure = 'detached_undelivered'
|
|
25374
|
+
WHERE synced_at IS NULL
|
|
25375
|
+
AND event_type IN (${TYPE_LIST})
|
|
25376
|
+
AND started_at >= :attachedAt`
|
|
25377
|
+
);
|
|
25378
|
+
this.releaseBoundaryStmt = db.prepare(
|
|
25379
|
+
`UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
|
|
25380
|
+
);
|
|
25381
|
+
this.freezeBoundaryStmt = db.prepare(
|
|
25382
|
+
`UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
|
|
25383
|
+
);
|
|
25384
|
+
this.leaseStmt = db.prepare(
|
|
25385
|
+
`SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
|
|
25386
|
+
acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
|
|
25387
|
+
FROM history_sync WHERE id = 1`
|
|
25388
|
+
);
|
|
25389
|
+
this.inspectionsStmt = db.prepare(
|
|
25390
|
+
`SELECT d.rule_id AS ruleId,
|
|
25391
|
+
d.name AS ruleName,
|
|
25392
|
+
d.version AS ruleVersion,
|
|
25393
|
+
d.category AS category,
|
|
25394
|
+
d.severity AS severity,
|
|
25395
|
+
f.span_start AS spanStart,
|
|
25396
|
+
f.span_end AS spanEnd,
|
|
25397
|
+
f.masked_match AS maskedMatch,
|
|
25398
|
+
f.action_taken AS actionTaken,
|
|
25399
|
+
f.confidence AS confidence
|
|
25400
|
+
FROM inspection_findings f
|
|
25401
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
25402
|
+
WHERE f.audit_event_id = :auditEventId
|
|
25403
|
+
ORDER BY f.span_start, f.id`
|
|
25404
|
+
);
|
|
24866
25405
|
}
|
|
24867
|
-
|
|
24868
|
-
|
|
25406
|
+
db;
|
|
25407
|
+
ensureRowStmt;
|
|
25408
|
+
sessionsStmt;
|
|
25409
|
+
rowsStmt;
|
|
25410
|
+
stampStmt;
|
|
25411
|
+
countsStmt;
|
|
25412
|
+
fingerprintStmt;
|
|
25413
|
+
setFingerprintStmt;
|
|
25414
|
+
rearmStmt;
|
|
25415
|
+
claimStmt;
|
|
25416
|
+
heartbeatStmt;
|
|
25417
|
+
releaseStmt;
|
|
25418
|
+
leaseStmt;
|
|
25419
|
+
inspectionsStmt;
|
|
25420
|
+
closeWindowStmt;
|
|
25421
|
+
releaseBoundaryStmt;
|
|
25422
|
+
freezeBoundaryStmt;
|
|
25423
|
+
captureRowsStmt;
|
|
25424
|
+
markOwedStmt;
|
|
25425
|
+
markCaptureBacklogOwedStmt;
|
|
25426
|
+
captureSkipCountStmt;
|
|
25427
|
+
disownCapturesStmt;
|
|
25428
|
+
partitionStmt;
|
|
25429
|
+
partitionByKindStmt;
|
|
25430
|
+
claimRowStmt;
|
|
25431
|
+
releaseRowStmt;
|
|
25432
|
+
releaseStaleClaimsStmt;
|
|
25433
|
+
/**
|
|
25434
|
+
* The masked detections recorded against one tool call.
|
|
25435
|
+
*
|
|
25436
|
+
* These travel with the event because a tool call's target is not
|
|
25437
|
+
* re-inspectable from the event alone — unlike a capture, where the text
|
|
25438
|
+
* itself is re-scannable. What crosses is the masked match and the rule that
|
|
25439
|
+
* produced it, never the value.
|
|
25440
|
+
*/
|
|
25441
|
+
inspectionsFor(auditEventId) {
|
|
25442
|
+
return allRows(this.inspectionsStmt, { auditEventId });
|
|
24869
25443
|
}
|
|
24870
|
-
|
|
24871
|
-
|
|
24872
|
-
|
|
24873
|
-
|
|
24874
|
-
|
|
24875
|
-
|
|
24876
|
-
|
|
24877
|
-
|
|
24878
|
-
|
|
24879
|
-
|
|
24880
|
-
|
|
25444
|
+
/**
|
|
25445
|
+
* Sessions with structural rows still to send, oldest first.
|
|
25446
|
+
*
|
|
25447
|
+
* BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
|
|
25448
|
+
* read. Anything recorded after the machine attached is the live forward
|
|
25449
|
+
* path's to deliver; this drain exists for what was recorded before it, and a
|
|
25450
|
+
* row both paths send is at best a duplicate request and at worst — for a
|
|
25451
|
+
* session root — an overwrite of the inventory ids the live path resolved.
|
|
25452
|
+
*/
|
|
25453
|
+
pendingSessions(limit, before) {
|
|
25454
|
+
return allRows(this.sessionsStmt, { limit, before }).map(
|
|
25455
|
+
(r) => r.sessionId
|
|
25456
|
+
);
|
|
24881
25457
|
}
|
|
24882
|
-
|
|
24883
|
-
|
|
24884
|
-
|
|
24885
|
-
const marks = [];
|
|
24886
|
-
for (const table of ["events", "findings"]) {
|
|
24887
|
-
try {
|
|
24888
|
-
const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
|
|
24889
|
-
if (row === void 0) {
|
|
24890
|
-
holdsRows = true;
|
|
24891
|
-
marks.push(`${table}:unreadable`);
|
|
24892
|
-
continue;
|
|
24893
|
-
}
|
|
24894
|
-
if (row.n > 0) holdsRows = true;
|
|
24895
|
-
marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
|
|
24896
|
-
} catch {
|
|
24897
|
-
holdsRows = true;
|
|
24898
|
-
marks.push(`${table}:unreadable`);
|
|
24899
|
-
}
|
|
25458
|
+
/** One session's undelivered structural rows within the backlog, root first. */
|
|
25459
|
+
pendingRows(sessionId, limit, before) {
|
|
25460
|
+
return allRows(this.rowsStmt, { sessionId, limit, before });
|
|
24900
25461
|
}
|
|
24901
|
-
|
|
24902
|
-
|
|
24903
|
-
|
|
24904
|
-
|
|
24905
|
-
|
|
24906
|
-
|
|
24907
|
-
|
|
24908
|
-
|
|
24909
|
-
|
|
24910
|
-
|
|
24911
|
-
akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
|
|
24912
|
-
return;
|
|
24913
|
-
}
|
|
25462
|
+
/**
|
|
25463
|
+
* Captures this machine still owes the deployment, oldest first.
|
|
25464
|
+
*
|
|
25465
|
+
* Selected by the `outbox_owed` marker the attached forward path writes, not
|
|
25466
|
+
* by a time window — see captureRowsStmt for why a window could not express
|
|
25467
|
+
* this. `before` is the grace window that leaves a just-recorded capture to
|
|
25468
|
+
* the live path.
|
|
25469
|
+
*/
|
|
25470
|
+
pendingCaptureRows(limit, before) {
|
|
25471
|
+
return allRows(this.captureRowsStmt, { limit, before });
|
|
24914
25472
|
}
|
|
24915
|
-
|
|
25473
|
+
/**
|
|
25474
|
+
* Record that a capture is OWED to the deployment.
|
|
25475
|
+
*
|
|
25476
|
+
* Written by the attached forward path when a live send did not confirm
|
|
25477
|
+
* delivery, and read by the drain as the whole of its eligibility test. It is
|
|
25478
|
+
* a fact rather than an inference: the machine was attached, the send did not
|
|
25479
|
+
* land, so the row is owed — which no time window can state, because the same
|
|
25480
|
+
* window that holds the rows a past attachment left owed also holds every
|
|
25481
|
+
* capture recorded while the machine was DETACHED, and those were never
|
|
25482
|
+
* offered to anyone.
|
|
25483
|
+
*
|
|
25484
|
+
* Idempotent, and never un-set: `markSynced` settling the row is what takes it
|
|
25485
|
+
* out of the drain's read.
|
|
25486
|
+
*/
|
|
25487
|
+
markCaptureOwed(id) {
|
|
25488
|
+
this.markOwedStmt.run({ id });
|
|
25489
|
+
}
|
|
25490
|
+
/**
|
|
25491
|
+
* Mark every capture already on disk as owed, as of `before`.
|
|
25492
|
+
*
|
|
25493
|
+
* The consent-time backfill, called once from `aka attach` when a human
|
|
25494
|
+
* grants existing-history consent — never from an ongoing drain pass, and
|
|
25495
|
+
* never inferred from a boundary that could later move. `before` is the
|
|
25496
|
+
* caller's own "now" at the moment consent was granted, so what this marks
|
|
25497
|
+
* is exactly the backlog the consent prompt already counted, not whatever a
|
|
25498
|
+
* later re-attach or key rotation might widen it to.
|
|
25499
|
+
*
|
|
25500
|
+
* Returns how many rows matched, for the caller to log or test against. Not a
|
|
25501
|
+
* count of NEWLY marked rows — a row still unsynced from an earlier call
|
|
25502
|
+
* matches again and is counted again, the same as `UPDATE`'s own `changes`.
|
|
25503
|
+
*/
|
|
25504
|
+
markCaptureBacklogOwed(before) {
|
|
25505
|
+
return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
|
|
25506
|
+
}
|
|
25507
|
+
/**
|
|
25508
|
+
* Record delivery. Called only AFTER the far side has accepted the rows.
|
|
25509
|
+
*
|
|
25510
|
+
* CLEARS any failure reason in the same statement. A row that failed against
|
|
25511
|
+
* one deployment and then landed is delivered, and leaving the reason behind
|
|
25512
|
+
* would leave the store holding two contradictory answers about one row —
|
|
25513
|
+
* with the surface free to render either.
|
|
25514
|
+
*/
|
|
25515
|
+
markSynced(ids, atMs) {
|
|
25516
|
+
this.stampAll(ids, atMs, null);
|
|
25517
|
+
}
|
|
25518
|
+
/**
|
|
25519
|
+
* Record that THIS MACHINE cannot express the row on the wire.
|
|
25520
|
+
*
|
|
25521
|
+
* Reserved for a local defect — a row that cannot be rebuilt into a valid
|
|
25522
|
+
* payload, or a body the client itself refused to send. It fails identically
|
|
25523
|
+
* against every deployment, so it is terminal everywhere and the re-arm leaves
|
|
25524
|
+
* it alone. A row that merely failed to REACH the deployment stays NULL, so it
|
|
25525
|
+
* is retried; marking those would turn one outage into permanent data loss.
|
|
25526
|
+
*/
|
|
25527
|
+
markSkipped(ids, atMs) {
|
|
25528
|
+
this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
|
|
25529
|
+
}
|
|
25530
|
+
/**
|
|
25531
|
+
* Record that THIS DEPLOYMENT refused the row.
|
|
25532
|
+
*
|
|
25533
|
+
* The same sentinel as `markSkipped`, and deliberately so: both stop the row
|
|
25534
|
+
* being re-offered on this lane, and `synced_at` goes on answering whether a
|
|
25535
|
+
* row is outstanding rather than why. What separates them is the reason, and
|
|
25536
|
+
* what the reason buys is the re-arm — a refusal is one deployment's verdict
|
|
25537
|
+
* on one body, so it is terminal only for as long as this machine points at
|
|
25538
|
+
* that deployment, and `rearmFor` clears it when the deployment changes.
|
|
25539
|
+
*
|
|
25540
|
+
* Leaving such a row NULL instead would be worse than the loss it replaces:
|
|
25541
|
+
* these reads carry no cursor, so an unstamped row the deployment refuses is
|
|
25542
|
+
* the head of every subsequent page, and the lane stalls behind it for ever.
|
|
25543
|
+
*/
|
|
25544
|
+
markRefused(ids, atMs) {
|
|
25545
|
+
this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
|
|
25546
|
+
}
|
|
25547
|
+
eachInTransaction(ids, run) {
|
|
25548
|
+
if (ids.length === 0) return;
|
|
24916
25549
|
withTransaction(
|
|
24917
|
-
db,
|
|
25550
|
+
this.db,
|
|
24918
25551
|
() => {
|
|
24919
|
-
|
|
24920
|
-
|
|
24921
|
-
|
|
24922
|
-
|
|
24923
|
-
|
|
24924
|
-
|
|
24925
|
-
|
|
24926
|
-
|
|
24927
|
-
|
|
24928
|
-
|
|
24929
|
-
|
|
24930
|
-
|
|
25552
|
+
for (const id of ids) run(id);
|
|
25553
|
+
},
|
|
25554
|
+
"IMMEDIATE"
|
|
25555
|
+
);
|
|
25556
|
+
}
|
|
25557
|
+
stampAll(ids, value, failure, failedAtMs) {
|
|
25558
|
+
if (ids.length === 0) return;
|
|
25559
|
+
const failedAt = failure === null ? null : failedAtMs ?? null;
|
|
25560
|
+
withTransaction(
|
|
25561
|
+
this.db,
|
|
25562
|
+
() => {
|
|
25563
|
+
for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
|
|
25564
|
+
},
|
|
25565
|
+
"IMMEDIATE"
|
|
25566
|
+
);
|
|
25567
|
+
}
|
|
25568
|
+
/**
|
|
25569
|
+
* Claim rows as in-flight.
|
|
25570
|
+
*
|
|
25571
|
+
* Advisory in exactly the sense the lease is: it records that a send is in
|
|
25572
|
+
* progress so a surface can say so, and a lost claim costs a row showing as
|
|
25573
|
+
* queued while it is actually being sent. It is not exclusion — the far side
|
|
25574
|
+
* settles a duplicate on the row id.
|
|
25575
|
+
*/
|
|
25576
|
+
claimRows(ids, atMs) {
|
|
25577
|
+
this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
|
|
25578
|
+
}
|
|
25579
|
+
/** Give back a claim without settling — the send failed, the row is queued again. */
|
|
25580
|
+
releaseRows(ids) {
|
|
25581
|
+
this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
|
|
25582
|
+
}
|
|
25583
|
+
/**
|
|
25584
|
+
* Clear claims older than `staleBefore`, and report how many were cleared.
|
|
25585
|
+
*
|
|
25586
|
+
* A process killed between claiming and settling leaves rows claimed with
|
|
25587
|
+
* nothing left to settle them. Without this they read as "sending" for ever.
|
|
25588
|
+
*/
|
|
25589
|
+
releaseStaleClaims(staleBefore) {
|
|
25590
|
+
return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
|
|
25591
|
+
}
|
|
25592
|
+
/**
|
|
25593
|
+
* Every tracked row in exactly one delivery state.
|
|
25594
|
+
*
|
|
25595
|
+
* Takes no boundary on purpose. The boundary answers "what should the drain
|
|
25596
|
+
* pick up now", which is a different question from "what state is this row
|
|
25597
|
+
* in" — and a machine that has never attached has no boundary to pass, so
|
|
25598
|
+
* requiring one would force a caller to invent one and report the whole store
|
|
25599
|
+
* as queued.
|
|
25600
|
+
*/
|
|
25601
|
+
/**
|
|
25602
|
+
* The same partition, one row per kind that a lane carries.
|
|
25603
|
+
*
|
|
25604
|
+
* A kind with nothing to report is ABSENT rather than a row of zeros: the
|
|
25605
|
+
* scope decides which rows exist at all, so a kind that has never been
|
|
25606
|
+
* recorded — or whose captures nobody ever owed — produces no group. A caller
|
|
25607
|
+
* rendering a fixed list of kinds must therefore treat a missing one as "no
|
|
25608
|
+
* rows", never as "zero sent"; the two look identical in a bar and mean
|
|
25609
|
+
* different things.
|
|
25610
|
+
*/
|
|
25611
|
+
partitionByKind() {
|
|
25612
|
+
return allRows(
|
|
25613
|
+
this.partitionByKindStmt,
|
|
25614
|
+
{}
|
|
25615
|
+
).map((row) => ({
|
|
25616
|
+
kind: row.kind,
|
|
25617
|
+
queued: row.queued ?? 0,
|
|
25618
|
+
inProgress: row.inProgress ?? 0,
|
|
25619
|
+
synced: row.synced ?? 0,
|
|
25620
|
+
failed: row.failed ?? 0,
|
|
25621
|
+
refused: row.refused ?? 0,
|
|
25622
|
+
detached: row.detached ?? 0,
|
|
25623
|
+
total: row.total ?? 0
|
|
25624
|
+
}));
|
|
25625
|
+
}
|
|
25626
|
+
partition() {
|
|
25627
|
+
const row = getRow(this.partitionStmt, {});
|
|
25628
|
+
return {
|
|
25629
|
+
queued: row?.queued ?? 0,
|
|
25630
|
+
inProgress: row?.inProgress ?? 0,
|
|
25631
|
+
synced: row?.synced ?? 0,
|
|
25632
|
+
failed: row?.failed ?? 0,
|
|
25633
|
+
refused: row?.refused ?? 0,
|
|
25634
|
+
detached: row?.detached ?? 0,
|
|
25635
|
+
total: row?.total ?? 0
|
|
25636
|
+
};
|
|
25637
|
+
}
|
|
25638
|
+
/** `pending` counts only what is inside the backlog; sent and skipped are totals. */
|
|
25639
|
+
counts(before) {
|
|
25640
|
+
const row = getRow(this.countsStmt, { before });
|
|
25641
|
+
const captures = getRow(this.captureSkipCountStmt);
|
|
25642
|
+
return {
|
|
25643
|
+
pending: row?.pending ?? 0,
|
|
25644
|
+
sent: row?.sent ?? 0,
|
|
25645
|
+
skipped: row?.skipped ?? 0,
|
|
25646
|
+
refused: row?.refused ?? 0,
|
|
25647
|
+
detached: row?.detached ?? 0,
|
|
25648
|
+
capturesSkipped: captures?.skipped ?? 0
|
|
25649
|
+
};
|
|
25650
|
+
}
|
|
25651
|
+
/**
|
|
25652
|
+
* The deployment the current stamps were made against, and where its backlog
|
|
25653
|
+
* ends.
|
|
25654
|
+
*
|
|
25655
|
+
* READ-ONLY. An absent row reads as an absent deployment, which is what a
|
|
25656
|
+
* machine that has never drained is — and every writer below seeds the row
|
|
25657
|
+
* before it needs one, so nothing depends on this creating it. Keeping the
|
|
25658
|
+
* write off the gate path matters because the gate runs on every pass while a
|
|
25659
|
+
* write has to take the database's write lock.
|
|
25660
|
+
*/
|
|
25661
|
+
deployment() {
|
|
25662
|
+
const row = getRow(
|
|
25663
|
+
this.fingerprintStmt
|
|
25664
|
+
);
|
|
25665
|
+
return {
|
|
25666
|
+
fingerprint: row?.fingerprint ?? void 0,
|
|
25667
|
+
backlogBefore: row?.backlogBefore ?? void 0
|
|
25668
|
+
};
|
|
25669
|
+
}
|
|
25670
|
+
/**
|
|
25671
|
+
* Point the ledger at a different deployment, discarding what it recorded
|
|
25672
|
+
* about the previous one.
|
|
25673
|
+
*
|
|
25674
|
+
* Delivery is a fact about ONE recipient: rows sent to the deployment a
|
|
25675
|
+
* machine has just left are undelivered as far as the new one is concerned.
|
|
25676
|
+
* All four in one transaction, so a crash between them cannot leave stamps
|
|
25677
|
+
* attributed to the wrong deployment, a boundary that belongs to another, or
|
|
25678
|
+
* a disown with no re-mark to follow it.
|
|
25679
|
+
*
|
|
25680
|
+
* The boundary is written HERE and only here, which is what freezes it: a
|
|
25681
|
+
* re-attach to the SAME deployment (a key rotation) leaves the fingerprint
|
|
25682
|
+
* unchanged, so this never runs and the backlog does not widen back over rows
|
|
25683
|
+
* the live path has since delivered.
|
|
25684
|
+
*
|
|
25685
|
+
* `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
|
|
25686
|
+
* granted existing-history consent for the deployment this call is arming —
|
|
25687
|
+
* a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
|
|
25688
|
+
* instant, `backlogBefore` is the ATTACH instant, and the two can be far
|
|
25689
|
+
* apart. Passed only when that grant is valid, since this method has no way
|
|
25690
|
+
* to check consent itself and must not mark a row owed for a machine that
|
|
25691
|
+
* never agreed to it. Applied AFTER the disown above, in the SAME
|
|
25692
|
+
* transaction: what the disown clears is every marker below `backlogBefore`,
|
|
25693
|
+
* which includes this deployment's OWN pre-attach rows — `aka attach` calls
|
|
25694
|
+
* `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
|
|
25695
|
+
* on the cleared side of that bound — and the re-mark in the same
|
|
25696
|
+
* transaction is what puts those rows back. A crash between the two cannot
|
|
25697
|
+
* strand the ledger disowned with nothing re-marked — the transaction either
|
|
25698
|
+
* lands whole or not at all, and a fingerprint mismatch that has not yet
|
|
25699
|
+
* committed re-enters this method on the very next pass. Omit it (the
|
|
25700
|
+
* structural-only tests do) to exercise the disown in isolation.
|
|
25701
|
+
*
|
|
25702
|
+
* The disown is bounded by `backlogBefore`, which is what keeps it from
|
|
25703
|
+
* touching a marker the NEW deployment's OWN live path has already set: B's
|
|
25704
|
+
* live path can mark a capture owed from the moment `aka attach` writes the
|
|
25705
|
+
* descriptor, before the drain's first pass ever reaches this method, and
|
|
25706
|
+
* such a row sits at or after the bound rather than below it. What keeps the
|
|
25707
|
+
* disown from eating THIS SAME CALL's own re-mark is the order, not the
|
|
25708
|
+
* bound — disown runs first, re-mark second, both inside the one
|
|
25709
|
+
* transaction above.
|
|
25710
|
+
*/
|
|
25711
|
+
rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
|
|
25712
|
+
this.ensureRowStmt.run();
|
|
25713
|
+
withTransaction(
|
|
25714
|
+
this.db,
|
|
25715
|
+
() => {
|
|
25716
|
+
const previous = getRow(this.fingerprintStmt)?.fingerprint;
|
|
25717
|
+
this.rearmStmt.run();
|
|
25718
|
+
if (previous !== null && previous !== void 0 && previous !== fingerprint) {
|
|
25719
|
+
this.disownCapturesStmt.run({ attachedAt: backlogBefore });
|
|
25720
|
+
}
|
|
25721
|
+
if (backfillCapturesBefore !== void 0) {
|
|
25722
|
+
this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
|
|
25723
|
+
}
|
|
25724
|
+
this.setFingerprintStmt.run({ fingerprint, backlogBefore });
|
|
25725
|
+
},
|
|
25726
|
+
"IMMEDIATE"
|
|
25727
|
+
);
|
|
25728
|
+
}
|
|
25729
|
+
/**
|
|
25730
|
+
* End the attached period: hand its rows to the live path, and release the
|
|
25731
|
+
* boundary so the next attachment can freeze a new one.
|
|
25732
|
+
*
|
|
25733
|
+
* WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
|
|
25734
|
+
* nothing delivers. The fingerprint is unchanged, so the boundary is never
|
|
25735
|
+
* re-frozen and stays at the FIRST attachment — while nothing forwards at all
|
|
25736
|
+
* during the detached period, because the machine is not attached. Rows
|
|
25737
|
+
* recorded in that window sit after the boundary and before the re-attach, so
|
|
25738
|
+
* neither path takes them, and the pending count reports none outstanding.
|
|
25739
|
+
*
|
|
25740
|
+
* WHAT IT RECORDS, and what it deliberately does not. These rows were the
|
|
25741
|
+
* closing attachment's to deliver and are no longer outstanding — that is what
|
|
25742
|
+
* lets the boundary move. It is NOT a claim that any of them arrived, and the
|
|
25743
|
+
* distinction is not academic: this used to write a delivery TIME, which every
|
|
25744
|
+
* read treats as delivery, so one detach turned a window of undelivered rows
|
|
25745
|
+
* into a window of delivered ones and no surface could tell. It writes the
|
|
25746
|
+
* skip sentinel and a reason of its own instead, so "no longer owed" and
|
|
25747
|
+
* "received" stop being the same fact.
|
|
25748
|
+
*
|
|
25749
|
+
* A change of deployment still frees them (see the re-arm), because the next
|
|
25750
|
+
* deployment has seen none of this machine's history — so the rows reach it
|
|
25751
|
+
* exactly as they did when this wrote a delivery time.
|
|
25752
|
+
*
|
|
25753
|
+
* ONE TRANSACTION, so a crash cannot release the boundary while leaving the
|
|
25754
|
+
* window unstamped — that half-state would re-send the whole attached period
|
|
25755
|
+
* on the next attach, which is the failure the boundary exists to prevent.
|
|
25756
|
+
*/
|
|
25757
|
+
closeAttachedWindow(attachedAtMs, atMs) {
|
|
25758
|
+
this.ensureRowStmt.run();
|
|
25759
|
+
withTransaction(
|
|
25760
|
+
this.db,
|
|
25761
|
+
() => {
|
|
25762
|
+
const row = getRow(this.fingerprintStmt);
|
|
25763
|
+
const from = row?.backlogBefore ?? attachedAtMs;
|
|
25764
|
+
this.closeWindowStmt.run({ at: atMs, attachedAt: from });
|
|
25765
|
+
this.releaseBoundaryStmt.run();
|
|
25766
|
+
},
|
|
25767
|
+
"IMMEDIATE"
|
|
25768
|
+
);
|
|
25769
|
+
}
|
|
25770
|
+
/**
|
|
25771
|
+
* Freeze a boundary for the deployment already on file, KEEPING the stamps.
|
|
25772
|
+
*
|
|
25773
|
+
* The re-attach half of the above. Distinct from `rearmFor`, which is for a
|
|
25774
|
+
* different deployment and therefore discards what was delivered to the old
|
|
25775
|
+
* one: here the recipient is the same, so everything already sent to it stays
|
|
25776
|
+
* sent.
|
|
25777
|
+
*/
|
|
25778
|
+
freezeBoundary(backlogBefore) {
|
|
25779
|
+
this.ensureRowStmt.run();
|
|
25780
|
+
this.freezeBoundaryStmt.run({ backlogBefore });
|
|
25781
|
+
}
|
|
25782
|
+
/** Take the claim, or report that someone live already holds it. */
|
|
25783
|
+
claim(pid, host, nowMs, staleAfterMs) {
|
|
25784
|
+
this.ensureRowStmt.run();
|
|
25785
|
+
let taken = false;
|
|
25786
|
+
withTransaction(
|
|
25787
|
+
this.db,
|
|
25788
|
+
() => {
|
|
25789
|
+
const result = this.claimStmt.run({
|
|
25790
|
+
pid,
|
|
25791
|
+
host,
|
|
25792
|
+
now: nowMs,
|
|
25793
|
+
staleBefore: nowMs - staleAfterMs
|
|
25794
|
+
});
|
|
25795
|
+
taken = result.changes === 1;
|
|
25796
|
+
},
|
|
25797
|
+
"IMMEDIATE"
|
|
25798
|
+
);
|
|
25799
|
+
return taken;
|
|
25800
|
+
}
|
|
25801
|
+
/** Say the holder is still alive. A no-op once the claim has moved on. */
|
|
25802
|
+
heartbeat(pid, nowMs) {
|
|
25803
|
+
this.heartbeatStmt.run({ now: nowMs, pid });
|
|
25804
|
+
}
|
|
25805
|
+
/** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
|
|
25806
|
+
release(pid) {
|
|
25807
|
+
this.releaseStmt.run({ pid });
|
|
25808
|
+
}
|
|
25809
|
+
/** Who holds the claim, if anyone. Read-only, for the same reason as above. */
|
|
25810
|
+
lease() {
|
|
25811
|
+
return getRow(this.leaseStmt);
|
|
25812
|
+
}
|
|
25813
|
+
};
|
|
25814
|
+
|
|
25815
|
+
// ../../packages/persistence/src/migrations.ts
|
|
25816
|
+
function describeObject(object2) {
|
|
25817
|
+
return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
|
|
25818
|
+
}
|
|
25819
|
+
function splitStatements(sql) {
|
|
25820
|
+
return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
|
|
25821
|
+
}
|
|
25822
|
+
function createdIndexName(statement) {
|
|
25823
|
+
const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
|
|
25824
|
+
return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
|
|
25825
|
+
}
|
|
25826
|
+
var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
|
|
25827
|
+
function applyMigrations(db, file2, options = {}) {
|
|
25828
|
+
const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
|
|
25829
|
+
db.exec(
|
|
25830
|
+
"CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
|
|
25831
|
+
);
|
|
25832
|
+
const applied = new Set(
|
|
25833
|
+
db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
|
|
25834
|
+
);
|
|
25835
|
+
const preLedgerStore = applied.size === 0 && legacyCount > 0;
|
|
25836
|
+
const record2 = db.prepare(
|
|
25837
|
+
"INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
|
|
25838
|
+
);
|
|
25839
|
+
for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
|
|
25840
|
+
if (applied.has(migration.tag)) continue;
|
|
25841
|
+
if (options.skipTags?.has(migration.tag) === true) continue;
|
|
25842
|
+
if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
|
|
25843
|
+
const evidence = evidenceObjects(migration.sql);
|
|
25844
|
+
const present = evidence.filter((o) => evidenceExists(db, o));
|
|
25845
|
+
if (present.length > 0 && present.length < evidence.length) {
|
|
25846
|
+
const missing = evidence.filter((o) => !present.includes(o));
|
|
25847
|
+
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.`;
|
|
25848
|
+
akaWarn(message);
|
|
25849
|
+
throw new Error(`[aka] ${message}`);
|
|
25850
|
+
}
|
|
25851
|
+
const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
|
|
25852
|
+
const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
|
|
25853
|
+
const statements = splitStatements(migration.sql);
|
|
25854
|
+
if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
|
|
25855
|
+
try {
|
|
25856
|
+
withTransaction(
|
|
25857
|
+
db,
|
|
25858
|
+
() => {
|
|
25859
|
+
for (const statement of statements) {
|
|
25860
|
+
const indexName = createdIndexName(statement);
|
|
25861
|
+
if (indexName === void 0) {
|
|
25862
|
+
if (alreadyApplied) continue;
|
|
25863
|
+
} else if (indexExists(db, indexName)) {
|
|
25864
|
+
continue;
|
|
25865
|
+
}
|
|
25866
|
+
db.exec(statement);
|
|
25867
|
+
}
|
|
25868
|
+
if (wantsFkOff && !alreadyApplied) {
|
|
25869
|
+
const violations = db.prepare("PRAGMA foreign_key_check").all();
|
|
25870
|
+
if (violations.length > 0) {
|
|
25871
|
+
throw new Error(
|
|
25872
|
+
`[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
|
|
25873
|
+
);
|
|
25874
|
+
}
|
|
25875
|
+
}
|
|
25876
|
+
record2.run(migration.tag, Date.now());
|
|
25877
|
+
},
|
|
25878
|
+
"IMMEDIATE"
|
|
25879
|
+
);
|
|
25880
|
+
} finally {
|
|
25881
|
+
if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
|
|
25882
|
+
}
|
|
25883
|
+
}
|
|
25884
|
+
if (legacyCount < SQLITE_MIGRATIONS.length) {
|
|
25885
|
+
db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
|
|
25886
|
+
}
|
|
25887
|
+
ensureSyncedAtColumn(db, "audit_events");
|
|
25888
|
+
ensureScanLedgerTable(db);
|
|
25889
|
+
ensureHistorySyncTable(db);
|
|
25890
|
+
ensureBlockedDetectionsTable(db);
|
|
25891
|
+
ensureRuleProbeCacheTable(db);
|
|
25892
|
+
ensureWriteGateTrigger(db);
|
|
25893
|
+
ensureTokenUsageColumns(db);
|
|
25894
|
+
reconcileSourceProjectIds(db);
|
|
25895
|
+
if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
|
|
25896
|
+
const drained = runLegacyHistoryBackfill(db);
|
|
25897
|
+
if (drained) applyLegacyDropMigration(db, file2);
|
|
25898
|
+
}
|
|
25899
|
+
}
|
|
25900
|
+
function readLegacyTables(db) {
|
|
25901
|
+
let holdsRows = false;
|
|
25902
|
+
const marks = [];
|
|
25903
|
+
for (const table of ["events", "findings"]) {
|
|
25904
|
+
try {
|
|
25905
|
+
const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
|
|
25906
|
+
if (row === void 0) {
|
|
25907
|
+
holdsRows = true;
|
|
25908
|
+
marks.push(`${table}:unreadable`);
|
|
25909
|
+
continue;
|
|
25910
|
+
}
|
|
25911
|
+
if (row.n > 0) holdsRows = true;
|
|
25912
|
+
marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
|
|
25913
|
+
} catch {
|
|
25914
|
+
holdsRows = true;
|
|
25915
|
+
marks.push(`${table}:unreadable`);
|
|
25916
|
+
}
|
|
25917
|
+
}
|
|
25918
|
+
return { holdsRows, mark: marks.join("|") };
|
|
25919
|
+
}
|
|
25920
|
+
function applyLegacyDropMigration(db, file2) {
|
|
25921
|
+
const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
|
|
25922
|
+
if (!migration) return;
|
|
25923
|
+
const before = file2 === void 0 ? void 0 : readLegacyTables(db);
|
|
25924
|
+
if (file2 !== void 0 && before?.holdsRows === true) {
|
|
25925
|
+
try {
|
|
25926
|
+
backupBeforeLegacyDrop(db, file2);
|
|
25927
|
+
} catch (error61) {
|
|
25928
|
+
akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
|
|
25929
|
+
return;
|
|
25930
|
+
}
|
|
25931
|
+
}
|
|
25932
|
+
try {
|
|
25933
|
+
withTransaction(
|
|
25934
|
+
db,
|
|
25935
|
+
() => {
|
|
25936
|
+
const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
|
|
25937
|
+
if (alreadyDropped) return;
|
|
25938
|
+
if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
|
|
25939
|
+
akaWarn(
|
|
25940
|
+
"legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
|
|
25941
|
+
);
|
|
25942
|
+
return;
|
|
25943
|
+
}
|
|
25944
|
+
for (const statement of splitStatements(migration.sql)) {
|
|
25945
|
+
db.exec(statement);
|
|
25946
|
+
}
|
|
25947
|
+
db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
|
|
24931
25948
|
migration.tag,
|
|
24932
25949
|
Date.now()
|
|
24933
25950
|
);
|
|
@@ -25228,10 +26245,62 @@ function ensureSyncedAtColumn(db, table) {
|
|
|
25228
26245
|
if (!columns.includes("outbox_owed")) {
|
|
25229
26246
|
db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
|
|
25230
26247
|
}
|
|
26248
|
+
if (!columns.includes("sync_failed_at")) {
|
|
26249
|
+
db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
|
|
26250
|
+
}
|
|
26251
|
+
if (!columns.includes("sync_failure")) {
|
|
26252
|
+
withTransaction(
|
|
26253
|
+
db,
|
|
26254
|
+
() => {
|
|
26255
|
+
db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
|
|
26256
|
+
db.exec(
|
|
26257
|
+
`UPDATE ${table} SET synced_at = NULL
|
|
26258
|
+
WHERE synced_at = -1
|
|
26259
|
+
AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
|
|
26260
|
+
);
|
|
26261
|
+
},
|
|
26262
|
+
"IMMEDIATE"
|
|
26263
|
+
);
|
|
26264
|
+
}
|
|
25231
26265
|
db.exec(
|
|
25232
|
-
`CREATE
|
|
25233
|
-
|
|
26266
|
+
`CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
|
|
26267
|
+
BEFORE UPDATE OF sync_failure ON ${table}
|
|
26268
|
+
WHEN ${syncFailureRejectCondition()}
|
|
26269
|
+
BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
|
|
25234
26270
|
);
|
|
26271
|
+
const syncIndexColumns = [
|
|
26272
|
+
"event_type",
|
|
26273
|
+
"synced_at",
|
|
26274
|
+
"sync_claimed_at",
|
|
26275
|
+
"started_at",
|
|
26276
|
+
// Appended LAST on purpose. The delivery-state read now projects it, so it
|
|
26277
|
+
// has to be in the index for the read to stay covered — but putting it
|
|
26278
|
+
// ahead of `started_at` would reorder the prefix the structural drain's
|
|
26279
|
+
// reads match on.
|
|
26280
|
+
"sync_failure"
|
|
26281
|
+
// `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
|
|
26282
|
+
//
|
|
26283
|
+
// The delivery-state read tests it — a capture's state depends on whether a
|
|
26284
|
+
// live forward marked it owed — so carrying it here makes that read covering
|
|
26285
|
+
// rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
|
|
26286
|
+
// But a sixth column changes what the planner charges for this index, and
|
|
26287
|
+
// with no ANALYZE statistics it plans from schema shape alone: measured, it
|
|
26288
|
+
// then stops choosing the per-session index for the token rollup and walks
|
|
26289
|
+
// every `llm_call` in the store through the event-type index instead. That
|
|
26290
|
+
// read grows with the store; this one does not.
|
|
26291
|
+
//
|
|
26292
|
+
// 40 ms on the largest store measured, once per render, is a cost worth
|
|
26293
|
+
// paying to leave every other read's plan where it was.
|
|
26294
|
+
];
|
|
26295
|
+
const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
|
|
26296
|
+
const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
|
|
26297
|
+
if (!syncIndexMatches) {
|
|
26298
|
+
db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
|
|
26299
|
+
db.exec(
|
|
26300
|
+
`CREATE INDEX idx_audit_events_sync
|
|
26301
|
+
ON audit_events (${syncIndexColumns.join(", ")})`
|
|
26302
|
+
);
|
|
26303
|
+
}
|
|
25235
26304
|
db.exec(
|
|
25236
26305
|
`CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
|
|
25237
26306
|
ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
|
|
@@ -25453,7 +26522,11 @@ function buildAuditEvent(row) {
|
|
|
25453
26522
|
link: linkParsed?.success ? linkParsed.data : null,
|
|
25454
26523
|
targetId: row.target_id,
|
|
25455
26524
|
internal: intToBool(row.internal),
|
|
25456
|
-
flagged: intToBool(row.flagged)
|
|
26525
|
+
flagged: intToBool(row.flagged),
|
|
26526
|
+
// Only meaningful when the title came out empty — a row whose body was
|
|
26527
|
+
// expired but whose title fell back to `tool_name` still has something to
|
|
26528
|
+
// render, and flagging it would make the view apologise for nothing.
|
|
26529
|
+
bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
|
|
25457
26530
|
};
|
|
25458
26531
|
}
|
|
25459
26532
|
var TIMELINE_COLUMNS = `
|
|
@@ -25461,6 +26534,7 @@ var TIMELINE_COLUMNS = `
|
|
|
25461
26534
|
event_type,
|
|
25462
26535
|
started_at,
|
|
25463
26536
|
coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
|
|
26537
|
+
content_expired_at,
|
|
25464
26538
|
coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
|
|
25465
26539
|
coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
|
|
25466
26540
|
json_extract(attributes, '$.severity') AS severity,
|
|
@@ -25587,7 +26661,8 @@ var SqliteActivityRepository = class {
|
|
|
25587
26661
|
SELECT 1 FROM audit_events d
|
|
25588
26662
|
WHERE d.root_session_id = audit_events.id
|
|
25589
26663
|
AND (d.content LIKE ? ESCAPE '\\'
|
|
25590
|
-
OR json_extract(d.attributes, '$.detail')
|
|
26664
|
+
OR coalesce(json_extract(d.attributes, '$.detail'),
|
|
26665
|
+
json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
|
|
25591
26666
|
);
|
|
25592
26667
|
params.push(pattern, pattern, pattern, pattern, pattern, pattern);
|
|
25593
26668
|
}
|
|
@@ -26125,6 +27200,88 @@ var SqliteAuditEventsRepository = class {
|
|
|
26125
27200
|
}
|
|
26126
27201
|
};
|
|
26127
27202
|
|
|
27203
|
+
// ../../packages/persistence/src/repositories/body-retention.ts
|
|
27204
|
+
var DEFAULT_BATCH_SIZE = 500;
|
|
27205
|
+
var DEFAULT_MAX_ROWS = 5e4;
|
|
27206
|
+
var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
|
|
27207
|
+
var SqliteBodyRetentionRepository = class {
|
|
27208
|
+
constructor(db) {
|
|
27209
|
+
this.db = db;
|
|
27210
|
+
const select = (laneClause) => `
|
|
27211
|
+
SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
|
|
27212
|
+
FROM audit_events
|
|
27213
|
+
WHERE content IS NOT NULL
|
|
27214
|
+
AND started_at < :cutoff
|
|
27215
|
+
AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
|
|
27216
|
+
${laneClause}
|
|
27217
|
+
ORDER BY started_at
|
|
27218
|
+
LIMIT :limit`;
|
|
27219
|
+
this.candidatesStmt = this.db.prepare(select(""));
|
|
27220
|
+
this.candidatesSyncSafeStmt = this.db.prepare(
|
|
27221
|
+
select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
|
|
27222
|
+
);
|
|
27223
|
+
this.heldBySyncStmt = this.db.prepare(`
|
|
27224
|
+
SELECT COUNT(*) AS n
|
|
27225
|
+
FROM audit_events
|
|
27226
|
+
WHERE content IS NOT NULL
|
|
27227
|
+
AND started_at < :cutoff
|
|
27228
|
+
AND event_type IN (${SYNC_LANE_TYPES_SQL})
|
|
27229
|
+
AND synced_at IS NULL`);
|
|
27230
|
+
this.expireStmt = this.db.prepare(
|
|
27231
|
+
`UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
|
|
27232
|
+
);
|
|
27233
|
+
}
|
|
27234
|
+
db;
|
|
27235
|
+
candidatesStmt;
|
|
27236
|
+
candidatesSyncSafeStmt;
|
|
27237
|
+
heldBySyncStmt;
|
|
27238
|
+
expireStmt;
|
|
27239
|
+
/** How many bytes a pass with these options would free, changing nothing. */
|
|
27240
|
+
preview(opts) {
|
|
27241
|
+
const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
|
|
27242
|
+
const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
|
|
27243
|
+
const rows = stmt.all({ cutoff: opts.cutoff, limit });
|
|
27244
|
+
return {
|
|
27245
|
+
rowsExpired: rows.length,
|
|
27246
|
+
bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
|
|
27247
|
+
rowsHeldBySync: this.countHeldBySync(opts)
|
|
27248
|
+
};
|
|
27249
|
+
}
|
|
27250
|
+
/** Clear eligible bodies, in bounded batches. */
|
|
27251
|
+
expire(opts) {
|
|
27252
|
+
const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
|
|
27253
|
+
const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
|
|
27254
|
+
const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
|
|
27255
|
+
let rowsExpired = 0;
|
|
27256
|
+
let bytesFreed = 0;
|
|
27257
|
+
let done = true;
|
|
27258
|
+
while (rowsExpired < maxRows) {
|
|
27259
|
+
const remaining = Math.min(batchSize, maxRows - rowsExpired);
|
|
27260
|
+
const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
|
|
27261
|
+
if (batch.length === 0) break;
|
|
27262
|
+
withTransaction(
|
|
27263
|
+
this.db,
|
|
27264
|
+
() => {
|
|
27265
|
+
for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
|
|
27266
|
+
},
|
|
27267
|
+
"IMMEDIATE"
|
|
27268
|
+
);
|
|
27269
|
+
rowsExpired += batch.length;
|
|
27270
|
+
bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
|
|
27271
|
+
if (batch.length < remaining) break;
|
|
27272
|
+
if (rowsExpired >= maxRows) {
|
|
27273
|
+
done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
|
|
27274
|
+
}
|
|
27275
|
+
}
|
|
27276
|
+
return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
|
|
27277
|
+
}
|
|
27278
|
+
countHeldBySync(opts) {
|
|
27279
|
+
if (opts.sweepSyncLane) return 0;
|
|
27280
|
+
const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
|
|
27281
|
+
return row.n;
|
|
27282
|
+
}
|
|
27283
|
+
};
|
|
27284
|
+
|
|
26128
27285
|
// ../../packages/persistence/src/repositories/classified-data.ts
|
|
26129
27286
|
var SqliteClassifiedDataRepository = class {
|
|
26130
27287
|
constructor(db) {
|
|
@@ -26925,23 +28082,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
|
|
|
26925
28082
|
)`;
|
|
26926
28083
|
|
|
26927
28084
|
// ../../packages/persistence/src/repositories/findings.ts
|
|
26928
|
-
var PREVIEW_INSTANCES_PER_GROUP = 200;
|
|
26929
|
-
var DEFAULT_LOCATIONS_LIMIT = 100;
|
|
26930
|
-
var LOCATION_RULE_IDS_CAP = 20;
|
|
26931
|
-
function compareLocationOrder(a, b) {
|
|
26932
|
-
return compareFindingGroupOrder(
|
|
26933
|
-
{
|
|
26934
|
-
severity: a.maxSeverity,
|
|
26935
|
-
latestDetectedAt: a.latestDetectedAt,
|
|
26936
|
-
id: ""
|
|
26937
|
-
},
|
|
26938
|
-
{
|
|
26939
|
-
severity: b.maxSeverity,
|
|
26940
|
-
latestDetectedAt: b.latestDetectedAt,
|
|
26941
|
-
id: ""
|
|
26942
|
-
}
|
|
26943
|
-
);
|
|
26944
|
-
}
|
|
26945
28085
|
var CONCAT_SEP = ",";
|
|
26946
28086
|
var TUPLE_SEP = "|";
|
|
26947
28087
|
function splitConcat(value) {
|
|
@@ -26970,7 +28110,15 @@ function toFlatFindingRow(r) {
|
|
|
26970
28110
|
...r.tool_name === null ? {} : { toolName: r.tool_name },
|
|
26971
28111
|
eventId: r.event_id,
|
|
26972
28112
|
...r.session_id === null ? {} : { sessionId: r.session_id },
|
|
26973
|
-
status: deriveInstanceStatus(r)
|
|
28113
|
+
status: deriveInstanceStatus(r),
|
|
28114
|
+
delivery: deriveFindingDelivery({
|
|
28115
|
+
kind: r.kind,
|
|
28116
|
+
syncedAt: r.synced_at,
|
|
28117
|
+
syncClaimedAt: r.sync_claimed_at,
|
|
28118
|
+
syncFailedAt: r.sync_failed_at,
|
|
28119
|
+
syncFailure: r.sync_failure,
|
|
28120
|
+
outboxOwed: r.outbox_owed
|
|
28121
|
+
})
|
|
26974
28122
|
};
|
|
26975
28123
|
}
|
|
26976
28124
|
function encodeGroupCursor(group) {
|
|
@@ -26993,13 +28141,51 @@ function decodeGroupCursor(cursor) {
|
|
|
26993
28141
|
return null;
|
|
26994
28142
|
}
|
|
26995
28143
|
function firstAfter(sorted, cursor) {
|
|
26996
|
-
const index = sorted.findIndex((
|
|
28144
|
+
const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
|
|
26997
28145
|
return index === -1 ? sorted.length : index;
|
|
26998
28146
|
}
|
|
26999
28147
|
function findDeepLinked(sorted, page, id) {
|
|
27000
|
-
if (page.some((
|
|
27001
|
-
return sorted.find((
|
|
28148
|
+
if (page.some((t) => t.id === id)) return void 0;
|
|
28149
|
+
return sorted.find((t) => t.id === id);
|
|
28150
|
+
}
|
|
28151
|
+
function encodeLocationCursor(location) {
|
|
28152
|
+
const payload = {
|
|
28153
|
+
sev: location.maxSeverity,
|
|
28154
|
+
t: location.latestDetectedAt,
|
|
28155
|
+
r: location.repo,
|
|
28156
|
+
f: location.file
|
|
28157
|
+
};
|
|
28158
|
+
return Buffer.from(JSON.stringify(payload)).toString("base64url");
|
|
28159
|
+
}
|
|
28160
|
+
function decodeLocationCursor(cursor) {
|
|
28161
|
+
const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
28162
|
+
if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
|
|
28163
|
+
return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
|
|
28164
|
+
}
|
|
28165
|
+
return null;
|
|
28166
|
+
}
|
|
28167
|
+
function firstLocationAfter(sorted, cursor) {
|
|
28168
|
+
const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
|
|
28169
|
+
return index === -1 ? sorted.length : index;
|
|
27002
28170
|
}
|
|
28171
|
+
function findDeepLinkedLocation(sorted, page, id) {
|
|
28172
|
+
if (page.some((l) => l.id === id)) return void 0;
|
|
28173
|
+
return sorted.find((l) => l.id === id);
|
|
28174
|
+
}
|
|
28175
|
+
var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
|
|
28176
|
+
d.severity AS severity, f.masked_match AS masked_match,
|
|
28177
|
+
f.action_taken AS action_taken, f.confidence AS confidence,
|
|
28178
|
+
e.started_at AS occurred_at,
|
|
28179
|
+
e.source_tool AS source_tool,
|
|
28180
|
+
e.repo AS repo,
|
|
28181
|
+
e.file_path AS file,
|
|
28182
|
+
e.tool_name AS tool_name,
|
|
28183
|
+
f.audit_event_id AS event_id, e.root_session_id AS session_id,
|
|
28184
|
+
e.event_type AS kind, f.finding_key AS finding_key,
|
|
28185
|
+
${latestResolutionStatusSql("f")} AS latest_status,
|
|
28186
|
+
e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
|
|
28187
|
+
e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
|
|
28188
|
+
e.outbox_owed AS outbox_owed`;
|
|
27003
28189
|
var DAY_MS3 = 864e5;
|
|
27004
28190
|
var SqliteFindingsRepository = class {
|
|
27005
28191
|
constructor(db) {
|
|
@@ -27120,30 +28306,26 @@ var SqliteFindingsRepository = class {
|
|
|
27120
28306
|
);
|
|
27121
28307
|
}
|
|
27122
28308
|
/**
|
|
27123
|
-
*
|
|
27124
|
-
*
|
|
27125
|
-
*
|
|
27126
|
-
*
|
|
27127
|
-
*
|
|
27128
|
-
*
|
|
27129
|
-
*
|
|
27130
|
-
*
|
|
27131
|
-
*
|
|
27132
|
-
*
|
|
27133
|
-
*
|
|
27134
|
-
*
|
|
28309
|
+
* Finding TYPES for the dashboard — one row per rule, scoped to the four
|
|
28310
|
+
* capture kinds (audit_events also holds structural/reconciler/scan rows this
|
|
28311
|
+
* list must never surface), with per-filter-excluded facets, the requested
|
|
28312
|
+
* filters applied, and sorted by severity then recency. Filtering and faceting
|
|
28313
|
+
* run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
|
|
28314
|
+
* full filtered set; `items` is the requested page (default 50), keyset-paged.
|
|
28315
|
+
* Under a `status` filter, `totals.findings` counts only findings whose
|
|
28316
|
+
* derived status was requested.
|
|
28317
|
+
*
|
|
28318
|
+
* ONE read, which materializes no findings: a single aggregate per rule_id,
|
|
28319
|
+
* folding EVERY finding into the numbers a type row and the filters need
|
|
28320
|
+
* (count, severity, category, providers, actions, statuses, latest, search
|
|
28321
|
+
* text). The findings OF a type come from listFindingInstances scoped to
|
|
28322
|
+
* `subtype`, so neither list bounds the other and no per-type cap exists.
|
|
27135
28323
|
*
|
|
27136
|
-
* Two reads, neither of which materializes a row per finding:
|
|
27137
|
-
* 1. one aggregate row per rule_id, folding EVERY instance into the numbers
|
|
27138
|
-
* the group and the filters need (count, providers, actions, statuses,
|
|
27139
|
-
* latest, search text);
|
|
27140
|
-
* 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
|
|
27141
|
-
* populate `instances` for the table's expanded rows.
|
|
27142
28324
|
* The aggregates carry raw DB values and are translated by the same
|
|
27143
|
-
* @akasecurity/schema mappers
|
|
27144
|
-
* rule is ever restated in SQL.
|
|
28325
|
+
* @akasecurity/schema mappers every other path uses, so no enum mapping or
|
|
28326
|
+
* status rule is ever restated in SQL.
|
|
27145
28327
|
*/
|
|
27146
|
-
|
|
28328
|
+
listFindingTypes(query) {
|
|
27147
28329
|
const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
|
|
27148
28330
|
const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
|
|
27149
28331
|
const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
|
|
@@ -27156,12 +28338,7 @@ var SqliteFindingsRepository = class {
|
|
|
27156
28338
|
predicate,
|
|
27157
28339
|
params: sessionParams
|
|
27158
28340
|
});
|
|
27159
|
-
const
|
|
27160
|
-
sessionId: query.sessionId,
|
|
27161
|
-
from: query.from
|
|
27162
|
-
});
|
|
27163
|
-
const groupable = rows.map(toFlatFindingRow);
|
|
27164
|
-
const allGroups = buildFindingGroups(groupable, { aggregates });
|
|
28341
|
+
const allTypes = buildFindingTypes(aggregates);
|
|
27165
28342
|
const filterOpts = {
|
|
27166
28343
|
severity: query.severity,
|
|
27167
28344
|
providers: query.provider,
|
|
@@ -27170,30 +28347,25 @@ var SqliteFindingsRepository = class {
|
|
|
27170
28347
|
subtype: query.subtype,
|
|
27171
28348
|
q: query.q
|
|
27172
28349
|
};
|
|
27173
|
-
const facets = computeFindingFacets(
|
|
27174
|
-
const sorted =
|
|
28350
|
+
const facets = computeFindingFacets(allTypes, filterOpts);
|
|
28351
|
+
const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
|
|
27175
28352
|
const statusFilter = query.status ?? [];
|
|
27176
28353
|
const totals = {
|
|
27177
|
-
findings: sorted.reduce((acc,
|
|
27178
|
-
if (statusFilter.length === 0) return acc +
|
|
27179
|
-
const agg = aggregates.get(
|
|
27180
|
-
return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ??
|
|
28354
|
+
findings: sorted.reduce((acc, t) => {
|
|
28355
|
+
if (statusFilter.length === 0) return acc + t.instanceCount;
|
|
28356
|
+
const agg = aggregates.get(t.id);
|
|
28357
|
+
return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
|
|
27181
28358
|
}, 0),
|
|
27182
|
-
|
|
28359
|
+
types: sorted.length
|
|
27183
28360
|
};
|
|
27184
|
-
const limit = query.limit ??
|
|
28361
|
+
const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
|
|
27185
28362
|
const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
|
|
27186
28363
|
const start = cursor === null ? 0 : firstAfter(sorted, cursor);
|
|
27187
28364
|
const page = sorted.slice(start, start + limit);
|
|
27188
28365
|
const lastOnPage = page.at(-1);
|
|
27189
28366
|
const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
|
|
27190
28367
|
const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
|
|
27191
|
-
const
|
|
27192
|
-
const narrow = (g) => statusSet ? {
|
|
27193
|
-
...g,
|
|
27194
|
-
instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
|
|
27195
|
-
} : g;
|
|
27196
|
-
const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
|
|
28368
|
+
const items = [...page, ...deepLinked ? [deepLinked] : []];
|
|
27197
28369
|
return Promise.resolve({
|
|
27198
28370
|
totals,
|
|
27199
28371
|
facets,
|
|
@@ -27204,7 +28376,7 @@ var SqliteFindingsRepository = class {
|
|
|
27204
28376
|
}
|
|
27205
28377
|
/**
|
|
27206
28378
|
* One row per rule_id, folding EVERY instance of the group into the values
|
|
27207
|
-
*
|
|
28379
|
+
* buildFindingTypes cannot recover from an aggregate. Bounded by the number of
|
|
27208
28380
|
* distinct rule_ids (the installed packs' rules), not by the store's size.
|
|
27209
28381
|
*
|
|
27210
28382
|
* A single scan, folded in two levels: the inner SELECT groups by
|
|
@@ -27258,6 +28430,7 @@ var SqliteFindingsRepository = class {
|
|
|
27258
28430
|
providers: query.provider,
|
|
27259
28431
|
actions: query.action,
|
|
27260
28432
|
statuses: query.status,
|
|
28433
|
+
deliveries: query.deployment,
|
|
27261
28434
|
tools: query.tool,
|
|
27262
28435
|
repo: query.repo,
|
|
27263
28436
|
file: query.file,
|
|
@@ -27298,13 +28471,25 @@ var SqliteFindingsRepository = class {
|
|
|
27298
28471
|
});
|
|
27299
28472
|
}
|
|
27300
28473
|
/**
|
|
27301
|
-
* The same findings folded by
|
|
28474
|
+
* The same findings folded by WHERE they live — one row per (repo, file) pair.
|
|
27302
28475
|
*
|
|
27303
28476
|
* The grouping keys come from the capturing event's attributes, which is what
|
|
27304
|
-
* the local store relates a finding to
|
|
27305
|
-
*
|
|
27306
|
-
* empty-string bucket, which
|
|
27307
|
-
*
|
|
28477
|
+
* the local store relates a finding to; there is no finding↔asset row to group
|
|
28478
|
+
* by instead. A repo or file the event did not record folds into the
|
|
28479
|
+
* empty-string bucket, which is a real location like any other: it is listed,
|
|
28480
|
+
* it is selectable, and its `?loc=` token is as good as any other row's.
|
|
28481
|
+
*
|
|
28482
|
+
* ONE flat list rather than repos nesting files. A rollup can only be paged by
|
|
28483
|
+
* repo, which leaves the file list inside it unbounded — the shape the by-type
|
|
28484
|
+
* list was rebuilt to remove — and two-level pagination inside an
|
|
28485
|
+
* expand/collapse table is what pushed that view to master/detail in the first
|
|
28486
|
+
* place.
|
|
28487
|
+
*
|
|
28488
|
+
* Every filter narrows the FINDINGS and the locations fall out of what
|
|
28489
|
+
* survives, so each row's `instanceCount` is exactly what listFindingInstances
|
|
28490
|
+
* reports for the same filters scoped to that pair. The view depends on it:
|
|
28491
|
+
* one toolbar sits over both panels precisely because a location owns none of
|
|
28492
|
+
* its fields.
|
|
27308
28493
|
*/
|
|
27309
28494
|
listFindingLocations(query) {
|
|
27310
28495
|
const opts = {
|
|
@@ -27313,16 +28498,20 @@ var SqliteFindingsRepository = class {
|
|
|
27313
28498
|
providers: query.provider,
|
|
27314
28499
|
actions: query.action,
|
|
27315
28500
|
statuses: query.status,
|
|
28501
|
+
deliveries: query.deployment,
|
|
27316
28502
|
tools: query.tool,
|
|
27317
28503
|
q: query.q
|
|
27318
28504
|
};
|
|
27319
|
-
const limit = query.limit ??
|
|
28505
|
+
const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
|
|
28506
|
+
const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
|
|
27320
28507
|
const byRepo = /* @__PURE__ */ new Map();
|
|
28508
|
+
const accumulator = createInstanceFacetAccumulator(opts);
|
|
27321
28509
|
let total = 0;
|
|
27322
28510
|
for (const row of this.scanFindingRows({
|
|
27323
28511
|
sessionId: query.sessionId,
|
|
27324
28512
|
from: query.from
|
|
27325
28513
|
})) {
|
|
28514
|
+
accumulator.add(row);
|
|
27326
28515
|
if (!matchesInstanceFilters(row, opts)) continue;
|
|
27327
28516
|
total += 1;
|
|
27328
28517
|
let files = byRepo.get(row.repo);
|
|
@@ -27337,103 +28526,35 @@ var SqliteFindingsRepository = class {
|
|
|
27337
28526
|
}
|
|
27338
28527
|
addToLocation(acc, row);
|
|
27339
28528
|
}
|
|
27340
|
-
|
|
27341
|
-
const
|
|
27342
|
-
|
|
27343
|
-
|
|
27344
|
-
|
|
27345
|
-
|
|
27346
|
-
|
|
27347
|
-
|
|
27348
|
-
|
|
27349
|
-
|
|
27350
|
-
|
|
27351
|
-
|
|
27352
|
-
|
|
27353
|
-
|
|
27354
|
-
|
|
27355
|
-
|
|
27356
|
-
|
|
27357
|
-
|
|
27358
|
-
|
|
27359
|
-
|
|
27360
|
-
|
|
27361
|
-
|
|
27362
|
-
);
|
|
27363
|
-
const statuses = fileRows.map((f) => f.status);
|
|
27364
|
-
const folded = foldGroupStatus(statuses);
|
|
27365
|
-
return {
|
|
27366
|
-
repo,
|
|
27367
|
-
instanceCount: rollup.instanceCount,
|
|
27368
|
-
maxSeverity: rollup.maxSeverity,
|
|
27369
|
-
latestDetectedAt: rollup.latestDetectedAt,
|
|
27370
|
-
...folded === void 0 ? {} : { status: folded },
|
|
27371
|
-
files: fileRows
|
|
27372
|
-
};
|
|
27373
|
-
});
|
|
27374
|
-
repos.sort(compareLocationOrder);
|
|
28529
|
+
const sorted = [];
|
|
28530
|
+
for (const [repo, files] of byRepo) {
|
|
28531
|
+
for (const [file2, acc] of files) {
|
|
28532
|
+
const status = foldGroupStatus(acc.statuses);
|
|
28533
|
+
sorted.push({
|
|
28534
|
+
id: encodeLocationId(repo, file2),
|
|
28535
|
+
repo,
|
|
28536
|
+
file: file2,
|
|
28537
|
+
instanceCount: acc.instanceCount,
|
|
28538
|
+
maxSeverity: acc.maxSeverity,
|
|
28539
|
+
latestDetectedAt: acc.latestDetectedAt,
|
|
28540
|
+
...status === void 0 ? {} : { status },
|
|
28541
|
+
ruleIds: [...acc.ruleIds]
|
|
28542
|
+
});
|
|
28543
|
+
}
|
|
28544
|
+
}
|
|
28545
|
+
sorted.sort(compareLocationOrder);
|
|
28546
|
+
const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
|
|
28547
|
+
const page = sorted.slice(start, start + limit);
|
|
28548
|
+
const lastOnPage = page.at(-1);
|
|
28549
|
+
const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
|
|
28550
|
+
const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
|
|
27375
28551
|
return Promise.resolve({
|
|
27376
|
-
totals: { findings: total,
|
|
27377
|
-
|
|
27378
|
-
|
|
28552
|
+
totals: { findings: total, locations: sorted.length },
|
|
28553
|
+
facets: accumulator.facets(),
|
|
28554
|
+
items: [...page, ...deepLinked ? [deepLinked] : []],
|
|
28555
|
+
nextCursor
|
|
27379
28556
|
});
|
|
27380
28557
|
}
|
|
27381
|
-
/**
|
|
27382
|
-
* Each group's newest instances, for the table's expanded rows.
|
|
27383
|
-
*
|
|
27384
|
-
* ONE index-ordered scan with early termination, and the shape is the point.
|
|
27385
|
-
* The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
|
|
27386
|
-
* started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
|
|
27387
|
-
* through a temp B-tree to keep a bounded preview of each group, and then
|
|
27388
|
-
* sorts the survivors again for the page order. Both sorts grow with the
|
|
27389
|
-
* store while the answer does not.
|
|
27390
|
-
*
|
|
27391
|
-
* Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
|
|
27392
|
-
* (or the session or window index the scope names — see `findingScanSql`),
|
|
27393
|
-
* which is already the order the page wants, and keeps rows per rule until
|
|
27394
|
-
* each rule has as many as it can show. The aggregate the caller already holds
|
|
27395
|
-
* says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
|
|
27396
|
-
* per rule, summed, is the number of rows this scan has to find, and it stops
|
|
27397
|
-
* on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
|
|
27398
|
-
* (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
|
|
27399
|
-
* store with many firing rules widens it. The bound that DOES hold
|
|
27400
|
-
* unconditionally is the sorted form's floor: this scan visits at most as
|
|
27401
|
-
* many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
|
|
27402
|
-
* sorted, and stops the moment every rule has its cap, where the sorted form
|
|
27403
|
-
* sorts the whole scope regardless. The true worst case — the rarest rule's
|
|
27404
|
-
* wanted instances sitting at the tail of the scope — is one pass over
|
|
27405
|
-
* everything in scope with a block sort of the id tie-break only, never a
|
|
27406
|
-
* sort of the scope, which is still that floor.
|
|
27407
|
-
*
|
|
27408
|
-
* A row whose rule the aggregate did not see is skipped: the two statements
|
|
27409
|
-
* run without a shared snapshot, so a capture landing between them can add a
|
|
27410
|
-
* rule here that has no counts there, and the counts are what the group is
|
|
27411
|
-
* built from.
|
|
27412
|
-
*/
|
|
27413
|
-
previewRows(aggregates, scope) {
|
|
27414
|
-
const wanted = /* @__PURE__ */ new Map();
|
|
27415
|
-
let remaining = 0;
|
|
27416
|
-
for (const [ruleId, agg] of aggregates) {
|
|
27417
|
-
const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
|
|
27418
|
-
wanted.set(ruleId, n);
|
|
27419
|
-
remaining += n;
|
|
27420
|
-
}
|
|
27421
|
-
const rows = [];
|
|
27422
|
-
if (remaining === 0) return rows;
|
|
27423
|
-
const { sql, params } = this.findingScanSql(scope);
|
|
27424
|
-
const taken = /* @__PURE__ */ new Map();
|
|
27425
|
-
for (const r of iterateRows(this.db.prepare(sql), params)) {
|
|
27426
|
-
const want = wanted.get(r.rule_id);
|
|
27427
|
-
if (want === void 0) continue;
|
|
27428
|
-
const have = taken.get(r.rule_id) ?? 0;
|
|
27429
|
-
if (have >= want) continue;
|
|
27430
|
-
taken.set(r.rule_id, have + 1);
|
|
27431
|
-
rows.push(r);
|
|
27432
|
-
remaining -= 1;
|
|
27433
|
-
if (remaining === 0) break;
|
|
27434
|
-
}
|
|
27435
|
-
return rows;
|
|
27436
|
-
}
|
|
27437
28558
|
/**
|
|
27438
28559
|
* Every finding in scope as a FlatFindingRow, newest first, streamed.
|
|
27439
28560
|
*
|
|
@@ -27460,6 +28581,33 @@ var SqliteFindingsRepository = class {
|
|
|
27460
28581
|
yield toFlatFindingRow(r);
|
|
27461
28582
|
}
|
|
27462
28583
|
}
|
|
28584
|
+
/**
|
|
28585
|
+
* One finding by its own id, or null when no such row exists.
|
|
28586
|
+
*
|
|
28587
|
+
* A primary-key seek on `inspection_findings`, so its cost does not grow with
|
|
28588
|
+
* the store — and, unlike anything derived from a list page, it resolves a
|
|
28589
|
+
* finding of ANY age. That is what the Findings page's one-shot `?finding=`
|
|
28590
|
+
* deep link needs: the id it carries may name a finding thousands of rows
|
|
28591
|
+
* older than anything a first page holds.
|
|
28592
|
+
*
|
|
28593
|
+
* Deliberately UNFILTERED — no capture-kind, session or time predicate. It
|
|
28594
|
+
* RESOLVES an id; whether that row would survive the list's current filters is
|
|
28595
|
+
* a different question, and hiding the target because a filter excludes it is
|
|
28596
|
+
* worse than showing it.
|
|
28597
|
+
*
|
|
28598
|
+
* `groupId` on the result IS the rule id, so this one read answers both "which
|
|
28599
|
+
* type should the list select?" and "what does the drawer show?".
|
|
28600
|
+
*/
|
|
28601
|
+
findingInstance(id) {
|
|
28602
|
+
const row = this.db.prepare(
|
|
28603
|
+
`SELECT ${FINDING_ROW_COLUMNS_SQL}
|
|
28604
|
+
FROM inspection_findings f
|
|
28605
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
28606
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
28607
|
+
WHERE f.id = ?`
|
|
28608
|
+
).get(id);
|
|
28609
|
+
return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
|
|
28610
|
+
}
|
|
27463
28611
|
/**
|
|
27464
28612
|
* The one statement both instance-level scans run: every finding in scope,
|
|
27465
28613
|
* joined to its event and definition, newest first.
|
|
@@ -27493,17 +28641,7 @@ var SqliteFindingsRepository = class {
|
|
|
27493
28641
|
conditions.push("e.started_at >= ?");
|
|
27494
28642
|
params.push(isoToEpochMillis(scope.from));
|
|
27495
28643
|
}
|
|
27496
|
-
const sql = `SELECT
|
|
27497
|
-
d.severity AS severity, f.masked_match AS masked_match,
|
|
27498
|
-
f.action_taken AS action_taken, f.confidence AS confidence,
|
|
27499
|
-
e.started_at AS occurred_at,
|
|
27500
|
-
e.source_tool AS source_tool,
|
|
27501
|
-
e.repo AS repo,
|
|
27502
|
-
e.file_path AS file,
|
|
27503
|
-
e.tool_name AS tool_name,
|
|
27504
|
-
f.audit_event_id AS event_id, e.root_session_id AS session_id,
|
|
27505
|
-
e.event_type AS kind, f.finding_key AS finding_key,
|
|
27506
|
-
${latestResolutionStatusSql("f")} AS latest_status
|
|
28644
|
+
const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
|
|
27507
28645
|
FROM audit_events e
|
|
27508
28646
|
CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
|
|
27509
28647
|
CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
@@ -27517,6 +28655,26 @@ var SqliteFindingsRepository = class {
|
|
|
27517
28655
|
group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
|
|
27518
28656
|
const rows = this.db.prepare(
|
|
27519
28657
|
`SELECT rule_id,
|
|
28658
|
+
-- BARE columns beside max(latest_at), which is deliberate and
|
|
28659
|
+
-- is SQLite's documented behaviour: with a single min()/max()
|
|
28660
|
+
-- in an aggregate query, every bare column takes its value from
|
|
28661
|
+
-- the row that produced the extremum. So these are the severity
|
|
28662
|
+
-- and category of the definition whose finding is NEWEST, which
|
|
28663
|
+
-- is what the row-based build they replaced read off its first
|
|
28664
|
+
-- (newest-first) row.
|
|
28665
|
+
--
|
|
28666
|
+
-- min() is WRONG here and was the defect: inspection_definitions
|
|
28667
|
+
-- holds one row per rule VERSION (see its writer \u2014 a version bump
|
|
28668
|
+
-- mints a new row), so a rule whose severity moved between
|
|
28669
|
+
-- versions has several, and min() picks the ALPHABETICALLY
|
|
28670
|
+
-- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
|
|
28671
|
+
-- That is arbitrary in direction, and it feeds the badge, the
|
|
28672
|
+
-- filter, the facet counts and the primary sort key.
|
|
28673
|
+
--
|
|
28674
|
+
-- Adding a second min()/max() aggregate here would make these
|
|
28675
|
+
-- bare columns ambiguous again; keep max(latest_at) the only one.
|
|
28676
|
+
severity,
|
|
28677
|
+
category,
|
|
27520
28678
|
sum(tuple_count) AS instance_count,
|
|
27521
28679
|
max(latest_at) AS latest_at,
|
|
27522
28680
|
group_concat(source_tools) AS source_tools,
|
|
@@ -27527,6 +28685,14 @@ var SqliteFindingsRepository = class {
|
|
|
27527
28685
|
group_concat(tool_names) AS tool_names
|
|
27528
28686
|
FROM (
|
|
27529
28687
|
SELECT d.rule_id AS rule_id,
|
|
28688
|
+
-- Severity and category are columns of the DEFINITION, and
|
|
28689
|
+
-- a rule can have SEVERAL definitions (one per version), so
|
|
28690
|
+
-- these are grouped on below and resolved to the newest
|
|
28691
|
+
-- firing version by the outer query's bare-column select.
|
|
28692
|
+
-- They ride the aggregate because the type build has no rows
|
|
28693
|
+
-- to read them off \u2014 see buildFindingTypes.
|
|
28694
|
+
d.severity AS severity,
|
|
28695
|
+
d.category AS category,
|
|
27530
28696
|
e.event_type || '${TUPLE_SEP}' ||
|
|
27531
28697
|
(CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
|
|
27532
28698
|
coalesce(latest.status, '') AS status_tuple,
|
|
@@ -27541,7 +28707,7 @@ var SqliteFindingsRepository = class {
|
|
|
27541
28707
|
LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
|
|
27542
28708
|
ON latest.finding_key = f.finding_key
|
|
27543
28709
|
${scope.predicate}
|
|
27544
|
-
GROUP BY d.rule_id, status_tuple
|
|
28710
|
+
GROUP BY d.rule_id, d.severity, d.category, status_tuple
|
|
27545
28711
|
)
|
|
27546
28712
|
GROUP BY rule_id`
|
|
27547
28713
|
).all(scope.params);
|
|
@@ -27550,6 +28716,8 @@ var SqliteFindingsRepository = class {
|
|
|
27550
28716
|
r.rule_id,
|
|
27551
28717
|
{
|
|
27552
28718
|
instanceCount: r.instance_count,
|
|
28719
|
+
severity: r.severity,
|
|
28720
|
+
category: r.category,
|
|
27553
28721
|
sourceTools: splitConcat(r.source_tools),
|
|
27554
28722
|
actionsTaken: splitConcat(r.actions_taken),
|
|
27555
28723
|
statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
|
|
@@ -27566,7 +28734,7 @@ var SqliteFindingsRepository = class {
|
|
|
27566
28734
|
latestDetectedAt: epochMillisToIso(r.latest_at),
|
|
27567
28735
|
// Free text only — joined and substring-matched, so group_concat's
|
|
27568
28736
|
// commas need no unpicking (a repo/path containing one still matches).
|
|
27569
|
-
// Left undefined (not '') when unfetched, so
|
|
28737
|
+
// Left undefined (not '') when unfetched, so buildFindingTypes can
|
|
27570
28738
|
// tell "no q this request" from "a group with no repo/file at all"
|
|
27571
28739
|
// and skip priming a haystack nothing will read.
|
|
27572
28740
|
...withSearchText ? {
|
|
@@ -27594,7 +28762,9 @@ var SqliteFindingsRepository = class {
|
|
|
27594
28762
|
)
|
|
27595
28763
|
);
|
|
27596
28764
|
for (const row of grouped) {
|
|
27597
|
-
if (
|
|
28765
|
+
if (Object.hasOwn(byAction, row.action_taken)) {
|
|
28766
|
+
byAction[row.action_taken] = row.c;
|
|
28767
|
+
}
|
|
27598
28768
|
}
|
|
27599
28769
|
const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
|
|
27600
28770
|
const sevRows = allRows(
|
|
@@ -27611,7 +28781,9 @@ var SqliteFindingsRepository = class {
|
|
|
27611
28781
|
)
|
|
27612
28782
|
);
|
|
27613
28783
|
for (const row of sevRows) {
|
|
27614
|
-
if (
|
|
28784
|
+
if (Object.hasOwn(bySeverity, row.severity)) {
|
|
28785
|
+
bySeverity[row.severity] = row.c;
|
|
28786
|
+
}
|
|
27615
28787
|
}
|
|
27616
28788
|
const categories = ENFORCEABLE_CATEGORIES;
|
|
27617
28789
|
const enabledRows = allRows(
|
|
@@ -27660,469 +28832,6 @@ function isoDay(ms) {
|
|
|
27660
28832
|
return new Date(ms).toISOString().slice(0, 10);
|
|
27661
28833
|
}
|
|
27662
28834
|
|
|
27663
|
-
// ../../packages/persistence/src/repositories/history-sync.ts
|
|
27664
|
-
var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
|
|
27665
|
-
var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
27666
|
-
var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
|
|
27667
|
-
var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
27668
|
-
var SKIPPED = -1;
|
|
27669
|
-
var ROW_COLUMNS = `id,
|
|
27670
|
-
parent_id AS parentId,
|
|
27671
|
-
root_session_id AS rootSessionId,
|
|
27672
|
-
event_type AS eventType,
|
|
27673
|
-
host_id AS hostId,
|
|
27674
|
-
harness_id AS harnessId,
|
|
27675
|
-
source_project_id AS sourceProjectId,
|
|
27676
|
-
started_at AS startedAt,
|
|
27677
|
-
ended_at AS endedAt,
|
|
27678
|
-
severity,
|
|
27679
|
-
priority,
|
|
27680
|
-
content,
|
|
27681
|
-
content_hash AS contentHash,
|
|
27682
|
-
attributes`;
|
|
27683
|
-
var SqliteHistorySyncRepository = class {
|
|
27684
|
-
constructor(db) {
|
|
27685
|
-
this.db = db;
|
|
27686
|
-
this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
|
|
27687
|
-
this.sessionsStmt = db.prepare(
|
|
27688
|
-
`SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
|
|
27689
|
-
FROM audit_events
|
|
27690
|
-
WHERE synced_at IS NULL
|
|
27691
|
-
AND event_type IN (${TYPE_LIST})
|
|
27692
|
-
AND started_at < :before
|
|
27693
|
-
GROUP BY sessionId
|
|
27694
|
-
ORDER BY earliest
|
|
27695
|
-
LIMIT :limit`
|
|
27696
|
-
);
|
|
27697
|
-
this.rowsStmt = db.prepare(
|
|
27698
|
-
`SELECT ${ROW_COLUMNS}
|
|
27699
|
-
FROM audit_events
|
|
27700
|
-
WHERE synced_at IS NULL
|
|
27701
|
-
AND event_type IN (${TYPE_LIST})
|
|
27702
|
-
AND started_at < :before
|
|
27703
|
-
AND COALESCE(root_session_id, id) = :sessionId
|
|
27704
|
-
ORDER BY (event_type = 'session') DESC, started_at
|
|
27705
|
-
LIMIT :limit`
|
|
27706
|
-
);
|
|
27707
|
-
this.captureRowsStmt = db.prepare(
|
|
27708
|
-
`SELECT ${ROW_COLUMNS}
|
|
27709
|
-
FROM audit_events
|
|
27710
|
-
WHERE synced_at IS NULL
|
|
27711
|
-
AND sync_claimed_at IS NULL
|
|
27712
|
-
AND outbox_owed = 1
|
|
27713
|
-
AND event_type IN (${CAPTURE_TYPE_LIST})
|
|
27714
|
-
AND started_at < :before
|
|
27715
|
-
ORDER BY started_at
|
|
27716
|
-
LIMIT :limit`
|
|
27717
|
-
);
|
|
27718
|
-
this.markOwedStmt = db.prepare(
|
|
27719
|
-
`UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
|
|
27720
|
-
);
|
|
27721
|
-
this.stampStmt = db.prepare(
|
|
27722
|
-
`UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
|
|
27723
|
-
);
|
|
27724
|
-
this.claimRowStmt = db.prepare(
|
|
27725
|
-
`UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
|
|
27726
|
-
);
|
|
27727
|
-
this.releaseRowStmt = db.prepare(
|
|
27728
|
-
`UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
|
|
27729
|
-
);
|
|
27730
|
-
this.releaseStaleClaimsStmt = db.prepare(
|
|
27731
|
-
`UPDATE audit_events SET sync_claimed_at = NULL
|
|
27732
|
-
WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
|
|
27733
|
-
);
|
|
27734
|
-
this.partitionStmt = db.prepare(
|
|
27735
|
-
`SELECT
|
|
27736
|
-
SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
|
|
27737
|
-
SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
|
|
27738
|
-
SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
|
|
27739
|
-
SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
|
|
27740
|
-
COUNT(*) AS total
|
|
27741
|
-
FROM audit_events
|
|
27742
|
-
WHERE event_type IN (${TYPE_LIST})`
|
|
27743
|
-
);
|
|
27744
|
-
this.countsStmt = db.prepare(
|
|
27745
|
-
`SELECT
|
|
27746
|
-
SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
|
|
27747
|
-
SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
|
|
27748
|
-
SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
|
|
27749
|
-
FROM audit_events
|
|
27750
|
-
WHERE event_type IN (${TYPE_LIST})`
|
|
27751
|
-
);
|
|
27752
|
-
this.captureSkipCountStmt = db.prepare(
|
|
27753
|
-
`SELECT COUNT(*) AS skipped
|
|
27754
|
-
FROM audit_events
|
|
27755
|
-
WHERE synced_at = ${String(SKIPPED)}
|
|
27756
|
-
AND event_type IN (${CAPTURE_TYPE_LIST})`
|
|
27757
|
-
);
|
|
27758
|
-
this.fingerprintStmt = db.prepare(
|
|
27759
|
-
`SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
|
|
27760
|
-
FROM history_sync WHERE id = 1`
|
|
27761
|
-
);
|
|
27762
|
-
this.setFingerprintStmt = db.prepare(
|
|
27763
|
-
`UPDATE history_sync
|
|
27764
|
-
SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
|
|
27765
|
-
WHERE id = 1`
|
|
27766
|
-
);
|
|
27767
|
-
this.disownCapturesStmt = db.prepare(
|
|
27768
|
-
`UPDATE audit_events SET outbox_owed = NULL
|
|
27769
|
-
WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
|
|
27770
|
-
);
|
|
27771
|
-
this.rearmStmt = db.prepare(
|
|
27772
|
-
`UPDATE audit_events SET synced_at = NULL
|
|
27773
|
-
WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
|
|
27774
|
-
);
|
|
27775
|
-
this.claimStmt = db.prepare(
|
|
27776
|
-
`UPDATE history_sync
|
|
27777
|
-
SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
|
|
27778
|
-
WHERE id = 1
|
|
27779
|
-
AND (owner_pid IS NULL
|
|
27780
|
-
OR heartbeat_at IS NULL
|
|
27781
|
-
OR heartbeat_at < :staleBefore
|
|
27782
|
-
OR heartbeat_at > :now)`
|
|
27783
|
-
);
|
|
27784
|
-
this.heartbeatStmt = db.prepare(
|
|
27785
|
-
`UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
|
|
27786
|
-
);
|
|
27787
|
-
this.releaseStmt = db.prepare(
|
|
27788
|
-
`UPDATE history_sync
|
|
27789
|
-
SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
|
|
27790
|
-
WHERE id = 1 AND owner_pid = :pid`
|
|
27791
|
-
);
|
|
27792
|
-
this.closeWindowStmt = db.prepare(
|
|
27793
|
-
`UPDATE audit_events SET synced_at = :at
|
|
27794
|
-
WHERE synced_at IS NULL
|
|
27795
|
-
AND event_type IN (${TYPE_LIST})
|
|
27796
|
-
AND started_at >= :attachedAt`
|
|
27797
|
-
);
|
|
27798
|
-
this.releaseBoundaryStmt = db.prepare(
|
|
27799
|
-
`UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
|
|
27800
|
-
);
|
|
27801
|
-
this.freezeBoundaryStmt = db.prepare(
|
|
27802
|
-
`UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
|
|
27803
|
-
);
|
|
27804
|
-
this.leaseStmt = db.prepare(
|
|
27805
|
-
`SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
|
|
27806
|
-
acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
|
|
27807
|
-
FROM history_sync WHERE id = 1`
|
|
27808
|
-
);
|
|
27809
|
-
this.inspectionsStmt = db.prepare(
|
|
27810
|
-
`SELECT d.rule_id AS ruleId,
|
|
27811
|
-
d.name AS ruleName,
|
|
27812
|
-
d.version AS ruleVersion,
|
|
27813
|
-
d.category AS category,
|
|
27814
|
-
d.severity AS severity,
|
|
27815
|
-
f.span_start AS spanStart,
|
|
27816
|
-
f.span_end AS spanEnd,
|
|
27817
|
-
f.masked_match AS maskedMatch,
|
|
27818
|
-
f.action_taken AS actionTaken,
|
|
27819
|
-
f.confidence AS confidence
|
|
27820
|
-
FROM inspection_findings f
|
|
27821
|
-
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
27822
|
-
WHERE f.audit_event_id = :auditEventId
|
|
27823
|
-
ORDER BY f.span_start, f.id`
|
|
27824
|
-
);
|
|
27825
|
-
}
|
|
27826
|
-
db;
|
|
27827
|
-
ensureRowStmt;
|
|
27828
|
-
sessionsStmt;
|
|
27829
|
-
rowsStmt;
|
|
27830
|
-
stampStmt;
|
|
27831
|
-
countsStmt;
|
|
27832
|
-
fingerprintStmt;
|
|
27833
|
-
setFingerprintStmt;
|
|
27834
|
-
rearmStmt;
|
|
27835
|
-
claimStmt;
|
|
27836
|
-
heartbeatStmt;
|
|
27837
|
-
releaseStmt;
|
|
27838
|
-
leaseStmt;
|
|
27839
|
-
inspectionsStmt;
|
|
27840
|
-
closeWindowStmt;
|
|
27841
|
-
releaseBoundaryStmt;
|
|
27842
|
-
freezeBoundaryStmt;
|
|
27843
|
-
captureRowsStmt;
|
|
27844
|
-
markOwedStmt;
|
|
27845
|
-
captureSkipCountStmt;
|
|
27846
|
-
disownCapturesStmt;
|
|
27847
|
-
partitionStmt;
|
|
27848
|
-
claimRowStmt;
|
|
27849
|
-
releaseRowStmt;
|
|
27850
|
-
releaseStaleClaimsStmt;
|
|
27851
|
-
/**
|
|
27852
|
-
* The masked detections recorded against one tool call.
|
|
27853
|
-
*
|
|
27854
|
-
* These travel with the event because a tool call's target is not
|
|
27855
|
-
* re-inspectable from the event alone — unlike a capture, where the text
|
|
27856
|
-
* itself is re-scannable. What crosses is the masked match and the rule that
|
|
27857
|
-
* produced it, never the value.
|
|
27858
|
-
*/
|
|
27859
|
-
inspectionsFor(auditEventId) {
|
|
27860
|
-
return allRows(this.inspectionsStmt, { auditEventId });
|
|
27861
|
-
}
|
|
27862
|
-
/**
|
|
27863
|
-
* Sessions with structural rows still to send, oldest first.
|
|
27864
|
-
*
|
|
27865
|
-
* BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
|
|
27866
|
-
* read. Anything recorded after the machine attached is the live forward
|
|
27867
|
-
* path's to deliver; this drain exists for what was recorded before it, and a
|
|
27868
|
-
* row both paths send is at best a duplicate request and at worst — for a
|
|
27869
|
-
* session root — an overwrite of the inventory ids the live path resolved.
|
|
27870
|
-
*/
|
|
27871
|
-
pendingSessions(limit, before) {
|
|
27872
|
-
return allRows(this.sessionsStmt, { limit, before }).map(
|
|
27873
|
-
(r) => r.sessionId
|
|
27874
|
-
);
|
|
27875
|
-
}
|
|
27876
|
-
/** One session's undelivered structural rows within the backlog, root first. */
|
|
27877
|
-
pendingRows(sessionId, limit, before) {
|
|
27878
|
-
return allRows(this.rowsStmt, { sessionId, limit, before });
|
|
27879
|
-
}
|
|
27880
|
-
/**
|
|
27881
|
-
* Captures this machine still owes the deployment, oldest first.
|
|
27882
|
-
*
|
|
27883
|
-
* Selected by the `outbox_owed` marker the attached forward path writes, not
|
|
27884
|
-
* by a time window — see captureRowsStmt for why a window could not express
|
|
27885
|
-
* this. `before` is the grace window that leaves a just-recorded capture to
|
|
27886
|
-
* the live path.
|
|
27887
|
-
*/
|
|
27888
|
-
pendingCaptureRows(limit, before) {
|
|
27889
|
-
return allRows(this.captureRowsStmt, { limit, before });
|
|
27890
|
-
}
|
|
27891
|
-
/**
|
|
27892
|
-
* Record that a capture is OWED to the deployment.
|
|
27893
|
-
*
|
|
27894
|
-
* Written by the attached forward path when a live send did not confirm
|
|
27895
|
-
* delivery, and read by the drain as the whole of its eligibility test. It is
|
|
27896
|
-
* a fact rather than an inference: the machine was attached, the send did not
|
|
27897
|
-
* land, so the row is owed — which no time window can state, because the same
|
|
27898
|
-
* window that holds the rows a past attachment left owed also holds every
|
|
27899
|
-
* capture recorded while the machine was DETACHED, and those were never
|
|
27900
|
-
* offered to anyone.
|
|
27901
|
-
*
|
|
27902
|
-
* Idempotent, and never un-set: `markSynced` settling the row is what takes it
|
|
27903
|
-
* out of the drain's read.
|
|
27904
|
-
*/
|
|
27905
|
-
markCaptureOwed(id) {
|
|
27906
|
-
this.markOwedStmt.run({ id });
|
|
27907
|
-
}
|
|
27908
|
-
/** Record delivery. Called only AFTER the far side has accepted the rows. */
|
|
27909
|
-
markSynced(ids, atMs) {
|
|
27910
|
-
this.stampAll(ids, atMs);
|
|
27911
|
-
}
|
|
27912
|
-
/**
|
|
27913
|
-
* Record that a row will never be sent.
|
|
27914
|
-
*
|
|
27915
|
-
* Reserved for a local defect — a row that cannot be rebuilt into a valid
|
|
27916
|
-
* payload. A row that merely failed to reach the deployment stays NULL, so it
|
|
27917
|
-
* is retried; marking those would turn one outage into permanent data loss.
|
|
27918
|
-
*/
|
|
27919
|
-
markSkipped(ids) {
|
|
27920
|
-
this.stampAll(ids, SKIPPED);
|
|
27921
|
-
}
|
|
27922
|
-
eachInTransaction(ids, run) {
|
|
27923
|
-
if (ids.length === 0) return;
|
|
27924
|
-
withTransaction(
|
|
27925
|
-
this.db,
|
|
27926
|
-
() => {
|
|
27927
|
-
for (const id of ids) run(id);
|
|
27928
|
-
},
|
|
27929
|
-
"IMMEDIATE"
|
|
27930
|
-
);
|
|
27931
|
-
}
|
|
27932
|
-
stampAll(ids, value) {
|
|
27933
|
-
if (ids.length === 0) return;
|
|
27934
|
-
withTransaction(
|
|
27935
|
-
this.db,
|
|
27936
|
-
() => {
|
|
27937
|
-
for (const id of ids) this.stampStmt.run({ at: value, id });
|
|
27938
|
-
},
|
|
27939
|
-
"IMMEDIATE"
|
|
27940
|
-
);
|
|
27941
|
-
}
|
|
27942
|
-
/**
|
|
27943
|
-
* Claim rows as in-flight.
|
|
27944
|
-
*
|
|
27945
|
-
* Advisory in exactly the sense the lease is: it records that a send is in
|
|
27946
|
-
* progress so a surface can say so, and a lost claim costs a row showing as
|
|
27947
|
-
* queued while it is actually being sent. It is not exclusion — the far side
|
|
27948
|
-
* settles a duplicate on the row id.
|
|
27949
|
-
*/
|
|
27950
|
-
claimRows(ids, atMs) {
|
|
27951
|
-
this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
|
|
27952
|
-
}
|
|
27953
|
-
/** Give back a claim without settling — the send failed, the row is queued again. */
|
|
27954
|
-
releaseRows(ids) {
|
|
27955
|
-
this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
|
|
27956
|
-
}
|
|
27957
|
-
/**
|
|
27958
|
-
* Clear claims older than `staleBefore`, and report how many were cleared.
|
|
27959
|
-
*
|
|
27960
|
-
* A process killed between claiming and settling leaves rows claimed with
|
|
27961
|
-
* nothing left to settle them. Without this they read as "sending" for ever.
|
|
27962
|
-
*/
|
|
27963
|
-
releaseStaleClaims(staleBefore) {
|
|
27964
|
-
return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
|
|
27965
|
-
}
|
|
27966
|
-
/**
|
|
27967
|
-
* Every tracked row in exactly one delivery state.
|
|
27968
|
-
*
|
|
27969
|
-
* Takes no boundary on purpose. The boundary answers "what should the drain
|
|
27970
|
-
* pick up now", which is a different question from "what state is this row
|
|
27971
|
-
* in" — and a machine that has never attached has no boundary to pass, so
|
|
27972
|
-
* requiring one would force a caller to invent one and report the whole store
|
|
27973
|
-
* as queued.
|
|
27974
|
-
*/
|
|
27975
|
-
partition() {
|
|
27976
|
-
const row = getRow(this.partitionStmt, {});
|
|
27977
|
-
return {
|
|
27978
|
-
queued: row?.queued ?? 0,
|
|
27979
|
-
inProgress: row?.inProgress ?? 0,
|
|
27980
|
-
synced: row?.synced ?? 0,
|
|
27981
|
-
failed: row?.failed ?? 0,
|
|
27982
|
-
total: row?.total ?? 0
|
|
27983
|
-
};
|
|
27984
|
-
}
|
|
27985
|
-
/** `pending` counts only what is inside the backlog; sent and skipped are totals. */
|
|
27986
|
-
counts(before) {
|
|
27987
|
-
const row = getRow(
|
|
27988
|
-
this.countsStmt,
|
|
27989
|
-
{ before }
|
|
27990
|
-
);
|
|
27991
|
-
const captures = getRow(this.captureSkipCountStmt);
|
|
27992
|
-
return {
|
|
27993
|
-
pending: row?.pending ?? 0,
|
|
27994
|
-
sent: row?.sent ?? 0,
|
|
27995
|
-
skipped: row?.skipped ?? 0,
|
|
27996
|
-
capturesSkipped: captures?.skipped ?? 0
|
|
27997
|
-
};
|
|
27998
|
-
}
|
|
27999
|
-
/**
|
|
28000
|
-
* The deployment the current stamps were made against, and where its backlog
|
|
28001
|
-
* ends.
|
|
28002
|
-
*
|
|
28003
|
-
* READ-ONLY. An absent row reads as an absent deployment, which is what a
|
|
28004
|
-
* machine that has never drained is — and every writer below seeds the row
|
|
28005
|
-
* before it needs one, so nothing depends on this creating it. Keeping the
|
|
28006
|
-
* write off the gate path matters because the gate runs on every pass while a
|
|
28007
|
-
* write has to take the database's write lock.
|
|
28008
|
-
*/
|
|
28009
|
-
deployment() {
|
|
28010
|
-
const row = getRow(
|
|
28011
|
-
this.fingerprintStmt
|
|
28012
|
-
);
|
|
28013
|
-
return {
|
|
28014
|
-
fingerprint: row?.fingerprint ?? void 0,
|
|
28015
|
-
backlogBefore: row?.backlogBefore ?? void 0
|
|
28016
|
-
};
|
|
28017
|
-
}
|
|
28018
|
-
/**
|
|
28019
|
-
* Point the ledger at a different deployment, discarding what it recorded
|
|
28020
|
-
* about the previous one.
|
|
28021
|
-
*
|
|
28022
|
-
* Delivery is a fact about ONE recipient: rows sent to the deployment a
|
|
28023
|
-
* machine has just left are undelivered as far as the new one is concerned.
|
|
28024
|
-
* All three in one transaction, so a crash between them cannot leave stamps
|
|
28025
|
-
* attributed to the wrong deployment, or a boundary that belongs to another.
|
|
28026
|
-
*
|
|
28027
|
-
* The boundary is written HERE and only here, which is what freezes it: a
|
|
28028
|
-
* re-attach to the SAME deployment (a key rotation) leaves the fingerprint
|
|
28029
|
-
* unchanged, so this never runs and the backlog does not widen back over rows
|
|
28030
|
-
* the live path has since delivered.
|
|
28031
|
-
*/
|
|
28032
|
-
rearmFor(fingerprint, backlogBefore) {
|
|
28033
|
-
this.ensureRowStmt.run();
|
|
28034
|
-
withTransaction(
|
|
28035
|
-
this.db,
|
|
28036
|
-
() => {
|
|
28037
|
-
const previous = getRow(this.fingerprintStmt)?.fingerprint;
|
|
28038
|
-
this.rearmStmt.run();
|
|
28039
|
-
if (previous !== null && previous !== void 0 && previous !== fingerprint) {
|
|
28040
|
-
this.disownCapturesStmt.run();
|
|
28041
|
-
}
|
|
28042
|
-
this.setFingerprintStmt.run({ fingerprint, backlogBefore });
|
|
28043
|
-
},
|
|
28044
|
-
"IMMEDIATE"
|
|
28045
|
-
);
|
|
28046
|
-
}
|
|
28047
|
-
/**
|
|
28048
|
-
* End the attached period: hand its rows to the live path, and release the
|
|
28049
|
-
* boundary so the next attachment can freeze a new one.
|
|
28050
|
-
*
|
|
28051
|
-
* WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
|
|
28052
|
-
* nothing delivers. The fingerprint is unchanged, so the boundary is never
|
|
28053
|
-
* re-frozen and stays at the FIRST attachment — while nothing forwards at all
|
|
28054
|
-
* during the detached period, because the machine is not attached. Rows
|
|
28055
|
-
* recorded in that window sit after the boundary and before the re-attach, so
|
|
28056
|
-
* neither path takes them, and the pending count reports none outstanding.
|
|
28057
|
-
*
|
|
28058
|
-
* Stamping the attached window is not a claim that every one of those rows
|
|
28059
|
-
* reached the deployment — the live path drops on failure and says so
|
|
28060
|
-
* elsewhere. It records that they were ITS to deliver, which is exactly the
|
|
28061
|
-
* status quo: they sit outside the frozen boundary today and are equally never
|
|
28062
|
-
* re-sent. Making it explicit is what lets the boundary move.
|
|
28063
|
-
*
|
|
28064
|
-
* ONE TRANSACTION, so a crash cannot release the boundary while leaving the
|
|
28065
|
-
* window unstamped — that half-state would re-send the whole attached period
|
|
28066
|
-
* on the next attach, which is the failure the boundary exists to prevent.
|
|
28067
|
-
*/
|
|
28068
|
-
closeAttachedWindow(attachedAtMs, atMs) {
|
|
28069
|
-
this.ensureRowStmt.run();
|
|
28070
|
-
withTransaction(
|
|
28071
|
-
this.db,
|
|
28072
|
-
() => {
|
|
28073
|
-
const row = getRow(this.fingerprintStmt);
|
|
28074
|
-
const from = row?.backlogBefore ?? attachedAtMs;
|
|
28075
|
-
this.closeWindowStmt.run({ at: atMs, attachedAt: from });
|
|
28076
|
-
this.releaseBoundaryStmt.run();
|
|
28077
|
-
},
|
|
28078
|
-
"IMMEDIATE"
|
|
28079
|
-
);
|
|
28080
|
-
}
|
|
28081
|
-
/**
|
|
28082
|
-
* Freeze a boundary for the deployment already on file, KEEPING the stamps.
|
|
28083
|
-
*
|
|
28084
|
-
* The re-attach half of the above. Distinct from `rearmFor`, which is for a
|
|
28085
|
-
* different deployment and therefore discards what was delivered to the old
|
|
28086
|
-
* one: here the recipient is the same, so everything already sent to it stays
|
|
28087
|
-
* sent.
|
|
28088
|
-
*/
|
|
28089
|
-
freezeBoundary(backlogBefore) {
|
|
28090
|
-
this.ensureRowStmt.run();
|
|
28091
|
-
this.freezeBoundaryStmt.run({ backlogBefore });
|
|
28092
|
-
}
|
|
28093
|
-
/** Take the claim, or report that someone live already holds it. */
|
|
28094
|
-
claim(pid, host, nowMs, staleAfterMs) {
|
|
28095
|
-
this.ensureRowStmt.run();
|
|
28096
|
-
let taken = false;
|
|
28097
|
-
withTransaction(
|
|
28098
|
-
this.db,
|
|
28099
|
-
() => {
|
|
28100
|
-
const result = this.claimStmt.run({
|
|
28101
|
-
pid,
|
|
28102
|
-
host,
|
|
28103
|
-
now: nowMs,
|
|
28104
|
-
staleBefore: nowMs - staleAfterMs
|
|
28105
|
-
});
|
|
28106
|
-
taken = result.changes === 1;
|
|
28107
|
-
},
|
|
28108
|
-
"IMMEDIATE"
|
|
28109
|
-
);
|
|
28110
|
-
return taken;
|
|
28111
|
-
}
|
|
28112
|
-
/** Say the holder is still alive. A no-op once the claim has moved on. */
|
|
28113
|
-
heartbeat(pid, nowMs) {
|
|
28114
|
-
this.heartbeatStmt.run({ now: nowMs, pid });
|
|
28115
|
-
}
|
|
28116
|
-
/** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
|
|
28117
|
-
release(pid) {
|
|
28118
|
-
this.releaseStmt.run({ pid });
|
|
28119
|
-
}
|
|
28120
|
-
/** Who holds the claim, if anyone. Read-only, for the same reason as above. */
|
|
28121
|
-
lease() {
|
|
28122
|
-
return getRow(this.leaseStmt);
|
|
28123
|
-
}
|
|
28124
|
-
};
|
|
28125
|
-
|
|
28126
28835
|
// ../../packages/persistence/src/repositories/inspection-definitions.ts
|
|
28127
28836
|
var SqliteInspectionDefinitionsRepository = class {
|
|
28128
28837
|
constructor(db) {
|
|
@@ -28317,7 +29026,8 @@ function managedSettingsPaths(platform2 = process.platform) {
|
|
|
28317
29026
|
}
|
|
28318
29027
|
return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
|
|
28319
29028
|
}
|
|
28320
|
-
|
|
29029
|
+
var testOnlyManagedPaths = null;
|
|
29030
|
+
function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
|
|
28321
29031
|
for (const path of paths) {
|
|
28322
29032
|
let text;
|
|
28323
29033
|
try {
|
|
@@ -28352,6 +29062,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
|
|
|
28352
29062
|
if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
|
|
28353
29063
|
if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
|
|
28354
29064
|
if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
|
|
29065
|
+
if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
|
|
28355
29066
|
if (values.vaultConsent !== void 0) {
|
|
28356
29067
|
merged.vaultConsent = values.vaultConsent ? (
|
|
28357
29068
|
// Keep an existing valid grant so its acknowledgedAt survives; mint one
|
|
@@ -30797,7 +31508,7 @@ function toUtcDateString(ms) {
|
|
|
30797
31508
|
return new Date(ms).toISOString().slice(0, 10);
|
|
30798
31509
|
}
|
|
30799
31510
|
function isTimeseriesSeverity(s) {
|
|
30800
|
-
return s === "critical" || s === "high" || s === "medium";
|
|
31511
|
+
return s === "critical" || s === "high" || s === "medium" || s === "low";
|
|
30801
31512
|
}
|
|
30802
31513
|
var SqliteSecurityRepository = class {
|
|
30803
31514
|
constructor(db, now = () => Date.now()) {
|
|
@@ -30859,7 +31570,7 @@ var SqliteSecurityRepository = class {
|
|
|
30859
31570
|
ELSE 0
|
|
30860
31571
|
END) AS open_at_rest
|
|
30861
31572
|
FROM inspection_findings f
|
|
30862
|
-
JOIN audit_events e ON e.id = f.audit_event_id
|
|
31573
|
+
JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
|
|
30863
31574
|
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
30864
31575
|
LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
|
|
30865
31576
|
ON latest.finding_key = f.finding_key
|
|
@@ -30926,12 +31637,16 @@ var SqliteSecurityRepository = class {
|
|
|
30926
31637
|
const now = this.now();
|
|
30927
31638
|
const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
|
|
30928
31639
|
const rows = this.findingsInRange(windowStart, now);
|
|
30929
|
-
const points = Array.from(
|
|
30930
|
-
|
|
30931
|
-
|
|
30932
|
-
|
|
30933
|
-
|
|
30934
|
-
|
|
31640
|
+
const points = Array.from(
|
|
31641
|
+
{ length: numBuckets },
|
|
31642
|
+
(_, i) => ({
|
|
31643
|
+
timestamp: toUtcDateString(windowStart + i * bucketMs),
|
|
31644
|
+
critical: 0,
|
|
31645
|
+
high: 0,
|
|
31646
|
+
medium: 0,
|
|
31647
|
+
low: 0
|
|
31648
|
+
})
|
|
31649
|
+
);
|
|
30935
31650
|
for (const r of rows) {
|
|
30936
31651
|
const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
|
|
30937
31652
|
const bucket = points[idx];
|
|
@@ -31081,7 +31796,7 @@ var SqliteSecurityRepository = class {
|
|
|
31081
31796
|
this.db.prepare(
|
|
31082
31797
|
`SELECT e.repo AS repo, count(*) AS c
|
|
31083
31798
|
FROM inspection_findings f
|
|
31084
|
-
JOIN audit_events e ON e.id = f.audit_event_id
|
|
31799
|
+
JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
|
|
31085
31800
|
WHERE e.started_at >= :from AND e.started_at < :to
|
|
31086
31801
|
AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
|
|
31087
31802
|
AND e.repo IS NOT NULL
|
|
@@ -31149,6 +31864,7 @@ var SqliteSecurityRepository = class {
|
|
|
31149
31864
|
`SELECT f.finding_key AS finding_key,
|
|
31150
31865
|
d.rule_id AS rule_id,
|
|
31151
31866
|
d.severity AS severity,
|
|
31867
|
+
e.repo AS repo,
|
|
31152
31868
|
e.file_path AS path,
|
|
31153
31869
|
COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
|
|
31154
31870
|
latest.resolved_at AS latest_resolved_at
|
|
@@ -31168,6 +31884,7 @@ var SqliteSecurityRepository = class {
|
|
|
31168
31884
|
const items = rows.map((r) => ({
|
|
31169
31885
|
findingKey: r.finding_key,
|
|
31170
31886
|
ruleId: r.rule_id,
|
|
31887
|
+
repo: r.repo ?? "",
|
|
31171
31888
|
severity: r.severity,
|
|
31172
31889
|
path: r.path ?? "",
|
|
31173
31890
|
resolvedAt: new Date(r.latest_resolved_at).toISOString(),
|
|
@@ -31177,15 +31894,68 @@ var SqliteSecurityRepository = class {
|
|
|
31177
31894
|
}));
|
|
31178
31895
|
return Promise.resolve({ items });
|
|
31179
31896
|
}
|
|
31897
|
+
/**
|
|
31898
|
+
* Per-rule tallies of the findings that are still OPEN, whole-store.
|
|
31899
|
+
*
|
|
31900
|
+
* Scoped by status rather than by time, because the card this feeds is a to-do
|
|
31901
|
+
* list: a secret committed three weeks ago and never rotated is still the most
|
|
31902
|
+
* important thing to fix, and any window hides it. It carried a "newest N
|
|
31903
|
+
* findings" cap and then a range; the first meant a different span on every
|
|
31904
|
+
* machine, and the second reported "no recommendations" over live exposure.
|
|
31905
|
+
*
|
|
31906
|
+
* `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
|
|
31907
|
+
* so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
|
|
31908
|
+
* is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
|
|
31909
|
+
* dismissal is a judgement, not a remediation) and drops untracked legacy rows.
|
|
31910
|
+
* The two answer different questions and only this one has to match a link.
|
|
31911
|
+
*
|
|
31912
|
+
* Aggregated in SQL: the result is O(distinct rule × category × severity), so a
|
|
31913
|
+
* whole-store scope costs a grouped scan rather than a row per finding.
|
|
31914
|
+
*/
|
|
31915
|
+
recommendationInputs() {
|
|
31916
|
+
const rows = allRows(
|
|
31917
|
+
this.db.prepare(
|
|
31918
|
+
`SELECT d.rule_id AS rule_id,
|
|
31919
|
+
d.category AS category,
|
|
31920
|
+
d.severity AS severity,
|
|
31921
|
+
COUNT(*) AS count
|
|
31922
|
+
FROM inspection_findings f
|
|
31923
|
+
JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
|
|
31924
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
31925
|
+
LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
|
|
31926
|
+
ON latest.finding_key = f.finding_key
|
|
31927
|
+
WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
|
|
31928
|
+
AND e.event_type = 'code_change'
|
|
31929
|
+
AND (
|
|
31930
|
+
f.finding_key IS NULL
|
|
31931
|
+
OR latest.status IS NULL
|
|
31932
|
+
OR latest.status NOT IN ('resolved', 'dismissed')
|
|
31933
|
+
)
|
|
31934
|
+
GROUP BY d.rule_id, d.category, d.severity`
|
|
31935
|
+
)
|
|
31936
|
+
);
|
|
31937
|
+
return Promise.resolve(
|
|
31938
|
+
rows.map((r) => ({
|
|
31939
|
+
ruleId: r.rule_id,
|
|
31940
|
+
category: r.category,
|
|
31941
|
+
severity: r.severity,
|
|
31942
|
+
count: r.count
|
|
31943
|
+
}))
|
|
31944
|
+
);
|
|
31945
|
+
}
|
|
31180
31946
|
// Findings whose parent event occurred in [fromMs, toMs), with the parent's
|
|
31181
31947
|
// epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
|
|
31182
31948
|
// numeric and the JS aggregations bucket/split on ms directly.
|
|
31183
31949
|
findingsInRange(fromMs, toMs) {
|
|
31184
31950
|
const rows = allRows(
|
|
31185
31951
|
this.db.prepare(
|
|
31186
|
-
`
|
|
31952
|
+
// `rule_id`/`category` cost nothing extra: inspection_definitions is already
|
|
31953
|
+
// joined for `severity`, so they are two more columns off a row this read
|
|
31954
|
+
// already fetches. They feed the recommended-actions rollup.
|
|
31955
|
+
`SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
|
|
31956
|
+
d.rule_id AS rule_id, d.category AS category
|
|
31187
31957
|
FROM inspection_findings f
|
|
31188
|
-
JOIN audit_events e ON e.id = f.audit_event_id
|
|
31958
|
+
JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
|
|
31189
31959
|
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
31190
31960
|
WHERE e.started_at >= :from AND e.started_at < :to
|
|
31191
31961
|
AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
|
|
@@ -31196,7 +31966,9 @@ var SqliteSecurityRepository = class {
|
|
|
31196
31966
|
return rows.map((r) => ({
|
|
31197
31967
|
occurredAt: r.occurred_at,
|
|
31198
31968
|
severity: r.severity,
|
|
31199
|
-
actionTaken: r.action_taken
|
|
31969
|
+
actionTaken: r.action_taken,
|
|
31970
|
+
ruleId: r.rule_id,
|
|
31971
|
+
category: r.category
|
|
31200
31972
|
}));
|
|
31201
31973
|
}
|
|
31202
31974
|
};
|
|
@@ -32024,6 +32796,7 @@ function openWithPragmas(file2) {
|
|
|
32024
32796
|
db.exec("PRAGMA journal_mode = WAL");
|
|
32025
32797
|
db.exec("PRAGMA busy_timeout = 2000");
|
|
32026
32798
|
db.exec("PRAGMA foreign_keys = ON");
|
|
32799
|
+
registerSqlFunctions(db);
|
|
32027
32800
|
} catch (err) {
|
|
32028
32801
|
closeQuietly(db);
|
|
32029
32802
|
throw err;
|
|
@@ -32053,7 +32826,7 @@ function backupLegacyStore(db, file2) {
|
|
|
32053
32826
|
discardStore(file2, backup);
|
|
32054
32827
|
return backup;
|
|
32055
32828
|
}
|
|
32056
|
-
function openAndInitialize(file2, base) {
|
|
32829
|
+
function openAndInitialize(file2, base, skipTags) {
|
|
32057
32830
|
let db = openWithPragmas(file2);
|
|
32058
32831
|
try {
|
|
32059
32832
|
if (isForeignSqliteLineage(db)) {
|
|
@@ -32063,7 +32836,7 @@ function openAndInitialize(file2, base) {
|
|
|
32063
32836
|
`Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
|
|
32064
32837
|
);
|
|
32065
32838
|
}
|
|
32066
|
-
applyMigrations(db, file2);
|
|
32839
|
+
applyMigrations(db, file2, { skipTags });
|
|
32067
32840
|
tightenPerms(file2);
|
|
32068
32841
|
const policies = new SqlitePoliciesRepository(db);
|
|
32069
32842
|
const installedPacks = new SqliteInstalledPacksRepository(db, base);
|
|
@@ -32078,6 +32851,7 @@ function openAndInitialize(file2, base) {
|
|
|
32078
32851
|
exceptions: new SqliteExceptionsRepository(db),
|
|
32079
32852
|
resolutions: new SqliteResolutionsRepository(db),
|
|
32080
32853
|
ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
|
|
32854
|
+
bodyRetention: new SqliteBodyRetentionRepository(db),
|
|
32081
32855
|
security: new SqliteSecurityRepository(db),
|
|
32082
32856
|
detections: new SqliteDetectionsRepository(db),
|
|
32083
32857
|
shares: new SqliteSharesRepository(db),
|
|
@@ -32100,7 +32874,8 @@ function openAndInitialize(file2, base) {
|
|
|
32100
32874
|
throw err;
|
|
32101
32875
|
}
|
|
32102
32876
|
}
|
|
32103
|
-
|
|
32877
|
+
var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
|
|
32878
|
+
function openLocalDatabase(dir, options = {}) {
|
|
32104
32879
|
ensureDataDirSync(dir);
|
|
32105
32880
|
const file2 = join7(dir, DB_FILENAME);
|
|
32106
32881
|
reapStalePartials(file2);
|
|
@@ -32112,6 +32887,7 @@ function openLocalDatabase(dir) {
|
|
|
32112
32887
|
installedPacks,
|
|
32113
32888
|
scanLedger,
|
|
32114
32889
|
historySync,
|
|
32890
|
+
bodyRetention,
|
|
32115
32891
|
secretVault,
|
|
32116
32892
|
exceptions,
|
|
32117
32893
|
resolutions,
|
|
@@ -32135,7 +32911,8 @@ function openLocalDatabase(dir) {
|
|
|
32135
32911
|
// `dir` is always `<base>/data` — every caller resolves it through
|
|
32136
32912
|
// `dataDir()` — so its parent is the `~/.aka` base the layout splits into
|
|
32137
32913
|
// settings/ and data/, and the pack-policy floor needs both halves.
|
|
32138
|
-
dirname2(dir)
|
|
32914
|
+
dirname2(dir),
|
|
32915
|
+
options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
|
|
32139
32916
|
);
|
|
32140
32917
|
function captureRowId(event) {
|
|
32141
32918
|
return captureId(
|
|
@@ -32328,6 +33105,7 @@ function openLocalDatabase(dir) {
|
|
|
32328
33105
|
installedPacks,
|
|
32329
33106
|
scanLedger,
|
|
32330
33107
|
historySync,
|
|
33108
|
+
bodyRetention,
|
|
32331
33109
|
secretVault,
|
|
32332
33110
|
exceptions,
|
|
32333
33111
|
resolutions,
|
|
@@ -32366,6 +33144,70 @@ function openLocalDatabase(dir) {
|
|
|
32366
33144
|
};
|
|
32367
33145
|
}
|
|
32368
33146
|
|
|
33147
|
+
// ../../packages/persistence/src/egress-wire.ts
|
|
33148
|
+
import { createHash as createHash3 } from "crypto";
|
|
33149
|
+
var PROJECT_KEY_DIGEST_VERSION = "v2";
|
|
33150
|
+
var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
|
|
33151
|
+
var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
|
|
33152
|
+
var FILE_URL = /^file:\/\//i;
|
|
33153
|
+
var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
|
|
33154
|
+
var SLASH = "/".charCodeAt(0);
|
|
33155
|
+
var GIT_SUFFIX = ".git";
|
|
33156
|
+
function trimSlashes(path) {
|
|
33157
|
+
let start = 0;
|
|
33158
|
+
let end = path.length;
|
|
33159
|
+
while (start < end && path.charCodeAt(start) === SLASH) start += 1;
|
|
33160
|
+
while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
|
|
33161
|
+
return path.slice(start, end);
|
|
33162
|
+
}
|
|
33163
|
+
function canonicalGitUrl(url2) {
|
|
33164
|
+
const trimmed = url2.trim();
|
|
33165
|
+
if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
|
|
33166
|
+
const scheme = SCHEME_FORM.exec(trimmed);
|
|
33167
|
+
const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
|
|
33168
|
+
const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
|
|
33169
|
+
if (host === void 0) return trimmed;
|
|
33170
|
+
const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
|
|
33171
|
+
const bare = trimSlashes(path);
|
|
33172
|
+
const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
|
|
33173
|
+
return cleaned === "" ? host : `${host}/${cleaned}`;
|
|
33174
|
+
}
|
|
33175
|
+
function hashProjectKey(projectKey) {
|
|
33176
|
+
const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
|
|
33177
|
+
return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
|
|
33178
|
+
}
|
|
33179
|
+
function toIngestHit(hit) {
|
|
33180
|
+
return {
|
|
33181
|
+
host: hit.host,
|
|
33182
|
+
kind: hit.kind,
|
|
33183
|
+
name: hit.name,
|
|
33184
|
+
category: hit.category,
|
|
33185
|
+
trust: hit.trust,
|
|
33186
|
+
network: hit.network,
|
|
33187
|
+
method: hit.method,
|
|
33188
|
+
transport: hit.transport,
|
|
33189
|
+
url: hit.url,
|
|
33190
|
+
template: hit.template,
|
|
33191
|
+
dataClass: hit.dataClass,
|
|
33192
|
+
site: {
|
|
33193
|
+
file: hit.site.file,
|
|
33194
|
+
line: hit.site.line,
|
|
33195
|
+
dynamic: hit.site.dynamic,
|
|
33196
|
+
vendored: hit.site.vendored
|
|
33197
|
+
}
|
|
33198
|
+
};
|
|
33199
|
+
}
|
|
33200
|
+
function toEgressIngestRequest(input2) {
|
|
33201
|
+
const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
|
|
33202
|
+
const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
|
|
33203
|
+
return {
|
|
33204
|
+
projectKey: hashProjectKey(input2.projectKey),
|
|
33205
|
+
project: input2.project,
|
|
33206
|
+
reconcile,
|
|
33207
|
+
hits: hits.map(toIngestHit)
|
|
33208
|
+
};
|
|
33209
|
+
}
|
|
33210
|
+
|
|
32369
33211
|
// ../../packages/persistence/src/exception-policy.ts
|
|
32370
33212
|
var UserGrantPolicyProvider = class {
|
|
32371
33213
|
#exceptions;
|
|
@@ -32387,13 +33229,13 @@ var UserGrantPolicyProvider = class {
|
|
|
32387
33229
|
};
|
|
32388
33230
|
|
|
32389
33231
|
// ../../packages/persistence/src/finding-key.ts
|
|
32390
|
-
import { createHash as
|
|
33232
|
+
import { createHash as createHash4 } from "crypto";
|
|
32391
33233
|
function normalizeFilePath(filePath) {
|
|
32392
33234
|
return filePath.replaceAll("\\", "/");
|
|
32393
33235
|
}
|
|
32394
33236
|
function computeFindingKey(input2) {
|
|
32395
33237
|
const normalizedPath = normalizeFilePath(input2.filePath);
|
|
32396
|
-
return
|
|
33238
|
+
return createHash4("sha256").update(`${input2.ruleId}\0${normalizedPath}\0${input2.valueFingerprint}`).digest("hex");
|
|
32397
33239
|
}
|
|
32398
33240
|
|
|
32399
33241
|
// ../../packages/persistence/src/fingerprint.ts
|
|
@@ -32519,14 +33361,50 @@ function fingerprintValue(key, raw) {
|
|
|
32519
33361
|
return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
|
|
32520
33362
|
}
|
|
32521
33363
|
|
|
32522
|
-
// ../../packages/persistence/src/
|
|
32523
|
-
import {
|
|
33364
|
+
// ../../packages/persistence/src/forward-health.ts
|
|
33365
|
+
import { readFileSync as readFileSync7 } from "fs";
|
|
32524
33366
|
import { join as join9 } from "path";
|
|
33367
|
+
var FAILURES = /* @__PURE__ */ new Set([
|
|
33368
|
+
"unauthorized",
|
|
33369
|
+
"forbidden",
|
|
33370
|
+
"unreachable"
|
|
33371
|
+
]);
|
|
33372
|
+
var BREAKER_COOLDOWN_MS = 3e4;
|
|
33373
|
+
function parseForwardHealth(raw, nowMs) {
|
|
33374
|
+
try {
|
|
33375
|
+
const parsed2 = JSON.parse(raw);
|
|
33376
|
+
if (typeof parsed2 !== "object" || parsed2 === null) return null;
|
|
33377
|
+
const record2 = parsed2;
|
|
33378
|
+
const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
|
|
33379
|
+
const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
|
|
33380
|
+
const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
|
|
33381
|
+
return { consecutiveFailures: failures, openedAtMs, lastFailure };
|
|
33382
|
+
} catch {
|
|
33383
|
+
return null;
|
|
33384
|
+
}
|
|
33385
|
+
}
|
|
33386
|
+
function isForwardPaused(health, nowMs) {
|
|
33387
|
+
const openedAtMs = health?.openedAtMs ?? null;
|
|
33388
|
+
if (openedAtMs === null) return false;
|
|
33389
|
+
return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
|
|
33390
|
+
}
|
|
33391
|
+
|
|
33392
|
+
// ../../packages/persistence/src/history-backfill.ts
|
|
33393
|
+
import { existsSync as existsSync4 } from "fs";
|
|
33394
|
+
import { join as join10 } from "path";
|
|
33395
|
+
|
|
33396
|
+
// ../../packages/persistence/src/history-preview.ts
|
|
33397
|
+
import { existsSync as existsSync5 } from "fs";
|
|
33398
|
+
import { join as join11 } from "path";
|
|
32525
33399
|
import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
|
|
32526
33400
|
|
|
33401
|
+
// ../../packages/persistence/src/history-sync-state.ts
|
|
33402
|
+
import { readFileSync as readFileSync8 } from "fs";
|
|
33403
|
+
import { join as join12 } from "path";
|
|
33404
|
+
|
|
32527
33405
|
// ../../packages/persistence/src/store-symlinks.ts
|
|
32528
|
-
import { existsSync as
|
|
32529
|
-
import { dirname as dirname3, join as
|
|
33406
|
+
import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
|
|
33407
|
+
import { dirname as dirname3, join as join13, resolve } from "path";
|
|
32530
33408
|
|
|
32531
33409
|
// ../../packages/persistence/src/vault/crypto.ts
|
|
32532
33410
|
import {
|
|
@@ -32639,8 +33517,8 @@ function formatPointer(category, keyVersion, pointerId, tag) {
|
|
|
32639
33517
|
// ../../packages/persistence/src/vault/key-provider.ts
|
|
32640
33518
|
import { execFileSync } from "child_process";
|
|
32641
33519
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
32642
|
-
import { chmodSync as chmodSync3, readFileSync as
|
|
32643
|
-
import { join as
|
|
33520
|
+
import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
|
|
33521
|
+
import { join as join14 } from "path";
|
|
32644
33522
|
var VAULT_OCCUPANT_REASON = {
|
|
32645
33523
|
symlink: "the path is a symlink; remove it so a keyring can be created",
|
|
32646
33524
|
gone: "the path was occupied but holds no keyring (removed while it was being created)",
|
|
@@ -32739,7 +33617,7 @@ function claimRotationLock(lock, owner) {
|
|
|
32739
33617
|
throw asError(err);
|
|
32740
33618
|
}
|
|
32741
33619
|
try {
|
|
32742
|
-
writeFileSync3(
|
|
33620
|
+
writeFileSync3(join14(lock, LOCK_OWNER_FILE), `${owner}
|
|
32743
33621
|
`, { mode: DATA_FILE_MODE });
|
|
32744
33622
|
return true;
|
|
32745
33623
|
} catch (err) {
|
|
@@ -32748,7 +33626,7 @@ function claimRotationLock(lock, owner) {
|
|
|
32748
33626
|
}
|
|
32749
33627
|
}
|
|
32750
33628
|
function acquireRotationLock(keysDir2) {
|
|
32751
|
-
const lock =
|
|
33629
|
+
const lock = join14(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
|
|
32752
33630
|
const owner = randomBytes2(16).toString("hex");
|
|
32753
33631
|
if (claimRotationLock(lock, owner)) return { lock, owner };
|
|
32754
33632
|
let held;
|
|
@@ -32775,7 +33653,7 @@ function acquireRotationLock(keysDir2) {
|
|
|
32775
33653
|
}
|
|
32776
33654
|
function releaseRotationLock(lease) {
|
|
32777
33655
|
try {
|
|
32778
|
-
if (
|
|
33656
|
+
if (readFileSync9(join14(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
|
|
32779
33657
|
} catch {
|
|
32780
33658
|
return;
|
|
32781
33659
|
}
|
|
@@ -32796,7 +33674,7 @@ var FileKeyProvider = class {
|
|
|
32796
33674
|
this.#keysDir = keysDir2;
|
|
32797
33675
|
}
|
|
32798
33676
|
get filePath() {
|
|
32799
|
-
return
|
|
33677
|
+
return join14(this.#keysDir, VAULT_KEY_FILENAME);
|
|
32800
33678
|
}
|
|
32801
33679
|
loadOrCreate() {
|
|
32802
33680
|
return asAsync(() => {
|
|
@@ -32826,7 +33704,7 @@ var FileKeyProvider = class {
|
|
|
32826
33704
|
#read() {
|
|
32827
33705
|
let raw;
|
|
32828
33706
|
try {
|
|
32829
|
-
raw =
|
|
33707
|
+
raw = readFileSync9(this.filePath, "utf8");
|
|
32830
33708
|
} catch (err) {
|
|
32831
33709
|
if (err.code === "ENOENT") return null;
|
|
32832
33710
|
throw err instanceof Error ? err : new Error(String(err));
|
|
@@ -33461,55 +34339,19 @@ var SecretVault = class {
|
|
|
33461
34339
|
};
|
|
33462
34340
|
|
|
33463
34341
|
// ../../packages/persistence/src/warn-era-cap.ts
|
|
33464
|
-
import { existsSync as
|
|
33465
|
-
import { join as
|
|
34342
|
+
import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
|
|
34343
|
+
import { join as join15 } from "path";
|
|
33466
34344
|
var MARKER = "warn-era-capped";
|
|
33467
34345
|
function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
|
|
33468
34346
|
if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
|
|
33469
|
-
const marker =
|
|
33470
|
-
if (
|
|
34347
|
+
const marker = join15(dataDir2, MARKER);
|
|
34348
|
+
if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
|
|
33471
34349
|
const capped = db.policies.capCategoryActions();
|
|
33472
34350
|
writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
|
|
33473
34351
|
`, { mode: DATA_FILE_MODE });
|
|
33474
34352
|
return { capped };
|
|
33475
34353
|
}
|
|
33476
34354
|
|
|
33477
|
-
// ../../packages/plugin-runtime/src/attached/egress-wire.ts
|
|
33478
|
-
function hashProjectKey(projectKey) {
|
|
33479
|
-
return createHash4("sha256").update(projectKey, "utf8").digest("hex");
|
|
33480
|
-
}
|
|
33481
|
-
function toIngestHit(hit) {
|
|
33482
|
-
return {
|
|
33483
|
-
host: hit.host,
|
|
33484
|
-
kind: hit.kind,
|
|
33485
|
-
name: hit.name,
|
|
33486
|
-
category: hit.category,
|
|
33487
|
-
trust: hit.trust,
|
|
33488
|
-
network: hit.network,
|
|
33489
|
-
method: hit.method,
|
|
33490
|
-
transport: hit.transport,
|
|
33491
|
-
url: hit.url,
|
|
33492
|
-
template: hit.template,
|
|
33493
|
-
dataClass: hit.dataClass,
|
|
33494
|
-
site: {
|
|
33495
|
-
file: hit.site.file,
|
|
33496
|
-
line: hit.site.line,
|
|
33497
|
-
dynamic: hit.site.dynamic,
|
|
33498
|
-
vendored: hit.site.vendored
|
|
33499
|
-
}
|
|
33500
|
-
};
|
|
33501
|
-
}
|
|
33502
|
-
function toEgressIngestRequest(input2) {
|
|
33503
|
-
const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
|
|
33504
|
-
const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
|
|
33505
|
-
return {
|
|
33506
|
-
projectKey: hashProjectKey(input2.projectKey),
|
|
33507
|
-
project: input2.project,
|
|
33508
|
-
reconcile,
|
|
33509
|
-
hits: hits.map(toIngestHit)
|
|
33510
|
-
};
|
|
33511
|
-
}
|
|
33512
|
-
|
|
33513
34355
|
// ../../packages/remote/src/http.ts
|
|
33514
34356
|
import { request as httpRequest } from "http";
|
|
33515
34357
|
import { request as httpsRequest } from "https";
|
|
@@ -33693,10 +34535,10 @@ function parsed(schema, body, route) {
|
|
|
33693
34535
|
}
|
|
33694
34536
|
function withoutTrailingSlashes(endpoint) {
|
|
33695
34537
|
let end = endpoint.length;
|
|
33696
|
-
while (end > 0 && endpoint.charCodeAt(end - 1) ===
|
|
34538
|
+
while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
|
|
33697
34539
|
return endpoint.slice(0, end);
|
|
33698
34540
|
}
|
|
33699
|
-
var
|
|
34541
|
+
var SLASH2 = "/".charCodeAt(0);
|
|
33700
34542
|
function createRemoteClient(options) {
|
|
33701
34543
|
const base = withoutTrailingSlashes(options.endpoint);
|
|
33702
34544
|
const url2 = (route) => `${base}${route}`;
|
|
@@ -33789,6 +34631,7 @@ function createRemoteClient(options) {
|
|
|
33789
34631
|
url: url2(ROUTES.shares),
|
|
33790
34632
|
body: JSON.stringify(validated.data)
|
|
33791
34633
|
});
|
|
34634
|
+
if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
|
|
33792
34635
|
okBody(response);
|
|
33793
34636
|
},
|
|
33794
34637
|
async pollCommand() {
|
|
@@ -33811,19 +34654,51 @@ function createRemoteClient(options) {
|
|
|
33811
34654
|
};
|
|
33812
34655
|
}
|
|
33813
34656
|
|
|
33814
|
-
// ../../packages/
|
|
34657
|
+
// ../../packages/remote/src/failure-kind.ts
|
|
33815
34658
|
function statusOf(err) {
|
|
33816
34659
|
if (typeof err !== "object" || err === null || !("status" in err)) return null;
|
|
33817
34660
|
const { status } = err;
|
|
33818
34661
|
if (typeof status !== "number" || !Number.isInteger(status)) return null;
|
|
33819
34662
|
return status >= 100 && status <= 599 ? status : null;
|
|
33820
34663
|
}
|
|
33821
|
-
function
|
|
33822
|
-
|
|
34664
|
+
function nameOf(err) {
|
|
34665
|
+
if (typeof err !== "object" || err === null || !("name" in err)) return null;
|
|
34666
|
+
return typeof err.name === "string" ? err.name : null;
|
|
34667
|
+
}
|
|
34668
|
+
function classifyRemoteFailure(err) {
|
|
34669
|
+
switch (nameOf(err)) {
|
|
34670
|
+
case "RemoteRouteAbsent":
|
|
34671
|
+
return "route-absent";
|
|
34672
|
+
case "RemoteRequestInvalid":
|
|
34673
|
+
return "invalid-request";
|
|
34674
|
+
case "RemoteResponseInvalid":
|
|
34675
|
+
return "rejected";
|
|
34676
|
+
default:
|
|
34677
|
+
break;
|
|
34678
|
+
}
|
|
34679
|
+
const status = statusOf(err);
|
|
34680
|
+
if (status === null) return "unreachable";
|
|
34681
|
+
switch (status) {
|
|
33823
34682
|
case 401:
|
|
33824
34683
|
return "unauthorized";
|
|
33825
34684
|
case 403:
|
|
33826
34685
|
return "forbidden";
|
|
34686
|
+
case 429:
|
|
34687
|
+
return "unreachable";
|
|
34688
|
+
case 404:
|
|
34689
|
+
return "unreachable";
|
|
34690
|
+
default:
|
|
34691
|
+
return status >= 400 && status <= 499 ? "rejected" : "unreachable";
|
|
34692
|
+
}
|
|
34693
|
+
}
|
|
34694
|
+
|
|
34695
|
+
// ../../packages/plugin-runtime/src/attached/failure.ts
|
|
34696
|
+
function classifyFailure(err) {
|
|
34697
|
+
switch (classifyRemoteFailure(err)) {
|
|
34698
|
+
case "unauthorized":
|
|
34699
|
+
return "unauthorized";
|
|
34700
|
+
case "forbidden":
|
|
34701
|
+
return "forbidden";
|
|
33827
34702
|
default:
|
|
33828
34703
|
return "unreachable";
|
|
33829
34704
|
}
|
|
@@ -33845,11 +34720,11 @@ function withTimeout(promise2, ms) {
|
|
|
33845
34720
|
}
|
|
33846
34721
|
|
|
33847
34722
|
// ../../packages/plugin-runtime/src/attached/forward-drops.ts
|
|
33848
|
-
import { readFileSync as
|
|
33849
|
-
import { join as
|
|
34723
|
+
import { readFileSync as readFileSync10 } from "fs";
|
|
34724
|
+
import { join as join16 } from "path";
|
|
33850
34725
|
var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
|
|
33851
34726
|
function forwardDropsPath(dataDir2) {
|
|
33852
|
-
return
|
|
34727
|
+
return join16(dataDir2, FORWARD_DROPS_FILENAME);
|
|
33853
34728
|
}
|
|
33854
34729
|
function recordForwardDrops(dataDir2, count, nowMs) {
|
|
33855
34730
|
if (count <= 0) return;
|
|
@@ -33867,7 +34742,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
|
|
|
33867
34742
|
}
|
|
33868
34743
|
function readForwardDrops(dataDir2) {
|
|
33869
34744
|
try {
|
|
33870
|
-
const parsed2 = JSON.parse(
|
|
34745
|
+
const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
|
|
33871
34746
|
if (typeof parsed2 !== "object" || parsed2 === null) return null;
|
|
33872
34747
|
const record2 = parsed2;
|
|
33873
34748
|
if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
|
|
@@ -33885,13 +34760,12 @@ function readForwardDrops(dataDir2) {
|
|
|
33885
34760
|
|
|
33886
34761
|
// ../../packages/plugin-runtime/src/attached/forward-policy.ts
|
|
33887
34762
|
import { randomUUID as randomUUID15 } from "crypto";
|
|
33888
|
-
import { readFileSync as readFileSync14 } from "fs";
|
|
33889
34763
|
import { readFile, rename, writeFile } from "fs/promises";
|
|
33890
|
-
import { join as
|
|
34764
|
+
import { join as join26 } from "path";
|
|
33891
34765
|
|
|
33892
34766
|
// ../../packages/plugin-sdk/src/config.ts
|
|
33893
|
-
import { existsSync as
|
|
33894
|
-
import { join as
|
|
34767
|
+
import { existsSync as existsSync8 } from "fs";
|
|
34768
|
+
import { join as join17 } from "path";
|
|
33895
34769
|
|
|
33896
34770
|
// ../../packages/plugin-sdk/src/provider-env.ts
|
|
33897
34771
|
var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
|
|
@@ -33955,8 +34829,8 @@ function providerFromModelId(modelId) {
|
|
|
33955
34829
|
function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
|
|
33956
34830
|
try {
|
|
33957
34831
|
ensureLayoutDirSync(base);
|
|
33958
|
-
const settingsFile =
|
|
33959
|
-
if (
|
|
34832
|
+
const settingsFile = join17(settingsDir(base), "settings.json");
|
|
34833
|
+
if (existsSync8(settingsFile)) tightenFile(settingsFile);
|
|
33960
34834
|
} catch {
|
|
33961
34835
|
}
|
|
33962
34836
|
migrateLegacyLayout(base);
|
|
@@ -33979,9 +34853,9 @@ function resolveProviderSafe(resolveProviderFn) {
|
|
|
33979
34853
|
}
|
|
33980
34854
|
|
|
33981
34855
|
// ../../packages/plugin-sdk/src/config-inventory.ts
|
|
33982
|
-
import { readdirSync as readdirSync2, readFileSync as
|
|
34856
|
+
import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
|
|
33983
34857
|
import { homedir as homedir2 } from "os";
|
|
33984
|
-
import { basename as basename3, join as
|
|
34858
|
+
import { basename as basename3, join as join19 } from "path";
|
|
33985
34859
|
|
|
33986
34860
|
// ../../packages/detections/src/egress/registry.ts
|
|
33987
34861
|
var EXTRACTOR_VERSION = "1";
|
|
@@ -37112,8 +37986,8 @@ function scanText(text, ruleVersions) {
|
|
|
37112
37986
|
}
|
|
37113
37987
|
|
|
37114
37988
|
// ../../packages/plugin-sdk/src/repo.ts
|
|
37115
|
-
import { existsSync as
|
|
37116
|
-
import { basename as basename2, dirname as dirname4, isAbsolute, join as
|
|
37989
|
+
import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
|
|
37990
|
+
import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
|
|
37117
37991
|
function resolveRepoIdentity(cwd) {
|
|
37118
37992
|
try {
|
|
37119
37993
|
const root = findGitRoot(cwd);
|
|
@@ -37146,36 +38020,36 @@ function resolveRepoNwo(cwd) {
|
|
|
37146
38020
|
function findGitRoot(start) {
|
|
37147
38021
|
let dir = start;
|
|
37148
38022
|
for (; ; ) {
|
|
37149
|
-
if (
|
|
38023
|
+
if (existsSync9(join18(dir, ".git"))) return dir;
|
|
37150
38024
|
const parent = dirname4(dir);
|
|
37151
38025
|
if (parent === dir) return void 0;
|
|
37152
38026
|
dir = parent;
|
|
37153
38027
|
}
|
|
37154
38028
|
}
|
|
37155
38029
|
function resolveGitContext(root) {
|
|
37156
|
-
const dotGit =
|
|
38030
|
+
const dotGit = join18(root, ".git");
|
|
37157
38031
|
try {
|
|
37158
38032
|
if (statSync6(dotGit).isDirectory()) {
|
|
37159
|
-
return { configPath:
|
|
38033
|
+
return { configPath: join18(dotGit, "config"), headRoot: root };
|
|
37160
38034
|
}
|
|
37161
38035
|
} catch {
|
|
37162
38036
|
return void 0;
|
|
37163
38037
|
}
|
|
37164
38038
|
const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
|
|
37165
38039
|
if (!target) return void 0;
|
|
37166
|
-
const gitdir = isAbsolute(target) ? target :
|
|
37167
|
-
if (
|
|
37168
|
-
return { configPath:
|
|
38040
|
+
const gitdir = isAbsolute(target) ? target : join18(root, target);
|
|
38041
|
+
if (existsSync9(join18(gitdir, "config"))) {
|
|
38042
|
+
return { configPath: join18(gitdir, "config"), headRoot: root };
|
|
37169
38043
|
}
|
|
37170
|
-
const commonRaw = safeRead(
|
|
38044
|
+
const commonRaw = safeRead(join18(gitdir, "commondir"))?.trim();
|
|
37171
38045
|
if (!commonRaw) return void 0;
|
|
37172
|
-
const commonGitDir = isAbsolute(commonRaw) ? commonRaw :
|
|
38046
|
+
const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join18(gitdir, commonRaw);
|
|
37173
38047
|
const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
|
|
37174
|
-
return { configPath:
|
|
38048
|
+
return { configPath: join18(commonGitDir, "config"), headRoot };
|
|
37175
38049
|
}
|
|
37176
38050
|
function safeRead(path) {
|
|
37177
38051
|
try {
|
|
37178
|
-
return
|
|
38052
|
+
return readFileSync11(path, "utf8");
|
|
37179
38053
|
} catch {
|
|
37180
38054
|
return void 0;
|
|
37181
38055
|
}
|
|
@@ -37254,7 +38128,7 @@ function buildIngestEvent(input2) {
|
|
|
37254
38128
|
}
|
|
37255
38129
|
|
|
37256
38130
|
// ../../packages/plugin-sdk/src/isolated-scan.ts
|
|
37257
|
-
import { existsSync as
|
|
38131
|
+
import { existsSync as existsSync10 } from "fs";
|
|
37258
38132
|
import { fileURLToPath } from "url";
|
|
37259
38133
|
import { Worker } from "worker_threads";
|
|
37260
38134
|
var ISOLATED_SCAN_BUDGET_MS = 2e3;
|
|
@@ -37268,7 +38142,7 @@ function resolveWorkerUrl() {
|
|
|
37268
38142
|
for (const name of ["scan-worker.js", "scan-worker.ts"]) {
|
|
37269
38143
|
const candidate = new URL(name, import.meta.url);
|
|
37270
38144
|
try {
|
|
37271
|
-
if (
|
|
38145
|
+
if (existsSync10(fileURLToPath(candidate))) {
|
|
37272
38146
|
resolvedWorkerUrl = candidate;
|
|
37273
38147
|
return candidate;
|
|
37274
38148
|
}
|
|
@@ -37731,10 +38605,45 @@ function createGuardedScanner(partition, gateway, opts) {
|
|
|
37731
38605
|
};
|
|
37732
38606
|
}
|
|
37733
38607
|
|
|
38608
|
+
// ../../packages/plugin-sdk/src/host-floor.ts
|
|
38609
|
+
import { readFileSync as readFileSync14 } from "fs";
|
|
38610
|
+
import { join as join21 } from "path";
|
|
38611
|
+
|
|
38612
|
+
// ../../packages/plugin-sdk/src/model-governance.ts
|
|
38613
|
+
import {
|
|
38614
|
+
closeSync as closeSync2,
|
|
38615
|
+
fstatSync,
|
|
38616
|
+
mkdirSync as mkdirSync2,
|
|
38617
|
+
openSync as openSync2,
|
|
38618
|
+
readFileSync as readFileSync13,
|
|
38619
|
+
readSync,
|
|
38620
|
+
writeFileSync as writeFileSync5
|
|
38621
|
+
} from "fs";
|
|
38622
|
+
import { join as join20 } from "path";
|
|
38623
|
+
var TAIL_BYTES = 256 * 1024;
|
|
38624
|
+
|
|
38625
|
+
// ../../packages/plugin-sdk/src/host-floor.ts
|
|
38626
|
+
var HOST_FEATURE = {
|
|
38627
|
+
ModelSwitch: "model-switch",
|
|
38628
|
+
VaultPointerDisplay: "vault-pointer-display"
|
|
38629
|
+
};
|
|
38630
|
+
var HOST_FLOORS = {
|
|
38631
|
+
[HOST_FEATURE.ModelSwitch]: {
|
|
38632
|
+
label: "model-switch protection",
|
|
38633
|
+
hookEvents: ["PreModelSwitch", "PostModelSwitch"],
|
|
38634
|
+
since: "2.1.251"
|
|
38635
|
+
},
|
|
38636
|
+
[HOST_FEATURE.VaultPointerDisplay]: {
|
|
38637
|
+
label: "vault pointer display",
|
|
38638
|
+
hookEvents: ["MessageDisplay"],
|
|
38639
|
+
since: "2.1.152"
|
|
38640
|
+
}
|
|
38641
|
+
};
|
|
38642
|
+
|
|
37734
38643
|
// ../../packages/plugin-sdk/src/ignore-layers.ts
|
|
37735
38644
|
var import_ignore = __toESM(require_ignore(), 1);
|
|
37736
|
-
import { readFileSync as
|
|
37737
|
-
import { join as
|
|
38645
|
+
import { readFileSync as readFileSync15 } from "fs";
|
|
38646
|
+
import { join as join22 } from "path";
|
|
37738
38647
|
|
|
37739
38648
|
// ../../packages/plugin-sdk/src/inventory-resolver.ts
|
|
37740
38649
|
import { arch, hostname as hostname4, platform, release } from "os";
|
|
@@ -37765,22 +38674,9 @@ function resolveInventoryContext(input2) {
|
|
|
37765
38674
|
return ctx;
|
|
37766
38675
|
}
|
|
37767
38676
|
|
|
37768
|
-
// ../../packages/plugin-sdk/src/model-governance.ts
|
|
37769
|
-
import {
|
|
37770
|
-
closeSync as closeSync2,
|
|
37771
|
-
fstatSync,
|
|
37772
|
-
mkdirSync as mkdirSync2,
|
|
37773
|
-
openSync as openSync2,
|
|
37774
|
-
readFileSync as readFileSync12,
|
|
37775
|
-
readSync,
|
|
37776
|
-
writeFileSync as writeFileSync5
|
|
37777
|
-
} from "fs";
|
|
37778
|
-
import { join as join18 } from "path";
|
|
37779
|
-
var TAIL_BYTES = 256 * 1024;
|
|
37780
|
-
|
|
37781
38677
|
// ../../packages/plugin-sdk/src/nudge.ts
|
|
37782
|
-
import { mkdirSync as mkdirSync3, readFileSync as
|
|
37783
|
-
import { join as
|
|
38678
|
+
import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
|
|
38679
|
+
import { join as join23 } from "path";
|
|
37784
38680
|
|
|
37785
38681
|
// ../../packages/plugin-sdk/src/paths.ts
|
|
37786
38682
|
import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
|
|
@@ -37822,8 +38718,8 @@ function createPolicyResolver(bundle) {
|
|
|
37822
38718
|
}
|
|
37823
38719
|
|
|
37824
38720
|
// ../../packages/plugin-sdk/src/project-files.ts
|
|
37825
|
-
import { existsSync as
|
|
37826
|
-
import { basename as basename5, join as
|
|
38721
|
+
import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
|
|
38722
|
+
import { basename as basename5, join as join24 } from "path";
|
|
37827
38723
|
|
|
37828
38724
|
// ../../packages/plugin-sdk/src/provider-env-antigravity.ts
|
|
37829
38725
|
var optionalBaseUrl2 = external_exports.preprocess((v) => {
|
|
@@ -37894,6 +38790,14 @@ function safeMaskedMatch(rawMatch) {
|
|
|
37894
38790
|
// ../../packages/plugin-sdk/src/runtime.ts
|
|
37895
38791
|
import { randomUUID as randomUUID14 } from "crypto";
|
|
37896
38792
|
var ENFORCEMENT_CEILING_ENABLED = false;
|
|
38793
|
+
function applyEnforcementCeiling(action, policyMode, enabled) {
|
|
38794
|
+
if (!enabled || policyMode !== "warn") return action;
|
|
38795
|
+
return action === "block" || action === "redact" ? "warn" : action;
|
|
38796
|
+
}
|
|
38797
|
+
function resolveEnforcedAction(action, opts) {
|
|
38798
|
+
const degraded = !opts.rewritable && action === "redact" ? builtinPolicyToAction(opts.redactFallback) : action;
|
|
38799
|
+
return applyEnforcementCeiling(degraded, opts.policyMode, opts.ceilingEnabled);
|
|
38800
|
+
}
|
|
37897
38801
|
function startTiming() {
|
|
37898
38802
|
try {
|
|
37899
38803
|
return performance.now();
|
|
@@ -37930,7 +38834,7 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
37930
38834
|
bundlesPacked = true;
|
|
37931
38835
|
}
|
|
37932
38836
|
const policyMode = settings.policy;
|
|
37933
|
-
|
|
38837
|
+
let redactFallback = settings.redactFallback;
|
|
37934
38838
|
const dataDir2 = opts?.dataDir;
|
|
37935
38839
|
let rules = [];
|
|
37936
38840
|
let scanner;
|
|
@@ -37974,6 +38878,7 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
37974
38878
|
rules = [...verified, ...unverified];
|
|
37975
38879
|
scanner = createGuardedScanner({ verified, unverified }, gateway, opts?.scanIsolation);
|
|
37976
38880
|
bundleExceptions = bundle.exceptions ?? [];
|
|
38881
|
+
redactFallback = strongerRedactFallback(settings.redactFallback, bundle.redactFallback);
|
|
37977
38882
|
initialized = true;
|
|
37978
38883
|
}
|
|
37979
38884
|
let cachedKey;
|
|
@@ -38002,21 +38907,23 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
38002
38907
|
}
|
|
38003
38908
|
function actionForFinding(finding, excepted, rewritable = true) {
|
|
38004
38909
|
if (excepted?.has(finding)) return "allow";
|
|
38005
|
-
|
|
38006
|
-
|
|
38007
|
-
|
|
38008
|
-
|
|
38009
|
-
|
|
38010
|
-
|
|
38910
|
+
return resolveEnforcedAction(resolveAction(finding.ruleId, finding.category), {
|
|
38911
|
+
policyMode,
|
|
38912
|
+
redactFallback,
|
|
38913
|
+
rewritable,
|
|
38914
|
+
ceilingEnabled: ENFORCEMENT_CEILING_ENABLED
|
|
38915
|
+
});
|
|
38011
38916
|
}
|
|
38012
38917
|
function decide(findings, text, excepted, rewritable = true) {
|
|
38013
38918
|
if (findings.length === 0) return { action: "log", text, findings: [] };
|
|
38014
38919
|
const actionFor = (finding) => actionForFinding(finding, excepted, rewritable);
|
|
38920
|
+
const degradedActions = rewritable ? [] : findings.filter((f) => actionForFinding(f, excepted, true) === "redact").map(actionFor);
|
|
38921
|
+
const degraded = degradedActions.length === 0 ? {} : { redactDegradedTo: degradedActions.reduce((a, b) => strongerAction(a, b)) };
|
|
38015
38922
|
let worst = "log";
|
|
38016
38923
|
for (const finding of findings) {
|
|
38017
38924
|
worst = strongerAction(worst, actionFor(finding));
|
|
38018
38925
|
}
|
|
38019
|
-
if (worst === "block") return { action: "block", text: null, findings };
|
|
38926
|
+
if (worst === "block") return { action: "block", text: null, findings, ...degraded };
|
|
38020
38927
|
if (worst === "redact") {
|
|
38021
38928
|
const redactFindings = findings.filter((f) => actionFor(f) === "redact");
|
|
38022
38929
|
const reversibleFindings = redactFindings.filter((f) => resolver.isReversible(f.ruleId));
|
|
@@ -38026,9 +38933,13 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
38026
38933
|
findings,
|
|
38027
38934
|
enforcedFindings: redactFindings,
|
|
38028
38935
|
reversibleFindings
|
|
38936
|
+
// No `degraded` here, and it is not an omission: `rewritable` is per
|
|
38937
|
+
// CAPTURE, so on an unrewritable field every redact has already become
|
|
38938
|
+
// the fallback and this branch is unreachable. Spreading it would read
|
|
38939
|
+
// as a case that can happen.
|
|
38029
38940
|
};
|
|
38030
38941
|
}
|
|
38031
|
-
return { action: worst, text, findings };
|
|
38942
|
+
return { action: worst, text, findings, ...degraded };
|
|
38032
38943
|
}
|
|
38033
38944
|
function fingerprintOf(key, finding, cache) {
|
|
38034
38945
|
let fp = cache.get(finding);
|
|
@@ -38157,8 +39068,8 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
38157
39068
|
};
|
|
38158
39069
|
}
|
|
38159
39070
|
}
|
|
38160
|
-
async function processText(text, context) {
|
|
38161
|
-
return (await evaluate(text, context, {})).decision;
|
|
39071
|
+
async function processText(text, context, opts2 = {}) {
|
|
39072
|
+
return (await evaluate(text, context, {}, opts2.rewritable)).decision;
|
|
38162
39073
|
}
|
|
38163
39074
|
async function capture(input2, opts2 = {}) {
|
|
38164
39075
|
const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
|
|
@@ -38181,10 +39092,12 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
38181
39092
|
);
|
|
38182
39093
|
const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
|
|
38183
39094
|
const inspectionMs = elapsedMs(timingStartedAt);
|
|
38184
|
-
const
|
|
39095
|
+
const redactDegradedTo = decision.redactDegradedTo;
|
|
39096
|
+
const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 ? {
|
|
38185
39097
|
...input2.metadata,
|
|
38186
39098
|
...exceptionIds.length > 0 ? { exceptionIds } : {},
|
|
38187
|
-
...inspectionMs !== void 0 ? { inspectionMs } : {}
|
|
39099
|
+
...inspectionMs !== void 0 ? { inspectionMs } : {},
|
|
39100
|
+
...redactDegradedTo !== void 0 ? { redactDegradedTo } : {}
|
|
38188
39101
|
} : input2.metadata;
|
|
38189
39102
|
const event = buildIngestEvent({
|
|
38190
39103
|
kind: input2.kind,
|
|
@@ -38256,7 +39169,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
|
38256
39169
|
|
|
38257
39170
|
// ../../packages/plugin-sdk/src/throttle.ts
|
|
38258
39171
|
import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
|
|
38259
|
-
import { join as
|
|
39172
|
+
import { join as join25 } from "path";
|
|
38260
39173
|
|
|
38261
39174
|
// ../../packages/plugin-sdk/src/tokenize.ts
|
|
38262
39175
|
function redactedPlaceholder(category) {
|
|
@@ -38585,31 +39498,12 @@ function isServerRejection(err) {
|
|
|
38585
39498
|
var FORWARD_BUDGET_MS = 1500;
|
|
38586
39499
|
var DECISION_PATH_BUDGET_MS = 800;
|
|
38587
39500
|
var BREAKER_FAILURE_THRESHOLD = 3;
|
|
38588
|
-
var BREAKER_COOLDOWN_MS = 3e4;
|
|
38589
39501
|
var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
|
|
38590
|
-
var FAILURES = /* @__PURE__ */ new Set([
|
|
38591
|
-
"unauthorized",
|
|
38592
|
-
"forbidden",
|
|
38593
|
-
"unreachable"
|
|
38594
|
-
]);
|
|
38595
39502
|
var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
|
|
38596
39503
|
var STATE_FILENAME = FORWARD_STATE_FILENAME;
|
|
38597
|
-
function parseBreakerState(raw, nowMs) {
|
|
38598
|
-
try {
|
|
38599
|
-
const parsed2 = JSON.parse(raw);
|
|
38600
|
-
if (typeof parsed2 !== "object" || parsed2 === null) return null;
|
|
38601
|
-
const record2 = parsed2;
|
|
38602
|
-
const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
|
|
38603
|
-
const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
|
|
38604
|
-
const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
|
|
38605
|
-
return { consecutiveFailures: failures, openedAtMs, lastFailure };
|
|
38606
|
-
} catch {
|
|
38607
|
-
return null;
|
|
38608
|
-
}
|
|
38609
|
-
}
|
|
38610
39504
|
function createForwardPolicy(deps) {
|
|
38611
39505
|
const now = deps.now ?? (() => Date.now());
|
|
38612
|
-
const file2 =
|
|
39506
|
+
const file2 = join26(deps.dir, STATE_FILENAME);
|
|
38613
39507
|
let state = null;
|
|
38614
39508
|
let loading = null;
|
|
38615
39509
|
async function readState() {
|
|
@@ -38619,7 +39513,7 @@ function createForwardPolicy(deps) {
|
|
|
38619
39513
|
} catch {
|
|
38620
39514
|
return { ...CLOSED };
|
|
38621
39515
|
}
|
|
38622
|
-
return
|
|
39516
|
+
return parseForwardHealth(raw, now()) ?? { ...CLOSED };
|
|
38623
39517
|
}
|
|
38624
39518
|
async function load() {
|
|
38625
39519
|
if (state !== null) return state;
|
|
@@ -38665,7 +39559,7 @@ function createForwardPolicy(deps) {
|
|
|
38665
39559
|
};
|
|
38666
39560
|
const at = now();
|
|
38667
39561
|
if (current.openedAtMs !== null) {
|
|
38668
|
-
if (
|
|
39562
|
+
if (isForwardPaused(current, at)) {
|
|
38669
39563
|
return { ok: false, reason: "breaker-open" };
|
|
38670
39564
|
}
|
|
38671
39565
|
await persist({
|
|
@@ -39202,7 +40096,18 @@ var AttachedDataGateway = class {
|
|
|
39202
40096
|
// and the spread above would otherwise drop the field silently — which is
|
|
39203
40097
|
// exactly what it did, leaving the whole control inert on every device
|
|
39204
40098
|
// while every test around it stayed green.
|
|
39205
|
-
prohibitedModels: cached2.prohibitedModels
|
|
40099
|
+
prohibitedModels: cached2.prohibitedModels,
|
|
40100
|
+
// NAMED for the same reason as the line above, and it is the same defect
|
|
40101
|
+
// if it is not: `...local` above spreads the DEVICE's bundle, so a field
|
|
40102
|
+
// only the cache carries is dropped in silence. That is what left
|
|
40103
|
+
// `prohibitedModels` inert on every attached device with every test
|
|
40104
|
+
// around it green.
|
|
40105
|
+
//
|
|
40106
|
+
// Taken from the cache rather than merged here, because merging it needs
|
|
40107
|
+
// the device's own SETTING — which is not a bundle field and is not in
|
|
40108
|
+
// scope at this seam. The runtime does that merge, raise-only, where both
|
|
40109
|
+
// values are in hand (createPluginRuntime's ensureInitialized).
|
|
40110
|
+
redactFallback: cached2.redactFallback
|
|
39206
40111
|
// ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
|
|
39207
40112
|
// merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
|
|
39208
40113
|
// it emits, so an 'authored' policy arriving from the control plane
|
|
@@ -39330,10 +40235,6 @@ function toolAuditEvent(input2) {
|
|
|
39330
40235
|
};
|
|
39331
40236
|
}
|
|
39332
40237
|
|
|
39333
|
-
// ../../packages/plugin-runtime/src/attached/history-state.ts
|
|
39334
|
-
import { readFileSync as readFileSync15 } from "fs";
|
|
39335
|
-
import { join as join23 } from "path";
|
|
39336
|
-
|
|
39337
40238
|
// ../../packages/plugin-runtime/src/attached/history-sync.ts
|
|
39338
40239
|
import { createHash as createHash6 } from "crypto";
|
|
39339
40240
|
import { hostname as hostname5 } from "os";
|
|
@@ -39342,6 +40243,10 @@ import { hostname as hostname5 } from "os";
|
|
|
39342
40243
|
var CORRELATION_ID = EventMetadata.shape.correlationId;
|
|
39343
40244
|
var TRACE_ID = EventMetadata.shape.traceId;
|
|
39344
40245
|
var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
|
|
40246
|
+
var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
|
|
40247
|
+
|
|
40248
|
+
// ../../packages/plugin-runtime/src/attached/history-sync.ts
|
|
40249
|
+
var CAPTURE_BATCH_BYTES = 1024 * 1024;
|
|
39345
40250
|
|
|
39346
40251
|
// ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
|
|
39347
40252
|
import { spawn } from "child_process";
|
|
@@ -39349,14 +40254,14 @@ import { fileURLToPath as fileURLToPath2 } from "url";
|
|
|
39349
40254
|
var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
|
|
39350
40255
|
|
|
39351
40256
|
// ../../packages/plugin-runtime/src/attached/plugin-block.ts
|
|
39352
|
-
import { readFileSync as
|
|
40257
|
+
import { readFileSync as readFileSync17 } from "fs";
|
|
39353
40258
|
var manifestBuildCache = /* @__PURE__ */ new Map();
|
|
39354
40259
|
function readManifestBuild(manifestUrl, packageName) {
|
|
39355
40260
|
const key = manifestUrl.href;
|
|
39356
40261
|
if (!manifestBuildCache.has(key)) {
|
|
39357
40262
|
let build;
|
|
39358
40263
|
try {
|
|
39359
|
-
const manifest = JSON.parse(
|
|
40264
|
+
const manifest = JSON.parse(readFileSync17(manifestUrl, "utf8"));
|
|
39360
40265
|
build = typeof manifest.version === "string" && manifest.version.length > 0 ? { package: packageName, version: manifest.version } : void 0;
|
|
39361
40266
|
} catch {
|
|
39362
40267
|
build = void 0;
|
|
@@ -39383,7 +40288,7 @@ function createPluginBlock(build, policyStore) {
|
|
|
39383
40288
|
// ../../packages/plugin-runtime/src/attached/policy-store.ts
|
|
39384
40289
|
import { randomUUID as randomUUID16 } from "crypto";
|
|
39385
40290
|
import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
|
|
39386
|
-
import { join as
|
|
40291
|
+
import { join as join27 } from "path";
|
|
39387
40292
|
|
|
39388
40293
|
// ../../packages/plugin-runtime/src/attached/atomic-publish.ts
|
|
39389
40294
|
import { rename as rename2 } from "fs/promises";
|
|
@@ -39407,7 +40312,7 @@ async function publishByRename(tmp, file2, move = rename2) {
|
|
|
39407
40312
|
|
|
39408
40313
|
// ../../packages/plugin-runtime/src/attached/policy-store.ts
|
|
39409
40314
|
function createPolicyStore(dir = dataDir()) {
|
|
39410
|
-
const file2 =
|
|
40315
|
+
const file2 = join27(dir, "policy-cache.json");
|
|
39411
40316
|
async function read() {
|
|
39412
40317
|
try {
|
|
39413
40318
|
const raw = await readFile2(file2, "utf8");
|
|
@@ -39638,11 +40543,11 @@ function readStorePosture(dbPath2) {
|
|
|
39638
40543
|
// ../../packages/plugin-runtime/src/attached/posture-store.ts
|
|
39639
40544
|
import { randomUUID as randomUUID17 } from "crypto";
|
|
39640
40545
|
import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
|
|
39641
|
-
import { join as
|
|
40546
|
+
import { join as join28 } from "path";
|
|
39642
40547
|
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
39643
40548
|
function createPostureStore(dir = settingsDir(), legacyDir) {
|
|
39644
|
-
const file2 =
|
|
39645
|
-
const legacyFile = legacyDir === void 0 ? null :
|
|
40549
|
+
const file2 = join28(dir, "posture-state.json");
|
|
40550
|
+
const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
|
|
39646
40551
|
async function persist(state) {
|
|
39647
40552
|
await ensureDataDir(dir);
|
|
39648
40553
|
const tmp = `${file2}.${randomUUID17()}.tmp`;
|
|
@@ -39710,8 +40615,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
|
|
|
39710
40615
|
}
|
|
39711
40616
|
|
|
39712
40617
|
// ../../packages/plugin-runtime/src/attached/sync-state.ts
|
|
39713
|
-
import { readFileSync as
|
|
39714
|
-
import { join as
|
|
40618
|
+
import { readFileSync as readFileSync18 } from "fs";
|
|
40619
|
+
import { join as join29 } from "path";
|
|
39715
40620
|
|
|
39716
40621
|
// ../../packages/plugin-runtime/src/attached/status.ts
|
|
39717
40622
|
var REFUSAL_LINES = {
|
|
@@ -39732,6 +40637,14 @@ import { spawn as spawn2 } from "child_process";
|
|
|
39732
40637
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
39733
40638
|
var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
|
|
39734
40639
|
|
|
40640
|
+
// ../../packages/plugin-runtime/src/content-retention-pass.ts
|
|
40641
|
+
var MAX_ROWS_PER_SWEEP = 50 * 1e3;
|
|
40642
|
+
|
|
40643
|
+
// ../../packages/plugin-runtime/src/content-retention-trigger.ts
|
|
40644
|
+
import { spawn as spawn3 } from "child_process";
|
|
40645
|
+
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
40646
|
+
var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
|
|
40647
|
+
|
|
39735
40648
|
// ../../packages/plugin-runtime/src/attached/factory.ts
|
|
39736
40649
|
import { hostname as hostname6 } from "os";
|
|
39737
40650
|
|
|
@@ -40183,7 +41096,7 @@ var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
|
|
|
40183
41096
|
|
|
40184
41097
|
// ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
|
|
40185
41098
|
import { writeFileSync as writeFileSync8 } from "fs";
|
|
40186
|
-
import { join as
|
|
41099
|
+
import { join as join30 } from "path";
|
|
40187
41100
|
|
|
40188
41101
|
// ../../packages/setup-wizard/src/triage/merge.ts
|
|
40189
41102
|
var RANK = Object.fromEntries(
|
|
@@ -40191,9 +41104,9 @@ var RANK = Object.fromEntries(
|
|
|
40191
41104
|
);
|
|
40192
41105
|
|
|
40193
41106
|
// ../../packages/setup-wizard/src/triage/plan-file.ts
|
|
40194
|
-
import { mkdtempSync, readFileSync as
|
|
41107
|
+
import { mkdtempSync, readFileSync as readFileSync19, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
|
|
40195
41108
|
import { tmpdir } from "os";
|
|
40196
|
-
import { basename as basename6, dirname as dirname6, join as
|
|
41109
|
+
import { basename as basename6, dirname as dirname6, join as join31 } from "path";
|
|
40197
41110
|
var SuppressionEntrySchema = external_exports.object({
|
|
40198
41111
|
ruleId: external_exports.string(),
|
|
40199
41112
|
category: DetectionCategory,
|
|
@@ -40238,11 +41151,11 @@ var PersistedPlanSchema = external_exports.object({
|
|
|
40238
41151
|
var TRIAGE_STATUSES = ["complete", "complete:no-history", "skipped:no-consent"];
|
|
40239
41152
|
|
|
40240
41153
|
// src/history/transcripts.ts
|
|
40241
|
-
import { readdirSync as readdirSync5, readFileSync as
|
|
41154
|
+
import { readdirSync as readdirSync5, readFileSync as readFileSync20 } from "fs";
|
|
40242
41155
|
import { homedir as homedir3 } from "os";
|
|
40243
|
-
import { join as
|
|
41156
|
+
import { join as join32 } from "path";
|
|
40244
41157
|
function transcriptsDir(home) {
|
|
40245
|
-
return
|
|
41158
|
+
return join32(home ?? homedir3(), ".claude", "projects");
|
|
40246
41159
|
}
|
|
40247
41160
|
function isRecord(value) {
|
|
40248
41161
|
return typeof value === "object" && value !== null;
|
|
@@ -40490,7 +41403,7 @@ function* iterateFileContents(dir, excludeSessionId) {
|
|
|
40490
41403
|
return;
|
|
40491
41404
|
}
|
|
40492
41405
|
for (const project of projects) {
|
|
40493
|
-
const projectDir =
|
|
41406
|
+
const projectDir = join32(dir, project);
|
|
40494
41407
|
let files;
|
|
40495
41408
|
try {
|
|
40496
41409
|
files = readdirSync5(projectDir).filter((name) => name.endsWith(".jsonl"));
|
|
@@ -40500,10 +41413,10 @@ function* iterateFileContents(dir, excludeSessionId) {
|
|
|
40500
41413
|
for (const file2 of files) {
|
|
40501
41414
|
if (excludeSessionId !== void 0 && file2.slice(0, -".jsonl".length) === excludeSessionId)
|
|
40502
41415
|
continue;
|
|
40503
|
-
const filePath =
|
|
41416
|
+
const filePath = join32(projectDir, file2);
|
|
40504
41417
|
let content;
|
|
40505
41418
|
try {
|
|
40506
|
-
content =
|
|
41419
|
+
content = readFileSync20(filePath, "utf8");
|
|
40507
41420
|
} catch {
|
|
40508
41421
|
continue;
|
|
40509
41422
|
}
|
|
@@ -40635,20 +41548,20 @@ async function scanHistory(config2, opts = {}, onHit) {
|
|
|
40635
41548
|
}
|
|
40636
41549
|
|
|
40637
41550
|
// src/history/tail-scrub.ts
|
|
40638
|
-
import { readFileSync as
|
|
41551
|
+
import { readFileSync as readFileSync22, renameSync as renameSync6, rmSync as rmSync9, statSync as statSync11, writeFileSync as writeFileSync11 } from "fs";
|
|
40639
41552
|
|
|
40640
41553
|
// src/remediation/redact.ts
|
|
40641
41554
|
import {
|
|
40642
41555
|
lstatSync as lstatSync4,
|
|
40643
41556
|
readdirSync as readdirSync6,
|
|
40644
|
-
readFileSync as
|
|
41557
|
+
readFileSync as readFileSync21,
|
|
40645
41558
|
realpathSync as realpathSync4,
|
|
40646
41559
|
renameSync as renameSync5,
|
|
40647
41560
|
rmSync as rmSync8,
|
|
40648
41561
|
statSync as statSync10,
|
|
40649
41562
|
writeFileSync as writeFileSync10
|
|
40650
41563
|
} from "fs";
|
|
40651
|
-
import { basename as basename7, dirname as dirname7, isAbsolute as isAbsolute2, join as
|
|
41564
|
+
import { basename as basename7, dirname as dirname7, isAbsolute as isAbsolute2, join as join33, relative, resolve as resolve2 } from "path";
|
|
40652
41565
|
function platformRedactionScope(home) {
|
|
40653
41566
|
return { artifactRoots: [transcriptsDir(home)] };
|
|
40654
41567
|
}
|
|
@@ -40679,7 +41592,7 @@ async function scrubTranscriptTail(filePath, deps) {
|
|
|
40679
41592
|
if (realPath === null) return null;
|
|
40680
41593
|
const statBefore = statSync11(realPath);
|
|
40681
41594
|
if (statBefore.size > (deps.maxBytes ?? DEFAULT_MAX_SCRUB_BYTES)) return null;
|
|
40682
|
-
const content =
|
|
41595
|
+
const content = readFileSync22(realPath, "utf8");
|
|
40683
41596
|
const lines = content.split("\n");
|
|
40684
41597
|
let rewritten = 0;
|
|
40685
41598
|
for (const [i, line] of lines.entries()) {
|
|
@@ -40729,11 +41642,11 @@ import {
|
|
|
40729
41642
|
fstatSync as fstatSync2,
|
|
40730
41643
|
mkdirSync as mkdirSync5,
|
|
40731
41644
|
openSync as openSync3,
|
|
40732
|
-
readFileSync as
|
|
41645
|
+
readFileSync as readFileSync23,
|
|
40733
41646
|
readSync as readSync2,
|
|
40734
41647
|
writeFileSync as writeFileSync12
|
|
40735
41648
|
} from "fs";
|
|
40736
|
-
import { join as
|
|
41649
|
+
import { join as join34 } from "path";
|
|
40737
41650
|
|
|
40738
41651
|
// src/history/usage.ts
|
|
40739
41652
|
var NO_PROJECT_CWD = "/nonexistent/aka-reconciler/no-project";
|
|
@@ -41062,7 +41975,7 @@ async function runBackfill(deps) {
|
|
|
41062
41975
|
} else {
|
|
41063
41976
|
const heading = "\u2713 Historical scan complete";
|
|
41064
41977
|
const scope = `Scanned ${String(summary.scanned)} messages from the last ${String(summary.windowDays)} days of Claude Code history.`;
|
|
41065
|
-
const result = summary.findings > 0 ? `Found ${String(summary.findings)} pre-install finding${summary.findings === 1 ? "" : "s"} \u2014 review them with /findings.` : "No new pre-install secrets found in your history.";
|
|
41978
|
+
const result = summary.findings > 0 ? `Found ${String(summary.findings)} pre-install finding${summary.findings === 1 ? "" : "s"} \u2014 review them with /aka:findings.` : "No new pre-install secrets found in your history.";
|
|
41066
41979
|
const lines = [heading, "", indent(scope), "", indent(result)];
|
|
41067
41980
|
if (scrubbedFiles > 0) {
|
|
41068
41981
|
lines.push(
|
|
@@ -41118,7 +42031,7 @@ async function readPolicyResolver(cfg) {
|
|
|
41118
42031
|
}
|
|
41119
42032
|
}
|
|
41120
42033
|
}
|
|
41121
|
-
if (process.argv[1] &&
|
|
42034
|
+
if (process.argv[1] && fileURLToPath5(import.meta.url) === process.argv[1]) {
|
|
41122
42035
|
const triage = process.argv.includes("--triage");
|
|
41123
42036
|
const startedAt = Date.now();
|
|
41124
42037
|
const sessionId = process.env.CLAUDE_CODE_BRIDGE_SESSION_ID;
|