@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/query.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
|
|
@@ -502,6 +502,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
|
|
|
502
502
|
import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
|
|
503
503
|
import { join as join2 } from "path";
|
|
504
504
|
|
|
505
|
+
// ../../packages/schema/src/drizzle/deferred-migrations.ts
|
|
506
|
+
var DEFERRED_MIGRATION_TAGS = [
|
|
507
|
+
"0031_audit_capture_by_time_index",
|
|
508
|
+
"0032_audit_capture_by_id_index",
|
|
509
|
+
"0033_audit_capture_location_index",
|
|
510
|
+
"0034_findings_read_indexes"
|
|
511
|
+
];
|
|
512
|
+
|
|
505
513
|
// ../../packages/schema/src/drizzle/sqlite-ddl.ts
|
|
506
514
|
var SQLITE_MIGRATIONS = [
|
|
507
515
|
{
|
|
@@ -619,6 +627,30 @@ var SQLITE_MIGRATIONS = [
|
|
|
619
627
|
{
|
|
620
628
|
tag: "0028_activity_session_probe_indexes",
|
|
621
629
|
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"
|
|
630
|
+
},
|
|
631
|
+
{
|
|
632
|
+
tag: "0029_audit_capture_rollup_index",
|
|
633
|
+
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');"
|
|
634
|
+
},
|
|
635
|
+
{
|
|
636
|
+
tag: "0030_audit_content_expiry",
|
|
637
|
+
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;"
|
|
638
|
+
},
|
|
639
|
+
{
|
|
640
|
+
tag: "0031_audit_capture_by_time_index",
|
|
641
|
+
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');"
|
|
642
|
+
},
|
|
643
|
+
{
|
|
644
|
+
tag: "0032_audit_capture_by_id_index",
|
|
645
|
+
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');"
|
|
646
|
+
},
|
|
647
|
+
{
|
|
648
|
+
tag: "0033_audit_capture_location_index",
|
|
649
|
+
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');"
|
|
650
|
+
},
|
|
651
|
+
{
|
|
652
|
+
tag: "0034_findings_read_indexes",
|
|
653
|
+
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`);"
|
|
622
654
|
}
|
|
623
655
|
];
|
|
624
656
|
|
|
@@ -20420,6 +20452,100 @@ function epochMillisToIso(ms) {
|
|
|
20420
20452
|
return new Date(ms).toISOString();
|
|
20421
20453
|
}
|
|
20422
20454
|
|
|
20455
|
+
// ../../packages/schema/src/security/recommendations.ts
|
|
20456
|
+
var SEVERITY_WEIGHT = {
|
|
20457
|
+
critical: 4,
|
|
20458
|
+
high: 3,
|
|
20459
|
+
medium: 2,
|
|
20460
|
+
low: 1
|
|
20461
|
+
};
|
|
20462
|
+
function severityWeight(severity) {
|
|
20463
|
+
return Object.hasOwn(SEVERITY_WEIGHT, severity) ? SEVERITY_WEIGHT[severity] : 0;
|
|
20464
|
+
}
|
|
20465
|
+
var ADVICE = {
|
|
20466
|
+
secret: "Rotate the exposed credentials and move them out of prompts (secrets manager / env vars).",
|
|
20467
|
+
pii: "Remove or mask personal data before it reaches the model.",
|
|
20468
|
+
financial: "Strip card and account numbers; share only non-sensitive references.",
|
|
20469
|
+
phi: "Remove protected health information \u2014 it should never reach an external model.",
|
|
20470
|
+
code_context: "Confirm this proprietary code context is safe to share.",
|
|
20471
|
+
code_flaw: "Review the flagged pattern and apply the secure alternative (parameterized queries, safe deserializers, etc.).",
|
|
20472
|
+
config: "Review the setting \u2014 a hook conflict or an egress change applies to every session that follows.",
|
|
20473
|
+
custom: "Review against your organization\u2019s custom policy."
|
|
20474
|
+
};
|
|
20475
|
+
var REC_TEMPLATE = {
|
|
20476
|
+
secret: { title: "Exposed secret detected", action: "Rotate" },
|
|
20477
|
+
pii: { title: "Personal data in a prompt", action: "Remove" },
|
|
20478
|
+
financial: { title: "Financial data detected", action: "Strip" },
|
|
20479
|
+
phi: { title: "Health information detected", action: "Remove" },
|
|
20480
|
+
code_context: { title: "Proprietary code shared", action: "Review" },
|
|
20481
|
+
code_flaw: { title: "Insecure code pattern", action: "Fix" },
|
|
20482
|
+
config: { title: "Weakened configuration", action: "Review" },
|
|
20483
|
+
custom: { title: "Custom policy match", action: "Review" }
|
|
20484
|
+
};
|
|
20485
|
+
var MAX_RECOMMENDATIONS = 10;
|
|
20486
|
+
function bucketizeRecommendations(findings) {
|
|
20487
|
+
const byRule = /* @__PURE__ */ new Map();
|
|
20488
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
20489
|
+
for (const f of findings) {
|
|
20490
|
+
const n = f.count ?? 1;
|
|
20491
|
+
byRule.set(f.ruleId, (byRule.get(f.ruleId) ?? 0) + n);
|
|
20492
|
+
const b = buckets.get(f.category) ?? {
|
|
20493
|
+
category: f.category,
|
|
20494
|
+
count: 0,
|
|
20495
|
+
categoryCount: 0,
|
|
20496
|
+
severity: f.severity,
|
|
20497
|
+
weight: 0,
|
|
20498
|
+
ruleId: f.ruleId
|
|
20499
|
+
};
|
|
20500
|
+
b.categoryCount += n;
|
|
20501
|
+
const w = severityWeight(f.severity);
|
|
20502
|
+
if (w > b.weight) {
|
|
20503
|
+
b.weight = w;
|
|
20504
|
+
b.severity = f.severity;
|
|
20505
|
+
b.ruleId = f.ruleId;
|
|
20506
|
+
}
|
|
20507
|
+
buckets.set(f.category, b);
|
|
20508
|
+
}
|
|
20509
|
+
for (const b of buckets.values()) b.count = byRule.get(b.ruleId) ?? 0;
|
|
20510
|
+
return [...buckets.values()].sort((a, b) => b.weight - a.weight || b.categoryCount - a.categoryCount).slice(0, MAX_RECOMMENDATIONS);
|
|
20511
|
+
}
|
|
20512
|
+
function buildRecommendations(findings) {
|
|
20513
|
+
return bucketizeRecommendations(findings).map((b) => {
|
|
20514
|
+
const copy = recommendationCopy(b.category);
|
|
20515
|
+
return {
|
|
20516
|
+
severity: b.severity,
|
|
20517
|
+
title: copy.title,
|
|
20518
|
+
description: copy.advice,
|
|
20519
|
+
context: `${b.ruleId} \xB7 ${String(b.count)} finding${b.count === 1 ? "" : "s"}`,
|
|
20520
|
+
action: copy.action
|
|
20521
|
+
};
|
|
20522
|
+
});
|
|
20523
|
+
}
|
|
20524
|
+
function recommendationCopy(category) {
|
|
20525
|
+
const template = REC_TEMPLATE_BY_STRING[category] ?? {
|
|
20526
|
+
title: `${category} finding`,
|
|
20527
|
+
action: "Review"
|
|
20528
|
+
};
|
|
20529
|
+
return {
|
|
20530
|
+
...template,
|
|
20531
|
+
advice: ADVICE_BY_STRING[category] ?? "Review this finding against your policy."
|
|
20532
|
+
};
|
|
20533
|
+
}
|
|
20534
|
+
var ADVICE_BY_STRING = ADVICE;
|
|
20535
|
+
var REC_TEMPLATE_BY_STRING = REC_TEMPLATE;
|
|
20536
|
+
function healthScore(summary) {
|
|
20537
|
+
const handled = summary.byAction.block + summary.byAction.redact + summary.byAction.warn;
|
|
20538
|
+
const handledRatio = summary.findings === 0 ? 1 : handled / summary.findings;
|
|
20539
|
+
return Math.round(100 * (0.6 * summary.coverage + 0.4 * handledRatio));
|
|
20540
|
+
}
|
|
20541
|
+
function findingStatus(summary) {
|
|
20542
|
+
return {
|
|
20543
|
+
score: healthScore(summary),
|
|
20544
|
+
unreviewed: { ...summary.bySeverity },
|
|
20545
|
+
openFindings: summary.findings
|
|
20546
|
+
};
|
|
20547
|
+
}
|
|
20548
|
+
|
|
20423
20549
|
// ../../packages/schema/src/token/cost-model.ts
|
|
20424
20550
|
var PROVIDER_PLATFORM = /* @__PURE__ */ new Map([
|
|
20425
20551
|
["anthropic", "anthropic"],
|
|
@@ -20726,6 +20852,15 @@ var FindingCategory = external_exports.enum([
|
|
|
20726
20852
|
]).meta({ id: "FindingCategory" });
|
|
20727
20853
|
var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
|
|
20728
20854
|
var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
|
|
20855
|
+
var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
|
|
20856
|
+
var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
|
|
20857
|
+
var FindingDelivery = external_exports.object({
|
|
20858
|
+
state: FindingDeliveryState,
|
|
20859
|
+
// The delivery time for `sent`; the failure time for `not_sent` when recorded.
|
|
20860
|
+
at: external_exports.iso.datetime().optional(),
|
|
20861
|
+
// Only on `not_sent`, and only when a known reason was recorded.
|
|
20862
|
+
reason: SyncFailureReason.optional()
|
|
20863
|
+
}).meta({ id: "FindingDelivery" });
|
|
20729
20864
|
var ResolutionMethod = external_exports.enum([
|
|
20730
20865
|
"enforced-in-flight",
|
|
20731
20866
|
"fixed-at-source",
|
|
@@ -20782,7 +20917,10 @@ var FindingInstance = external_exports.object({
|
|
|
20782
20917
|
// The session that event belongs to, when it has one — the seam a
|
|
20783
20918
|
// per-instance "view session" link needs. Absent for events captured
|
|
20784
20919
|
// outside a session.
|
|
20785
|
-
sessionId: external_exports.string().optional()
|
|
20920
|
+
sessionId: external_exports.string().optional(),
|
|
20921
|
+
// The delivery state of the event above (see FindingDelivery). Optional so
|
|
20922
|
+
// readers that do not project it stay valid.
|
|
20923
|
+
delivery: FindingDelivery.optional()
|
|
20786
20924
|
}).meta({ id: "FindingInstance" });
|
|
20787
20925
|
var FindingGroup = external_exports.object({
|
|
20788
20926
|
id: external_exports.string(),
|
|
@@ -20799,13 +20937,11 @@ var FindingGroup = external_exports.object({
|
|
|
20799
20937
|
latestDetectedAt: external_exports.iso.datetime(),
|
|
20800
20938
|
instances: external_exports.array(FindingInstance),
|
|
20801
20939
|
// Derived from instances' statuses with open-dominates precedence (see
|
|
20802
|
-
//
|
|
20940
|
+
// foldGroupStatus). Undefined only when no instance carries a status.
|
|
20803
20941
|
status: FindingStatus.optional(),
|
|
20804
|
-
// The distinct people across the WHOLE group, not just the
|
|
20805
|
-
//
|
|
20806
|
-
//
|
|
20807
|
-
// instance carries a user, or when the store supplied whole-group folds
|
|
20808
|
-
// without one.
|
|
20942
|
+
// The distinct people across the WHOLE group, not just the instances
|
|
20943
|
+
// carried here. Undefined when no instance carries a user, or when the
|
|
20944
|
+
// store supplied whole-group folds without one.
|
|
20809
20945
|
users: external_exports.array(FindingUser).optional()
|
|
20810
20946
|
}).meta({ id: "FindingGroup" });
|
|
20811
20947
|
var FindingStats = external_exports.object({
|
|
@@ -20834,21 +20970,34 @@ var FindingFacets = external_exports.object({
|
|
|
20834
20970
|
// counted under no value.
|
|
20835
20971
|
status: external_exports.array(FindingFacetItem),
|
|
20836
20972
|
// Host tool (attributes.tool_name). Present only on the instance-level
|
|
20837
|
-
// reads, which can filter by it; the
|
|
20973
|
+
// reads, which can filter by it; the type-level read omits the dimension
|
|
20838
20974
|
// because a group spans tools.
|
|
20839
|
-
tool: external_exports.array(FindingFacetItem).optional()
|
|
20975
|
+
tool: external_exports.array(FindingFacetItem).optional(),
|
|
20976
|
+
// Delivery states (FindingDeliveryState). Present only on the
|
|
20977
|
+
// instance-level reads, like `tool`.
|
|
20978
|
+
deployment: external_exports.array(FindingFacetItem).optional()
|
|
20840
20979
|
}).meta({ id: "FindingFacets" });
|
|
20841
|
-
var
|
|
20842
|
-
|
|
20980
|
+
var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
|
|
20981
|
+
id: "FindingTypeSummary"
|
|
20982
|
+
});
|
|
20983
|
+
var DEFAULT_FINDING_TYPES_LIMIT = 50;
|
|
20984
|
+
var MAX_FINDING_TYPES_LIMIT = 100;
|
|
20985
|
+
var ListFindingTypesQuery = external_exports.object({
|
|
20843
20986
|
// NOTE: severity filters by Severity (critical/high/medium/low), not by
|
|
20844
|
-
// FindingAction.
|
|
20987
|
+
// FindingAction. It narrows TYPES: a type's severity is the one its newest
|
|
20988
|
+
// firing version carries, and this list pages types.
|
|
20989
|
+
//
|
|
20990
|
+
// That is NOT a claim the findings of a type share it. A rule can hold several
|
|
20991
|
+
// definition versions at different severities, so a type kept by this filter
|
|
20992
|
+
// can hold findings that individually do not match — see totals.findings on
|
|
20993
|
+
// ListFindingTypesResponse, which counts them all.
|
|
20845
20994
|
severity: external_exports.array(Severity).optional(),
|
|
20846
20995
|
subtype: external_exports.array(external_exports.string()).optional(),
|
|
20847
20996
|
provider: external_exports.array(FindingProvider).optional(),
|
|
20848
20997
|
action: external_exports.array(FindingAction).optional(),
|
|
20849
|
-
// Matches a
|
|
20850
|
-
// individual
|
|
20851
|
-
//
|
|
20998
|
+
// Matches a type's DERIVED status (see FindingGroup.status), not its
|
|
20999
|
+
// individual findings' — so a filtered row's status always reads one of the
|
|
21000
|
+
// requested values.
|
|
20852
21001
|
status: external_exports.array(FindingStatus).optional(),
|
|
20853
21002
|
q: external_exports.string().optional(),
|
|
20854
21003
|
// Scope to findings whose event carries this session id (the Activity page's
|
|
@@ -20858,23 +21007,37 @@ var ListGroupedFindingsQuery = external_exports.object({
|
|
|
20858
21007
|
// from a time-scoped page (Activity's range) can carry that scope. Absent
|
|
20859
21008
|
// means all time — this list has no default window.
|
|
20860
21009
|
from: external_exports.iso.datetime().optional(),
|
|
20861
|
-
// A
|
|
20862
|
-
//
|
|
20863
|
-
//
|
|
20864
|
-
//
|
|
20865
|
-
//
|
|
21010
|
+
// A RULE id that must appear in the page even when the cursor has already
|
|
21011
|
+
// advanced past its sort position. This is what keeps the selected type
|
|
21012
|
+
// visible in the list once it paginates: the target is appended out of sort
|
|
21013
|
+
// order rather than scanned forward for. Never affects totals, facets or the
|
|
21014
|
+
// cursor. Unlike the grouped read this replaces, it names a rule only — an
|
|
21015
|
+
// instance id is resolved by `findingInstance`, which is a primary-key seek
|
|
21016
|
+
// and so is not bounded by what any page happens to hold.
|
|
20866
21017
|
includeId: external_exports.string().optional(),
|
|
20867
|
-
|
|
20868
|
-
limit: external_exports.coerce.number().int().min(1).max(100).optional(),
|
|
21018
|
+
limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
|
|
20869
21019
|
cursor: external_exports.string().optional()
|
|
20870
21020
|
});
|
|
20871
|
-
var
|
|
21021
|
+
var ListFindingTypesResponse = external_exports.object({
|
|
20872
21022
|
totals: external_exports.object({
|
|
21023
|
+
// Findings belonging to the matching TYPES — not findings that each match
|
|
21024
|
+
// the filters. The filters here select types, so a type that survives
|
|
21025
|
+
// contributes its whole instanceCount.
|
|
21026
|
+
//
|
|
21027
|
+
// `status` is the one exception, narrowed per finding via
|
|
21028
|
+
// countInstancesByStatus. `severity`, `provider` and `action` are not, so
|
|
21029
|
+
// this can exceed what the instance read reports for the same filters: a
|
|
21030
|
+
// rule whose severity moved between versions is kept on its newest and
|
|
21031
|
+
// still counts its older findings. Narrowing the other three needs
|
|
21032
|
+
// per-dimension counts the aggregate does not carry today.
|
|
20873
21033
|
findings: external_exports.number().int().nonnegative(),
|
|
20874
|
-
|
|
21034
|
+
// Counts TYPES, which is the unit this read pages. The instance read's
|
|
21035
|
+
// own totals count findings; the two deliberately answer different
|
|
21036
|
+
// questions and are never summed.
|
|
21037
|
+
types: external_exports.number().int().nonnegative()
|
|
20875
21038
|
}),
|
|
20876
21039
|
facets: FindingFacets,
|
|
20877
|
-
items: external_exports.array(
|
|
21040
|
+
items: external_exports.array(FindingTypeSummary),
|
|
20878
21041
|
nextCursor: external_exports.string().nullable(),
|
|
20879
21042
|
// Present only on session-scoped queries (`sessionId` set): per ruleId, how
|
|
20880
21043
|
// many times that rule fired in the session's persisted transcript. Findings
|
|
@@ -20882,7 +21045,7 @@ var ListGroupedFindingsResponse = external_exports.object({
|
|
|
20882
21045
|
// every firing, so the two numbers legitimately differ — this map lets a
|
|
20883
21046
|
// session-scoped view show both.
|
|
20884
21047
|
sessionFirings: external_exports.record(external_exports.string(), external_exports.number().int().nonnegative()).optional()
|
|
20885
|
-
}).meta({ id: "
|
|
21048
|
+
}).meta({ id: "ListFindingTypesResponse" });
|
|
20886
21049
|
var ApplyFindingActionRequest = external_exports.object({
|
|
20887
21050
|
// 'quarantined' is system-assigned (see FindingAction) — clients may not set
|
|
20888
21051
|
// it, so it is excluded from the request contract. The mapping helper
|
|
@@ -20912,16 +21075,19 @@ var DEFAULT_FLAT_FINDINGS_LIMIT = 50;
|
|
|
20912
21075
|
var MAX_FLAT_FINDINGS_LIMIT = 200;
|
|
20913
21076
|
var ListFindingInstancesQuery = external_exports.object({
|
|
20914
21077
|
severity: external_exports.array(Severity).optional(),
|
|
20915
|
-
// Rule ids, the same vocabulary the
|
|
21078
|
+
// Rule ids, the same vocabulary the types list's `subtype` carries. Pinning
|
|
21079
|
+
// ONE of them is how the master/detail view scopes its right-hand panel.
|
|
20916
21080
|
subtype: external_exports.array(external_exports.string()).optional(),
|
|
20917
21081
|
provider: external_exports.array(FindingProvider).optional(),
|
|
20918
21082
|
action: external_exports.array(FindingAction).optional(),
|
|
20919
21083
|
// Matches each instance's OWN derived status (deriveFindingStatus), unlike
|
|
20920
|
-
// the
|
|
21084
|
+
// the types query's type-level fold.
|
|
20921
21085
|
status: external_exports.array(FindingStatus).optional(),
|
|
20922
21086
|
// Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
|
|
20923
21087
|
// where the free-text `q` can only match the rendered "via Bash" label.
|
|
20924
21088
|
tool: external_exports.array(external_exports.string()).optional(),
|
|
21089
|
+
// The delivery state of each finding's event (see FindingDelivery).
|
|
21090
|
+
deployment: external_exports.array(FindingDeliveryState).optional(),
|
|
20925
21091
|
// Exact repository / file-path matches, for the drill-down out of the
|
|
20926
21092
|
// locations view. A row whose event carries no repo/file matches neither.
|
|
20927
21093
|
repo: external_exports.string().optional(),
|
|
@@ -20934,37 +21100,51 @@ var ListFindingInstancesQuery = external_exports.object({
|
|
|
20934
21100
|
});
|
|
20935
21101
|
var ListFindingInstancesResponse = external_exports.object({
|
|
20936
21102
|
// Instances matching the filters across the whole scope, not just this
|
|
20937
|
-
// page — cursor-independent, like the
|
|
21103
|
+
// page — cursor-independent, like the types list's totals.
|
|
20938
21104
|
totals: external_exports.object({ findings: external_exports.number().int().nonnegative() }),
|
|
20939
|
-
// Counts in INSTANCES here, where the
|
|
21105
|
+
// Counts in INSTANCES here, where the types response counts types. Each
|
|
20940
21106
|
// dimension still excludes its own filter.
|
|
20941
21107
|
facets: FindingFacets,
|
|
20942
21108
|
items: external_exports.array(FindingInstanceDetail),
|
|
20943
21109
|
nextCursor: external_exports.string().nullable()
|
|
20944
21110
|
}).meta({ id: "ListFindingInstancesResponse" });
|
|
20945
|
-
var
|
|
20946
|
-
|
|
20947
|
-
|
|
20948
|
-
|
|
20949
|
-
|
|
20950
|
-
|
|
20951
|
-
|
|
20952
|
-
//
|
|
20953
|
-
//
|
|
20954
|
-
|
|
20955
|
-
|
|
20956
|
-
// chips, and the count is what conveys scale.
|
|
20957
|
-
ruleIds: external_exports.array(external_exports.string())
|
|
20958
|
-
}).meta({ id: "FindingLocationFile" });
|
|
20959
|
-
var FindingLocationRepo = external_exports.object({
|
|
21111
|
+
var ListFindingInstancesPage = external_exports.object({
|
|
21112
|
+
items: external_exports.array(FindingInstanceDetail),
|
|
21113
|
+
nextCursor: external_exports.string().nullable()
|
|
21114
|
+
}).meta({ id: "ListFindingInstancesPage" });
|
|
21115
|
+
var FindingLocationSummary = external_exports.object({
|
|
21116
|
+
// Opaque, stable, minted from the pair by encodeLocationId. It exists
|
|
21117
|
+
// because a location's identity is two values and a URL param carries one:
|
|
21118
|
+
// `?loc=` names a location the way `?rule=` names a type. Only ever compared
|
|
21119
|
+
// for EQUALITY — the page's selection check, this read's `includeId`, the
|
|
21120
|
+
// client's page dedupe — never decoded, and never a sort key.
|
|
21121
|
+
id: external_exports.string(),
|
|
20960
21122
|
/** Empty when the instances carried no repo attribute. */
|
|
20961
21123
|
repo: external_exports.string(),
|
|
21124
|
+
// Empty when the instances carried no file path (a prompt, or a tool call
|
|
21125
|
+
// with no file attribution). Both halves empty is a real location — usually
|
|
21126
|
+
// the largest one in a store — and is selectable like any other.
|
|
21127
|
+
file: external_exports.string(),
|
|
20962
21128
|
instanceCount: external_exports.number().int().nonnegative(),
|
|
21129
|
+
// The WORST severity present, not the first row's. It is this list's primary
|
|
21130
|
+
// sort key, so it is also what explains why a row is where it is, and it is
|
|
21131
|
+
// how a reader decides what to open without opening everything.
|
|
20963
21132
|
maxSeverity: Severity,
|
|
20964
21133
|
latestDetectedAt: external_exports.iso.datetime(),
|
|
21134
|
+
// Folded from the instances' derived statuses with the same open-dominates
|
|
21135
|
+
// precedence a group uses, so it answers "is anything left to do here" and
|
|
21136
|
+
// not much more: a location holding 1 open among 40 resolved reads like one
|
|
21137
|
+
// holding 40 open. That loss is accepted — the panel beside this list
|
|
21138
|
+
// carries each finding's own status, and instanceCount sits next to the
|
|
21139
|
+
// badge.
|
|
20965
21140
|
status: FindingStatus.optional(),
|
|
20966
|
-
|
|
20967
|
-
|
|
21141
|
+
// Every distinct rule seen at this location, UNCAPPED — so the length is a
|
|
21142
|
+
// tally rather than a sample and a row can say how many there are. Bounded
|
|
21143
|
+
// by the ruleset, not by the store. The view bounds what it DISPLAYS.
|
|
21144
|
+
ruleIds: external_exports.array(external_exports.string())
|
|
21145
|
+
}).meta({ id: "FindingLocationSummary" });
|
|
21146
|
+
var DEFAULT_FINDING_LOCATIONS_LIMIT = 50;
|
|
21147
|
+
var MAX_FINDING_LOCATIONS_LIMIT = 100;
|
|
20968
21148
|
var ListFindingLocationsQuery = external_exports.object({
|
|
20969
21149
|
severity: external_exports.array(Severity).optional(),
|
|
20970
21150
|
subtype: external_exports.array(external_exports.string()).optional(),
|
|
@@ -20974,21 +21154,47 @@ var ListFindingLocationsQuery = external_exports.object({
|
|
|
20974
21154
|
// instances that match, and folds its status from those.
|
|
20975
21155
|
status: external_exports.array(FindingStatus).optional(),
|
|
20976
21156
|
tool: external_exports.array(external_exports.string()).optional(),
|
|
21157
|
+
// The delivery state of each finding's event (see FindingDelivery).
|
|
21158
|
+
deployment: external_exports.array(FindingDeliveryState).optional(),
|
|
20977
21159
|
q: external_exports.string().optional(),
|
|
20978
21160
|
sessionId: external_exports.string().optional(),
|
|
20979
21161
|
from: external_exports.iso.datetime().optional(),
|
|
20980
|
-
|
|
21162
|
+
// A LOCATION id (see FindingLocationSummary.id) that must appear in the page
|
|
21163
|
+
// even when the cursor has already advanced past its sort position — the
|
|
21164
|
+
// counterpart of ListFindingTypesQuery.includeId, and needed far more often
|
|
21165
|
+
// here. Selecting a row pushes the URL, which re-renders the server and resets
|
|
21166
|
+
// the client's page cache to page 0; with distinct (repo, file) pairs running
|
|
21167
|
+
// into the thousands, a selection sitting off page 0 is the ordinary case
|
|
21168
|
+
// rather than a deep-link corner. Never affects totals, facets or the cursor.
|
|
21169
|
+
includeId: external_exports.string().optional(),
|
|
21170
|
+
limit: external_exports.coerce.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
|
|
21171
|
+
cursor: external_exports.string().optional()
|
|
20981
21172
|
});
|
|
20982
21173
|
var ListFindingLocationsResponse = external_exports.object({
|
|
20983
21174
|
totals: external_exports.object({
|
|
21175
|
+
// Findings matching the filters across the whole scope. Unlike the types
|
|
21176
|
+
// read's same-named field this needs no caveat: the filters here narrow
|
|
21177
|
+
// per finding, so this is the sum of every row's instanceCount.
|
|
20984
21178
|
findings: external_exports.number().int().nonnegative(),
|
|
20985
|
-
|
|
20986
|
-
|
|
21179
|
+
// Counts LOCATIONS, the unit this read pages — the number the paginator
|
|
21180
|
+
// states. The facets beside it count FINDINGS (see below); a surface
|
|
21181
|
+
// showing both says which is which.
|
|
21182
|
+
locations: external_exports.number().int().nonnegative()
|
|
20987
21183
|
}),
|
|
20988
|
-
|
|
20989
|
-
|
|
20990
|
-
|
|
20991
|
-
|
|
21184
|
+
// Counts in FINDINGS, where the types response counts types, each dimension
|
|
21185
|
+
// still excluding its own filter. Deliberately not locations: counting those
|
|
21186
|
+
// needs a set of location keys per dimension per value — memory tracking the
|
|
21187
|
+
// store times the vocabulary, in a read whose scan promises flat memory —
|
|
21188
|
+
// and the cheap per-location version is not an approximation but WRONG. A
|
|
21189
|
+
// location holding {claudecode, block} and {codex, warn} would survive
|
|
21190
|
+
// provider=claudecode AND action=warn, under which no single finding
|
|
21191
|
+
// matches, so the facet would contradict the instanceCount this whole view
|
|
21192
|
+
// rests on. Findings also keep the toolbar in the same unit as the page
|
|
21193
|
+
// tally and the panel it sits above.
|
|
21194
|
+
facets: FindingFacets,
|
|
21195
|
+
/** Sorted by max severity, then most recent, then (repo, file). */
|
|
21196
|
+
items: external_exports.array(FindingLocationSummary),
|
|
21197
|
+
nextCursor: external_exports.string().nullable()
|
|
20992
21198
|
}).meta({ id: "ListFindingLocationsResponse" });
|
|
20993
21199
|
|
|
20994
21200
|
// ../../packages/schema/src/zod/meta.ts
|
|
@@ -21152,6 +21358,10 @@ var CaptureAttributes = external_exports.object({
|
|
|
21152
21358
|
// to 'allow' — the enforcement audit trail's link back to the grant that
|
|
21153
21359
|
// authorized the bypass.
|
|
21154
21360
|
exception_ids: external_exports.array(external_exports.guid()).optional(),
|
|
21361
|
+
// The persisted spellings of EventMetadata's messageId/conversationId — the
|
|
21362
|
+
// join back to the `llm_call` leaf for the same assistant turn.
|
|
21363
|
+
message_id: external_exports.string().optional(),
|
|
21364
|
+
conversation_id: external_exports.string().optional(),
|
|
21155
21365
|
// Whole milliseconds this capture's inspection blocked its caller — the
|
|
21156
21366
|
// plugin's own added latency (see EventMetadata.inspectionMs, whose value
|
|
21157
21367
|
// this is). Promoted to the `inspection_ms` generated column so the facet is
|
|
@@ -21160,7 +21370,19 @@ var CaptureAttributes = external_exports.object({
|
|
|
21160
21370
|
// inline json_extract and is not itself an optimization.
|
|
21161
21371
|
// ABSENT on replayed captures (backfill / worktree scan) and on rows written
|
|
21162
21372
|
// before the measurement shipped — never present as a placeholder 0.
|
|
21163
|
-
inspection_ms: external_exports.number().int().nonnegative().optional()
|
|
21373
|
+
inspection_ms: external_exports.number().int().nonnegative().optional(),
|
|
21374
|
+
// What a `redact` this capture could not carry out became instead (see
|
|
21375
|
+
// EventMetadata.redactDegradedTo, whose value this is). Present only when a
|
|
21376
|
+
// degrade actually happened, so absence is the ordinary case rather than a
|
|
21377
|
+
// reader having to distinguish it from a zero.
|
|
21378
|
+
//
|
|
21379
|
+
// PER CAPTURE, while `inspection_findings.action_taken` is per finding —
|
|
21380
|
+
// so on a multi-finding row this does not say which finding degraded, and
|
|
21381
|
+
// its presence does not mean the fallback decided the capture's action. A
|
|
21382
|
+
// capture denied by another finding's own Block policy carries `block`
|
|
21383
|
+
// here too. The full statement is on EventMetadata.redactDegradedTo; it is
|
|
21384
|
+
// repeated rather than referenced because a store reader opens this file.
|
|
21385
|
+
redact_degraded_to: ActionTaken.optional()
|
|
21164
21386
|
}).catchall(external_exports.unknown());
|
|
21165
21387
|
var ToolCallInspection = external_exports.object({
|
|
21166
21388
|
ruleId: external_exports.string().min(1),
|
|
@@ -21359,7 +21581,17 @@ var AuditEvent = external_exports.object({
|
|
|
21359
21581
|
/** `share` to a first-party/internal destination. */
|
|
21360
21582
|
internal: external_exports.boolean(),
|
|
21361
21583
|
/** Event needs review (e.g. unverified egress). */
|
|
21362
|
-
flagged: external_exports.boolean()
|
|
21584
|
+
flagged: external_exports.boolean(),
|
|
21585
|
+
/**
|
|
21586
|
+
* The body this event's `title` is drawn from was cleared by local body
|
|
21587
|
+
* expiry, so an EMPTY title here means "gone", not "never had one".
|
|
21588
|
+
*
|
|
21589
|
+
* A separate flag rather than a sentinel written into `title`: the title is
|
|
21590
|
+
* rendered text, and a store-layer module that invented display copy for it
|
|
21591
|
+
* would be choosing words the view is supposed to choose. Additive and
|
|
21592
|
+
* defaulted, so an older producer still validates.
|
|
21593
|
+
*/
|
|
21594
|
+
bodyExpired: external_exports.boolean().default(false)
|
|
21363
21595
|
}).meta({ id: "ActivityAuditEvent" });
|
|
21364
21596
|
var ActivitySessionSummary = external_exports.object({
|
|
21365
21597
|
id: external_exports.string(),
|
|
@@ -22157,6 +22389,14 @@ var ControlPlaneErrorBody = external_exports.object({
|
|
|
22157
22389
|
message: external_exports.string().optional()
|
|
22158
22390
|
}).optional()
|
|
22159
22391
|
});
|
|
22392
|
+
var RemoteFailureKind = external_exports.enum([
|
|
22393
|
+
"unauthorized",
|
|
22394
|
+
"forbidden",
|
|
22395
|
+
"route-absent",
|
|
22396
|
+
"invalid-request",
|
|
22397
|
+
"rejected",
|
|
22398
|
+
"unreachable"
|
|
22399
|
+
]);
|
|
22160
22400
|
var AttachDeviceRequest = external_exports.object({
|
|
22161
22401
|
// This machine's own continuity id, so re-attaching ROTATES the credential
|
|
22162
22402
|
// on one machine record instead of producing a second one. Client-minted
|
|
@@ -22692,6 +22932,12 @@ var EventMetadata = external_exports.object({
|
|
|
22692
22932
|
// to 'allow' — the enforcement audit trail's link back to the grant that
|
|
22693
22933
|
// authorized the bypass. Absent on captures where no exception applied.
|
|
22694
22934
|
exceptionIds: external_exports.array(external_exports.guid()).optional(),
|
|
22935
|
+
// The assistant message this capture belongs to, and the conversation it sits
|
|
22936
|
+
// in — set by the browser extension's network capture so a stored `response`
|
|
22937
|
+
// row can be joined to the `llm_call` leaf describing the same turn. Absent
|
|
22938
|
+
// on every other capture path, which has no such id.
|
|
22939
|
+
messageId: external_exports.string().optional(),
|
|
22940
|
+
conversationId: external_exports.string().optional(),
|
|
22695
22941
|
// How long THIS capture's inspection blocked its caller, in whole
|
|
22696
22942
|
// milliseconds — the plugin's own added latency, NOT the LLM call it sat in
|
|
22697
22943
|
// front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
|
|
@@ -22704,7 +22950,37 @@ var EventMetadata = external_exports.object({
|
|
|
22704
22950
|
// Absent is also what every pre-measurement client writes, and what a
|
|
22705
22951
|
// clock failure degrades to — a reader must treat absence as "not measured"
|
|
22706
22952
|
// and never as a zero, which would read as "inspection is free".
|
|
22707
|
-
inspectionMs: external_exports.number().int().nonnegative().optional()
|
|
22953
|
+
inspectionMs: external_exports.number().int().nonnegative().optional(),
|
|
22954
|
+
// What a `redact` this capture COULD NOT CARRY OUT became instead — the
|
|
22955
|
+
// workspace's `redactFallback`, applied because the field could not be
|
|
22956
|
+
// masked in place (a shell command, a URL, or any argument on a host whose
|
|
22957
|
+
// hook contract offers no rewrite channel).
|
|
22958
|
+
//
|
|
22959
|
+
// It exists because the action alone cannot say why. A finding recorded as
|
|
22960
|
+
// `warn` reads identically whether its detection was ASSIGNED Warn or was
|
|
22961
|
+
// assigned Redact on a field that could not take one — and those are
|
|
22962
|
+
// different facts about the same row: the first is a policy the user chose,
|
|
22963
|
+
// the second is a masking the host could not perform. Absent means no
|
|
22964
|
+
// degrade happened, which is every ordinary capture.
|
|
22965
|
+
//
|
|
22966
|
+
// TWO LIMITS a reader of a stored row has to know, because the grain here
|
|
22967
|
+
// is the CAPTURE while `actionTaken` is per FINDING:
|
|
22968
|
+
//
|
|
22969
|
+
// - It does not say WHICH finding degraded. A capture carrying a degraded
|
|
22970
|
+
// `redact` alongside a finding ASSIGNED the same action stores both
|
|
22971
|
+
// identically and one reason for the pair; attributing it to both
|
|
22972
|
+
// describes the assigned one wrongly, and to neither loses the degrade.
|
|
22973
|
+
// - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
|
|
22974
|
+
// became, not the reason the capture ended as it did — a capture denied
|
|
22975
|
+
// by some other finding's own Block policy still carries `block` here,
|
|
22976
|
+
// and clearing the workspace's fallback would not have let it through.
|
|
22977
|
+
// Gate on the value against what a fallback can produce; never read the
|
|
22978
|
+
// field's presence as "this was the fallback's doing".
|
|
22979
|
+
//
|
|
22980
|
+
// Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
|
|
22981
|
+
// Closing either means moving the reason onto the finding row, which
|
|
22982
|
+
// already carries its own action.
|
|
22983
|
+
redactDegradedTo: ActionTaken.optional()
|
|
22708
22984
|
}).meta({ id: "EventMetadata" });
|
|
22709
22985
|
var Event = external_exports.object({
|
|
22710
22986
|
id: external_exports.guid(),
|
|
@@ -22814,7 +23090,32 @@ var RotateKeyInput = external_exports.object({
|
|
|
22814
23090
|
confirmation: external_exports.string()
|
|
22815
23091
|
});
|
|
22816
23092
|
|
|
23093
|
+
// ../../packages/schema/src/zod/finding-delivery.ts
|
|
23094
|
+
var KNOWN_REASONS = SyncFailureReason.options;
|
|
23095
|
+
function knownReason(value) {
|
|
23096
|
+
return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
|
|
23097
|
+
}
|
|
23098
|
+
function deriveFindingDelivery(row) {
|
|
23099
|
+
if (row.kind === "code_change") return { state: "local_scan" };
|
|
23100
|
+
if (row.syncedAt !== null && row.syncedAt > 0) {
|
|
23101
|
+
return { state: "sent", at: epochMillisToIso(row.syncedAt) };
|
|
23102
|
+
}
|
|
23103
|
+
if (row.syncedAt !== null) {
|
|
23104
|
+
const reason = knownReason(row.syncFailure);
|
|
23105
|
+
return {
|
|
23106
|
+
state: "not_sent",
|
|
23107
|
+
...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
|
|
23108
|
+
...reason === void 0 ? {} : { reason }
|
|
23109
|
+
};
|
|
23110
|
+
}
|
|
23111
|
+
if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
|
|
23112
|
+
return { state: "never_offered" };
|
|
23113
|
+
}
|
|
23114
|
+
|
|
22817
23115
|
// ../../packages/schema/src/zod/findings-group-build.ts
|
|
23116
|
+
function lookupOwn(map2, key) {
|
|
23117
|
+
return Object.hasOwn(map2, key) ? map2[key] : void 0;
|
|
23118
|
+
}
|
|
22818
23119
|
function toApiAction(dbVal) {
|
|
22819
23120
|
const map2 = {
|
|
22820
23121
|
log: "monitored",
|
|
@@ -22823,7 +23124,7 @@ function toApiAction(dbVal) {
|
|
|
22823
23124
|
warn: "warned",
|
|
22824
23125
|
allow: "allowed"
|
|
22825
23126
|
};
|
|
22826
|
-
return map2
|
|
23127
|
+
return lookupOwn(map2, dbVal) ?? "allowed";
|
|
22827
23128
|
}
|
|
22828
23129
|
function toApiCategory(dbVal) {
|
|
22829
23130
|
if (dbVal === "code_context") return "source_code";
|
|
@@ -22831,13 +23132,18 @@ function toApiCategory(dbVal) {
|
|
|
22831
23132
|
return parsed2.success ? parsed2.data : "custom";
|
|
22832
23133
|
}
|
|
22833
23134
|
function toApiProvider(sourceTool) {
|
|
22834
|
-
return TOOL_TO_HARNESS
|
|
23135
|
+
return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
|
|
22835
23136
|
}
|
|
22836
|
-
var
|
|
23137
|
+
var FINDING_STATUS_PRECEDENCE = [
|
|
23138
|
+
"open",
|
|
23139
|
+
"handled",
|
|
23140
|
+
"dismissed",
|
|
23141
|
+
"resolved"
|
|
23142
|
+
];
|
|
22837
23143
|
function foldGroupStatus(instanceStatuses) {
|
|
22838
23144
|
const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
|
|
22839
23145
|
if (statuses.size === 0) return void 0;
|
|
22840
|
-
for (const candidate of
|
|
23146
|
+
for (const candidate of FINDING_STATUS_PRECEDENCE) {
|
|
22841
23147
|
if (statuses.has(candidate)) return candidate;
|
|
22842
23148
|
}
|
|
22843
23149
|
return void 0;
|
|
@@ -22850,139 +23156,62 @@ function deriveFindingStatus(row) {
|
|
|
22850
23156
|
if (row.latestResolutionStatus === "dismissed") return "dismissed";
|
|
22851
23157
|
return "open";
|
|
22852
23158
|
}
|
|
22853
|
-
function distinctUsers(instances) {
|
|
22854
|
-
const seen = /* @__PURE__ */ new Set();
|
|
22855
|
-
const users = [];
|
|
22856
|
-
for (const i of instances) {
|
|
22857
|
-
if (i.user === void 0 || seen.has(i.user.id)) continue;
|
|
22858
|
-
seen.add(i.user.id);
|
|
22859
|
-
users.push(i.user);
|
|
22860
|
-
}
|
|
22861
|
-
return users;
|
|
22862
|
-
}
|
|
22863
23159
|
function sortUsers(users) {
|
|
22864
23160
|
return [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
|
|
22865
23161
|
}
|
|
22866
|
-
function
|
|
22867
|
-
const overrides = opts.overrides;
|
|
23162
|
+
function buildFindingTypes(aggregates, opts = {}) {
|
|
22868
23163
|
const packNames = opts.packNames;
|
|
22869
|
-
const
|
|
22870
|
-
const
|
|
22871
|
-
|
|
22872
|
-
const
|
|
22873
|
-
|
|
22874
|
-
else byRuleId.set(row.ruleId, [row]);
|
|
22875
|
-
}
|
|
22876
|
-
const groups = [];
|
|
22877
|
-
for (const [ruleId, ruleRows] of byRuleId) {
|
|
22878
|
-
const instances = ruleRows.map((r) => {
|
|
22879
|
-
const effectiveDbAction = overrides?.get(r.id) ?? r.actionTaken;
|
|
22880
|
-
return {
|
|
22881
|
-
id: r.id,
|
|
22882
|
-
provider: toApiProvider(r.sourceTool),
|
|
22883
|
-
repo: r.repo,
|
|
22884
|
-
file: r.file,
|
|
22885
|
-
...r.toolName === void 0 ? {} : { toolName: r.toolName },
|
|
22886
|
-
...r.eventId === void 0 ? {} : { eventId: r.eventId },
|
|
22887
|
-
...r.sessionId === void 0 ? {} : { sessionId: r.sessionId },
|
|
22888
|
-
...r.user === void 0 ? {} : { user: r.user },
|
|
22889
|
-
action: toApiAction(effectiveDbAction),
|
|
22890
|
-
detectedAt: r.occurredAt,
|
|
22891
|
-
confidence: r.confidence,
|
|
22892
|
-
status: r.status
|
|
22893
|
-
};
|
|
22894
|
-
});
|
|
22895
|
-
const agg = aggregates?.get(ruleId);
|
|
22896
|
-
const users = agg ? sortUsers(agg.users ?? []) : distinctUsers(instances);
|
|
22897
|
-
const latestDetectedAt = agg?.latestDetectedAt ?? ruleRows.reduce(
|
|
22898
|
-
(max, r) => r.occurredAt > max ? r.occurredAt : max,
|
|
22899
|
-
ruleRows[0]?.occurredAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
|
|
22900
|
-
);
|
|
22901
|
-
const seenProviders = /* @__PURE__ */ new Set();
|
|
22902
|
-
const providers = (agg ? [...new Set(agg.sourceTools.map(toApiProvider))].sort() : instances.map((i) => i.provider)).filter((p) => {
|
|
22903
|
-
if (seenProviders.has(p)) return false;
|
|
22904
|
-
seenProviders.add(p);
|
|
22905
|
-
return true;
|
|
22906
|
-
});
|
|
22907
|
-
const actionSet = new Set(
|
|
22908
|
-
agg ? agg.actionsTaken.map(toApiAction) : instances.map((i) => i.action)
|
|
22909
|
-
);
|
|
23164
|
+
const types = [];
|
|
23165
|
+
for (const [ruleId, agg] of aggregates) {
|
|
23166
|
+
const users = sortUsers(agg.users ?? []);
|
|
23167
|
+
const providers = [...new Set(agg.sourceTools.map(toApiProvider))].sort();
|
|
23168
|
+
const actionSet = new Set(agg.actionsTaken.map(toApiAction));
|
|
22910
23169
|
const aggregateAction = actionSet.size === 1 ? [...actionSet][0] ?? null : null;
|
|
22911
|
-
const
|
|
22912
|
-
const
|
|
22913
|
-
id: ruleId,
|
|
22914
|
-
name: packNames?.get(ruleId) ?? null
|
|
22915
|
-
};
|
|
22916
|
-
const apiCategory = toApiCategory(ruleRows[0]?.category ?? "custom");
|
|
22917
|
-
const policy = { id: `category:${apiCategory}`, name: apiCategory };
|
|
22918
|
-
const match = {
|
|
22919
|
-
maskedValue: ruleRows[0]?.maskedMatch ?? "",
|
|
22920
|
-
contextPrefix: ""
|
|
22921
|
-
// empty (pending privacy review)
|
|
22922
|
-
};
|
|
22923
|
-
const status = foldGroupStatus(
|
|
22924
|
-
agg ? agg.statusInputs.map(deriveFindingStatus) : instances.map((i) => i.status)
|
|
22925
|
-
);
|
|
22926
|
-
const group = {
|
|
23170
|
+
const apiCategory = toApiCategory(agg.category ?? "custom");
|
|
23171
|
+
const type = {
|
|
22927
23172
|
id: ruleId,
|
|
22928
23173
|
category: apiCategory,
|
|
22929
23174
|
subtype: ruleId,
|
|
22930
23175
|
// human label comes with pack metadata later
|
|
22931
|
-
severity,
|
|
22932
|
-
|
|
22933
|
-
|
|
22934
|
-
|
|
22935
|
-
instanceCount: agg?.instanceCount ?? instances.length,
|
|
23176
|
+
severity: agg.severity ?? "low",
|
|
23177
|
+
detection: { id: ruleId, name: packNames?.get(ruleId) ?? null },
|
|
23178
|
+
policy: { id: `category:${apiCategory}`, name: apiCategory },
|
|
23179
|
+
instanceCount: agg.instanceCount,
|
|
22936
23180
|
providers,
|
|
22937
23181
|
aggregateAction,
|
|
22938
|
-
latestDetectedAt,
|
|
22939
|
-
|
|
22940
|
-
status,
|
|
23182
|
+
latestDetectedAt: agg.latestDetectedAt,
|
|
23183
|
+
status: foldGroupStatus(agg.statusInputs.map(deriveFindingStatus)),
|
|
22941
23184
|
...users.length > 0 ? { users } : {}
|
|
22942
23185
|
};
|
|
22943
|
-
|
|
22944
|
-
|
|
22945
|
-
|
|
22946
|
-
haystackCache.set(group, buildHaystack(group, agg.searchText));
|
|
22947
|
-
}
|
|
23186
|
+
actionsCache.set(type, [...actionSet]);
|
|
23187
|
+
if (agg.searchText !== void 0) {
|
|
23188
|
+
haystackCache.set(type, buildHaystack(type, agg.searchText));
|
|
22948
23189
|
}
|
|
22949
|
-
|
|
23190
|
+
types.push(type);
|
|
22950
23191
|
}
|
|
22951
|
-
return
|
|
23192
|
+
return types;
|
|
22952
23193
|
}
|
|
22953
23194
|
var haystackCache = /* @__PURE__ */ new WeakMap();
|
|
22954
|
-
function buildHaystack(
|
|
23195
|
+
function buildHaystack(t, extra) {
|
|
22955
23196
|
return [
|
|
22956
|
-
|
|
22957
|
-
|
|
22958
|
-
|
|
22959
|
-
|
|
22960
|
-
|
|
22961
|
-
...g.instances.map((i) => i.repo),
|
|
22962
|
-
...g.instances.map((i) => i.file),
|
|
22963
|
-
...g.instances.map((i) => i.toolName ? `via ${i.toolName}` : ""),
|
|
22964
|
-
...g.instances.map((i) => i.id),
|
|
22965
|
-
// The people: the whole group's list when the store folded one, plus the
|
|
22966
|
-
// preview's own — the two overlap, and a haystack does not mind.
|
|
22967
|
-
...(g.users ?? []).map((u) => u.name),
|
|
22968
|
-
...g.instances.map((i) => i.user?.name ?? ""),
|
|
23197
|
+
t.subtype,
|
|
23198
|
+
t.category,
|
|
23199
|
+
t.policy.name,
|
|
23200
|
+
t.id,
|
|
23201
|
+
...(t.users ?? []).map((u) => u.name),
|
|
22969
23202
|
...extra === void 0 ? [] : [extra]
|
|
22970
23203
|
].join(" ").toLowerCase();
|
|
22971
23204
|
}
|
|
22972
|
-
function
|
|
22973
|
-
const cached2 = haystackCache.get(
|
|
23205
|
+
function typeHaystack(t) {
|
|
23206
|
+
const cached2 = haystackCache.get(t);
|
|
22974
23207
|
if (cached2 !== void 0) return cached2;
|
|
22975
|
-
const haystack = buildHaystack(
|
|
22976
|
-
haystackCache.set(
|
|
23208
|
+
const haystack = buildHaystack(t);
|
|
23209
|
+
haystackCache.set(t, haystack);
|
|
22977
23210
|
return haystack;
|
|
22978
23211
|
}
|
|
22979
23212
|
var actionsCache = /* @__PURE__ */ new WeakMap();
|
|
22980
|
-
function
|
|
22981
|
-
|
|
22982
|
-
if (cached2 !== void 0) return cached2;
|
|
22983
|
-
const actions = [...new Set(g.instances.map((i) => i.action))];
|
|
22984
|
-
actionsCache.set(g, actions);
|
|
22985
|
-
return actions;
|
|
23213
|
+
function typeActions(t) {
|
|
23214
|
+
return actionsCache.get(t) ?? [];
|
|
22986
23215
|
}
|
|
22987
23216
|
function countInstancesByStatus(statusInputs, statuses) {
|
|
22988
23217
|
const statusSet = new Set(statuses);
|
|
@@ -22993,8 +23222,8 @@ function countInstancesByStatus(statusInputs, statuses) {
|
|
|
22993
23222
|
}
|
|
22994
23223
|
return sum;
|
|
22995
23224
|
}
|
|
22996
|
-
function applyFindingFilters(
|
|
22997
|
-
let filtered =
|
|
23225
|
+
function applyFindingFilters(types, opts) {
|
|
23226
|
+
let filtered = types;
|
|
22998
23227
|
if (opts.severity && opts.severity.length > 0) {
|
|
22999
23228
|
const sevSet = new Set(opts.severity);
|
|
23000
23229
|
filtered = filtered.filter((g) => sevSet.has(g.severity));
|
|
@@ -23005,7 +23234,7 @@ function applyFindingFilters(groups, opts) {
|
|
|
23005
23234
|
}
|
|
23006
23235
|
if (opts.actions && opts.actions.length > 0) {
|
|
23007
23236
|
const actionSet = new Set(opts.actions);
|
|
23008
|
-
filtered = filtered.filter((
|
|
23237
|
+
filtered = filtered.filter((t) => typeActions(t).some((a) => actionSet.has(a)));
|
|
23009
23238
|
}
|
|
23010
23239
|
if (opts.subtype && opts.subtype.length > 0) {
|
|
23011
23240
|
const subtypeSet = new Set(opts.subtype);
|
|
@@ -23017,26 +23246,31 @@ function applyFindingFilters(groups, opts) {
|
|
|
23017
23246
|
}
|
|
23018
23247
|
if (opts.q) {
|
|
23019
23248
|
const q = opts.q.toLowerCase();
|
|
23020
|
-
filtered = filtered.filter((
|
|
23249
|
+
filtered = filtered.filter((t) => typeHaystack(t).includes(q));
|
|
23021
23250
|
}
|
|
23022
23251
|
return filtered;
|
|
23023
23252
|
}
|
|
23024
|
-
|
|
23025
|
-
|
|
23253
|
+
function rankByOrder(members2) {
|
|
23254
|
+
return Object.fromEntries(members2.map((member, index) => [member, index]));
|
|
23255
|
+
}
|
|
23256
|
+
var SEVERITY_RANK = rankByOrder(Severity.options);
|
|
23257
|
+
function severityRank(severity) {
|
|
23258
|
+
return lookupOwn(SEVERITY_RANK, severity);
|
|
23259
|
+
}
|
|
23026
23260
|
function compareFindingGroupOrder(a, b) {
|
|
23027
|
-
const rankA =
|
|
23028
|
-
const rankB =
|
|
23261
|
+
const rankA = severityRank(a.severity) ?? -1;
|
|
23262
|
+
const rankB = severityRank(b.severity) ?? -1;
|
|
23029
23263
|
const severityDiff = rankA - rankB;
|
|
23030
23264
|
if (severityDiff !== 0) return severityDiff;
|
|
23031
23265
|
const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
|
|
23032
23266
|
if (recencyDiff !== 0) return recencyDiff;
|
|
23033
23267
|
return a.id.localeCompare(b.id);
|
|
23034
23268
|
}
|
|
23035
|
-
function
|
|
23036
|
-
return [...
|
|
23269
|
+
function sortFindingTypes(types) {
|
|
23270
|
+
return [...types].sort(compareFindingGroupOrder);
|
|
23037
23271
|
}
|
|
23038
|
-
function computeFindingFacets(
|
|
23039
|
-
const forSeverity = applyFindingFilters(
|
|
23272
|
+
function computeFindingFacets(allTypes, opts) {
|
|
23273
|
+
const forSeverity = applyFindingFilters(allTypes, {
|
|
23040
23274
|
providers: opts.providers,
|
|
23041
23275
|
actions: opts.actions,
|
|
23042
23276
|
statuses: opts.statuses,
|
|
@@ -23047,7 +23281,7 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
23047
23281
|
for (const g of forSeverity) {
|
|
23048
23282
|
severityMap.set(g.severity, (severityMap.get(g.severity) ?? 0) + 1);
|
|
23049
23283
|
}
|
|
23050
|
-
const forProvider = applyFindingFilters(
|
|
23284
|
+
const forProvider = applyFindingFilters(allTypes, {
|
|
23051
23285
|
actions: opts.actions,
|
|
23052
23286
|
statuses: opts.statuses,
|
|
23053
23287
|
q: opts.q,
|
|
@@ -23058,7 +23292,7 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
23058
23292
|
for (const g of forProvider) {
|
|
23059
23293
|
for (const p of g.providers) providerMap.set(p, (providerMap.get(p) ?? 0) + 1);
|
|
23060
23294
|
}
|
|
23061
|
-
const forAction = applyFindingFilters(
|
|
23295
|
+
const forAction = applyFindingFilters(allTypes, {
|
|
23062
23296
|
providers: opts.providers,
|
|
23063
23297
|
statuses: opts.statuses,
|
|
23064
23298
|
q: opts.q,
|
|
@@ -23067,9 +23301,9 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
23067
23301
|
});
|
|
23068
23302
|
const actionMap = /* @__PURE__ */ new Map();
|
|
23069
23303
|
for (const g of forAction) {
|
|
23070
|
-
for (const a of
|
|
23304
|
+
for (const a of typeActions(g)) actionMap.set(a, (actionMap.get(a) ?? 0) + 1);
|
|
23071
23305
|
}
|
|
23072
|
-
const forSubtype = applyFindingFilters(
|
|
23306
|
+
const forSubtype = applyFindingFilters(allTypes, {
|
|
23073
23307
|
providers: opts.providers,
|
|
23074
23308
|
actions: opts.actions,
|
|
23075
23309
|
statuses: opts.statuses,
|
|
@@ -23078,7 +23312,7 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
23078
23312
|
});
|
|
23079
23313
|
const subtypeMap = /* @__PURE__ */ new Map();
|
|
23080
23314
|
for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
|
|
23081
|
-
const forStatus = applyFindingFilters(
|
|
23315
|
+
const forStatus = applyFindingFilters(allTypes, {
|
|
23082
23316
|
providers: opts.providers,
|
|
23083
23317
|
actions: opts.actions,
|
|
23084
23318
|
q: opts.q,
|
|
@@ -23100,6 +23334,20 @@ function computeFindingFacets(allGroups, opts) {
|
|
|
23100
23334
|
}
|
|
23101
23335
|
|
|
23102
23336
|
// ../../packages/schema/src/zod/findings-flat-build.ts
|
|
23337
|
+
function compareCodePoints(a, b) {
|
|
23338
|
+
const aIter = a[Symbol.iterator]();
|
|
23339
|
+
const bIter = b[Symbol.iterator]();
|
|
23340
|
+
for (; ; ) {
|
|
23341
|
+
const aNext = aIter.next();
|
|
23342
|
+
const bNext = bIter.next();
|
|
23343
|
+
if (aNext.done && bNext.done) return 0;
|
|
23344
|
+
if (aNext.done) return -1;
|
|
23345
|
+
if (bNext.done) return 1;
|
|
23346
|
+
const aPoint = aNext.value.codePointAt(0) ?? 0;
|
|
23347
|
+
const bPoint = bNext.value.codePointAt(0) ?? 0;
|
|
23348
|
+
if (aPoint !== bPoint) return aPoint - bPoint;
|
|
23349
|
+
}
|
|
23350
|
+
}
|
|
23103
23351
|
function rowHaystack(row) {
|
|
23104
23352
|
return [
|
|
23105
23353
|
row.ruleId,
|
|
@@ -23124,12 +23372,24 @@ function matchesDimension(row, opts, dimension) {
|
|
|
23124
23372
|
return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
|
|
23125
23373
|
case "statuses":
|
|
23126
23374
|
return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
|
|
23375
|
+
case "deliveries":
|
|
23376
|
+
return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
|
|
23127
23377
|
case "tools":
|
|
23128
23378
|
return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
|
|
23379
|
+
// An EMPTY value is a real filter here, not an absent one. The location
|
|
23380
|
+
// list buckets a finding whose event recorded no repo — or no file — under
|
|
23381
|
+
// the empty string, and selecting that bucket has to narrow the panel to
|
|
23382
|
+
// exactly it. Only `undefined` means "no filter"; a caller that wants every
|
|
23383
|
+
// row omits the key, which every call site already does.
|
|
23384
|
+
//
|
|
23385
|
+
// Reading '' as unset is what this replaced, and it failed in the one place
|
|
23386
|
+
// it mattered: the no-repo/no-file bucket is often the largest in a real
|
|
23387
|
+
// store, and its panel dropped both predicates and returned the WHOLE scope
|
|
23388
|
+
// — a row reading 3 findings beside a panel listing every finding there is.
|
|
23129
23389
|
case "repo":
|
|
23130
|
-
return opts.repo === void 0 ||
|
|
23390
|
+
return opts.repo === void 0 || row.repo === opts.repo;
|
|
23131
23391
|
case "file":
|
|
23132
|
-
return opts.file === void 0 ||
|
|
23392
|
+
return opts.file === void 0 || row.file === opts.file;
|
|
23133
23393
|
case "q":
|
|
23134
23394
|
return !opts.q || rowHaystack(row).includes(opts.q.toLowerCase());
|
|
23135
23395
|
}
|
|
@@ -23140,6 +23400,7 @@ var DIMENSIONS = [
|
|
|
23140
23400
|
"providers",
|
|
23141
23401
|
"actions",
|
|
23142
23402
|
"statuses",
|
|
23403
|
+
"deliveries",
|
|
23143
23404
|
"tools",
|
|
23144
23405
|
"repo",
|
|
23145
23406
|
"file",
|
|
@@ -23153,10 +23414,19 @@ function matchesInstanceFilters(row, opts, except) {
|
|
|
23153
23414
|
return true;
|
|
23154
23415
|
}
|
|
23155
23416
|
function toItems(counts) {
|
|
23156
|
-
return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
|
|
23417
|
+
return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
|
|
23418
|
+
(a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
|
|
23419
|
+
// NFD spelling of the same text) as equal, so a count tie between
|
|
23420
|
+
// them would otherwise be ordered by whichever the Map iteration
|
|
23421
|
+
// produced. compareCodePoints breaks that tie deterministically, which
|
|
23422
|
+
// makes this a TOTAL order — not one that agrees with SQL collation,
|
|
23423
|
+
// which it need not: foldFacetTuples runs this same sort over grouped
|
|
23424
|
+
// tuples, so both paths order facets identically by construction.
|
|
23425
|
+
compareCodePoints(a.value, b.value)
|
|
23426
|
+
);
|
|
23157
23427
|
}
|
|
23158
|
-
function bump(counts, value) {
|
|
23159
|
-
counts.set(value, (counts.get(value) ?? 0) +
|
|
23428
|
+
function bump(counts, value, by = 1) {
|
|
23429
|
+
counts.set(value, (counts.get(value) ?? 0) + by);
|
|
23160
23430
|
}
|
|
23161
23431
|
function createInstanceFacetAccumulator(opts) {
|
|
23162
23432
|
const severity = /* @__PURE__ */ new Map();
|
|
@@ -23165,6 +23435,7 @@ function createInstanceFacetAccumulator(opts) {
|
|
|
23165
23435
|
const action = /* @__PURE__ */ new Map();
|
|
23166
23436
|
const status = /* @__PURE__ */ new Map();
|
|
23167
23437
|
const tool = /* @__PURE__ */ new Map();
|
|
23438
|
+
const deployment = /* @__PURE__ */ new Map();
|
|
23168
23439
|
return {
|
|
23169
23440
|
add(row) {
|
|
23170
23441
|
if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
|
|
@@ -23179,6 +23450,9 @@ function createInstanceFacetAccumulator(opts) {
|
|
|
23179
23450
|
if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
|
|
23180
23451
|
bump(tool, row.toolName);
|
|
23181
23452
|
}
|
|
23453
|
+
if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
|
|
23454
|
+
bump(deployment, row.delivery.state);
|
|
23455
|
+
}
|
|
23182
23456
|
},
|
|
23183
23457
|
facets: () => ({
|
|
23184
23458
|
severity: toItems(severity),
|
|
@@ -23186,7 +23460,8 @@ function createInstanceFacetAccumulator(opts) {
|
|
|
23186
23460
|
provider: toItems(provider),
|
|
23187
23461
|
action: toItems(action),
|
|
23188
23462
|
status: toItems(status),
|
|
23189
|
-
tool: toItems(tool)
|
|
23463
|
+
tool: toItems(tool),
|
|
23464
|
+
deployment: toItems(deployment)
|
|
23190
23465
|
})
|
|
23191
23466
|
};
|
|
23192
23467
|
}
|
|
@@ -23200,6 +23475,7 @@ function toInstanceDetail(row) {
|
|
|
23200
23475
|
...row.toolName === void 0 ? {} : { toolName: row.toolName },
|
|
23201
23476
|
eventId: row.eventId,
|
|
23202
23477
|
...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
|
|
23478
|
+
...row.delivery === void 0 ? {} : { delivery: row.delivery },
|
|
23203
23479
|
...row.user === void 0 ? {} : { user: row.user },
|
|
23204
23480
|
action: toApiAction(row.actionTaken),
|
|
23205
23481
|
detectedAt: row.occurredAt,
|
|
@@ -23214,12 +23490,6 @@ function toInstanceDetail(row) {
|
|
|
23214
23490
|
policy: { id: `category:${category}`, name: category }
|
|
23215
23491
|
};
|
|
23216
23492
|
}
|
|
23217
|
-
var SEVERITY_ORDER2 = {
|
|
23218
|
-
critical: 0,
|
|
23219
|
-
high: 1,
|
|
23220
|
-
medium: 2,
|
|
23221
|
-
low: 3
|
|
23222
|
-
};
|
|
23223
23493
|
function newLocationAccumulator() {
|
|
23224
23494
|
return {
|
|
23225
23495
|
instanceCount: 0,
|
|
@@ -23234,7 +23504,7 @@ function newLocationAccumulator() {
|
|
|
23234
23504
|
}
|
|
23235
23505
|
function addToLocation(acc, row) {
|
|
23236
23506
|
acc.instanceCount += 1;
|
|
23237
|
-
const rank =
|
|
23507
|
+
const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
|
|
23238
23508
|
if (rank < acc.maxSeverityRank) {
|
|
23239
23509
|
acc.maxSeverityRank = rank;
|
|
23240
23510
|
acc.maxSeverity = row.severity;
|
|
@@ -23243,6 +23513,23 @@ function addToLocation(acc, row) {
|
|
|
23243
23513
|
acc.statuses.push(row.status);
|
|
23244
23514
|
acc.ruleIds.add(row.ruleId);
|
|
23245
23515
|
}
|
|
23516
|
+
function compareLocationOrder(a, b) {
|
|
23517
|
+
const rankA = severityRank(a.maxSeverity) ?? -1;
|
|
23518
|
+
const rankB = severityRank(b.maxSeverity) ?? -1;
|
|
23519
|
+
if (rankA !== rankB) return rankA - rankB;
|
|
23520
|
+
if (a.latestDetectedAt !== b.latestDetectedAt) {
|
|
23521
|
+
return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
|
|
23522
|
+
}
|
|
23523
|
+
const repoDiff = compareCodePoints(a.repo, b.repo);
|
|
23524
|
+
if (repoDiff !== 0) return repoDiff;
|
|
23525
|
+
return compareCodePoints(a.file, b.file);
|
|
23526
|
+
}
|
|
23527
|
+
function encodeLocationId(repo, file2) {
|
|
23528
|
+
return `${encodePart(repo)}/${encodePart(file2)}`;
|
|
23529
|
+
}
|
|
23530
|
+
function encodePart(value) {
|
|
23531
|
+
return encodeURIComponent(value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD"));
|
|
23532
|
+
}
|
|
23246
23533
|
|
|
23247
23534
|
// ../../packages/schema/src/zod/installed-pack.ts
|
|
23248
23535
|
var InstalledPack = external_exports.object({
|
|
@@ -23310,6 +23597,11 @@ var Policy = external_exports.object({
|
|
|
23310
23597
|
// test `prohibitedModels` passes and `reversibleRuleIds` fails.
|
|
23311
23598
|
provenance: PolicyProvenance.optional()
|
|
23312
23599
|
}).meta({ id: "Policy" });
|
|
23600
|
+
var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
|
|
23601
|
+
var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
|
|
23602
|
+
var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
|
|
23603
|
+
id: "RedactFallback"
|
|
23604
|
+
});
|
|
23313
23605
|
var PolicyBundle = external_exports.object({
|
|
23314
23606
|
version: external_exports.string(),
|
|
23315
23607
|
policies: external_exports.array(Policy),
|
|
@@ -23357,6 +23649,16 @@ var PolicyBundle = external_exports.object({
|
|
|
23357
23649
|
// control plane), so no name resolution stands between the decision and the
|
|
23358
23650
|
// comparison.
|
|
23359
23651
|
prohibitedModels: external_exports.array(external_exports.string()).optional(),
|
|
23652
|
+
// What a resolved `redact` becomes on a field the host cannot rewrite, as
|
|
23653
|
+
// the ORGANIZATION would have it. Merged raise-only against the device's own
|
|
23654
|
+
// `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
|
|
23655
|
+
// a control plane can tighten a machine and never loosen one — the same
|
|
23656
|
+
// direction `mergeRaiseOnly` enforces for policies.
|
|
23657
|
+
//
|
|
23658
|
+
// Optional so an older backend, and an older on-disk cache, still parses;
|
|
23659
|
+
// absent leaves the device's own setting in force, which is the behaviour
|
|
23660
|
+
// that predates the field and the safe direction to default.
|
|
23661
|
+
redactFallback: RedactFallback.optional(),
|
|
23360
23662
|
customKeywords: external_exports.array(external_exports.string()),
|
|
23361
23663
|
fetchedAt: external_exports.iso.datetime()
|
|
23362
23664
|
}).meta({ id: "PolicyBundle" });
|
|
@@ -23386,11 +23688,6 @@ function severityFloorPolicy(category) {
|
|
|
23386
23688
|
const peak = CATEGORY_PEAK_SEVERITY[category];
|
|
23387
23689
|
return peak === "critical" || peak === "high" ? "warn" : "monitor";
|
|
23388
23690
|
}
|
|
23389
|
-
var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
|
|
23390
|
-
var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
|
|
23391
|
-
var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
|
|
23392
|
-
id: "RedactFallback"
|
|
23393
|
-
});
|
|
23394
23691
|
var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
|
|
23395
23692
|
var BUILTIN_POLICY_SPECS = {
|
|
23396
23693
|
monitor: {
|
|
@@ -23688,7 +23985,7 @@ var VaultConsent = external_exports.object({
|
|
|
23688
23985
|
});
|
|
23689
23986
|
|
|
23690
23987
|
// ../../packages/schema/src/zod/local.ts
|
|
23691
|
-
var WORKSPACE_SETTINGS_SPEC_VERSION =
|
|
23988
|
+
var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
|
|
23692
23989
|
var MODEL_JUDGE_PAYLOAD_VERSION = 1;
|
|
23693
23990
|
var RunMode = external_exports.enum(["standalone", "attached"]);
|
|
23694
23991
|
var ControlPlaneConnection = external_exports.object({
|
|
@@ -23708,6 +24005,15 @@ var HistorySyncConsent = external_exports.object({
|
|
|
23708
24005
|
payloadVersion: external_exports.number().int().positive(),
|
|
23709
24006
|
endpoint: external_exports.string()
|
|
23710
24007
|
});
|
|
24008
|
+
var BODY_RETENTION_DEFAULT_DAYS = 30;
|
|
24009
|
+
var BodyRetention = external_exports.object({
|
|
24010
|
+
enabled: external_exports.boolean().default(false),
|
|
24011
|
+
// Never 0, and the ceiling is a fat-finger guard rather than a policy
|
|
24012
|
+
// limit — `enabled` is the real gate. A low value cannot reach a row the
|
|
24013
|
+
// sync ledger still owes: the sweep's age filter only ever NARROWS a
|
|
24014
|
+
// candidate set that is already bounded by "delivered, or never owed".
|
|
24015
|
+
retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
|
|
24016
|
+
}).meta({ id: "BodyRetention" });
|
|
23711
24017
|
var WorkspaceSettings = external_exports.object({
|
|
23712
24018
|
specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
|
|
23713
24019
|
runMode: RunMode.default("standalone"),
|
|
@@ -23751,12 +24057,18 @@ var WorkspaceSettings = external_exports.object({
|
|
|
23751
24057
|
// covers the current payload and must be re-granted.
|
|
23752
24058
|
modelJudgeConsent: ModelJudgeConsent.optional(),
|
|
23753
24059
|
// Records that the user consented to the DEFERRED send — the outbox — along
|
|
23754
|
-
// with the payload shape and the endpoint they agreed to. Since payload
|
|
23755
|
-
// that covers
|
|
23756
|
-
// carry prompt/reply text in `content
|
|
23757
|
-
// Absent until granted, and a grant for a different endpoint
|
|
23758
|
-
// payload no longer counts.
|
|
23759
|
-
historySyncConsent: HistorySyncConsent.optional()
|
|
24060
|
+
// with the payload shape and the endpoint they agreed to. Since payload v3
|
|
24061
|
+
// that covers the pre-attach backlog AND undelivered captures alike, and both
|
|
24062
|
+
// carry prompt/reply/tool-output text in `content`; the key name predates
|
|
24063
|
+
// both widenings. Absent until granted, and a grant for a different endpoint
|
|
24064
|
+
// or an older payload no longer counts.
|
|
24065
|
+
historySyncConsent: HistorySyncConsent.optional(),
|
|
24066
|
+
// Local body expiry (see BodyRetention). Off until switched on; expiring a
|
|
24067
|
+
// body never removes the row or its findings.
|
|
24068
|
+
bodyRetention: BodyRetention.default({
|
|
24069
|
+
enabled: false,
|
|
24070
|
+
retainDays: BODY_RETENTION_DEFAULT_DAYS
|
|
24071
|
+
})
|
|
23760
24072
|
});
|
|
23761
24073
|
function defaultWorkspaceSettings() {
|
|
23762
24074
|
return WorkspaceSettings.parse({});
|
|
@@ -23851,12 +24163,15 @@ function toCaptureAttributes(event) {
|
|
|
23851
24163
|
...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
|
|
23852
24164
|
...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
|
|
23853
24165
|
...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
|
|
24166
|
+
...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
|
|
23854
24167
|
// `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
|
|
23855
24168
|
// has ever populated either), but every legacy metadata key still rides
|
|
23856
24169
|
// the bag rather than being silently dropped — CaptureAttributes'
|
|
23857
24170
|
// `.catchall(z.unknown())` carries the long tail.
|
|
23858
24171
|
...metadata?.model !== void 0 ? { model: metadata.model } : {},
|
|
23859
|
-
...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
|
|
24172
|
+
...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
|
|
24173
|
+
...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
|
|
24174
|
+
...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
|
|
23860
24175
|
};
|
|
23861
24176
|
}
|
|
23862
24177
|
function captureDefinitionVersion(finding) {
|
|
@@ -23884,10 +24199,22 @@ var ManagedSettingKey = external_exports.enum([
|
|
|
23884
24199
|
"vaultInlineReveal",
|
|
23885
24200
|
"modelJudgeConsent",
|
|
23886
24201
|
"dataSharesInPlace",
|
|
23887
|
-
"redactFallback"
|
|
24202
|
+
"redactFallback",
|
|
24203
|
+
// Pins the toggle and the day count together — see BodyRetention on why the
|
|
24204
|
+
// two are one unit. An administrator mandating a window wants the count
|
|
24205
|
+
// enforced with it, not one a user can widen while the toggle stays on.
|
|
24206
|
+
"bodyRetention"
|
|
23888
24207
|
]).meta({ id: "ManagedSettingKey" });
|
|
24208
|
+
function isManagedSettingKey(value) {
|
|
24209
|
+
return ManagedSettingKey.safeParse(value).success;
|
|
24210
|
+
}
|
|
23889
24211
|
var ManagedSettingsValues = external_exports.object({
|
|
23890
24212
|
runMode: external_exports.enum(["standalone", "attached"]).optional(),
|
|
24213
|
+
// `controlPlane` and `bodyRetention` are the two nested values, and both are
|
|
24214
|
+
// plain, non-strict objects: a key under either that this build does not know
|
|
24215
|
+
// is stripped and nothing reports it. The unknown-value split in
|
|
24216
|
+
// ManagedSettings below classifies top-level names only, so it stops at
|
|
24217
|
+
// these boundaries.
|
|
23891
24218
|
controlPlane: external_exports.object({
|
|
23892
24219
|
endpoint: external_exports.string().min(1),
|
|
23893
24220
|
label: external_exports.string().min(1).optional()
|
|
@@ -23898,7 +24225,8 @@ var ManagedSettingsValues = external_exports.object({
|
|
|
23898
24225
|
vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
|
|
23899
24226
|
modelJudgeConsent: external_exports.boolean().optional(),
|
|
23900
24227
|
dataSharesInPlace: external_exports.boolean().optional(),
|
|
23901
|
-
redactFallback: RedactFallback.optional()
|
|
24228
|
+
redactFallback: RedactFallback.optional(),
|
|
24229
|
+
bodyRetention: BodyRetention.optional()
|
|
23902
24230
|
}).meta({ id: "ManagedSettingsValues" });
|
|
23903
24231
|
var ManagedSettings = external_exports.object({
|
|
23904
24232
|
specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
|
|
@@ -23906,11 +24234,59 @@ var ManagedSettings = external_exports.object({
|
|
|
23906
24234
|
// decision from a bug. Absent renders as a generic "your organization".
|
|
23907
24235
|
organization: external_exports.string().min(1).optional(),
|
|
23908
24236
|
// What the administrator pinned.
|
|
23909
|
-
|
|
24237
|
+
//
|
|
24238
|
+
// Parsed as a RECORD rather than as the nested schema, and split below for
|
|
24239
|
+
// the same reason `lockedFields` is parsed as names: a plain `z.object`
|
|
24240
|
+
// drops an unrecognised key and succeeds, so a pin this build does not know
|
|
24241
|
+
// vanished and nothing anywhere said so. A pin with no lock is a supported
|
|
24242
|
+
// shape — it is a DEFAULT the user may still change — so that silence hit
|
|
24243
|
+
// exactly the file an administrator is most likely to write while a fleet
|
|
24244
|
+
// is mid-upgrade.
|
|
24245
|
+
//
|
|
24246
|
+
// Splitting here rather than calling `.strict()`: strict would REFUSE the
|
|
24247
|
+
// file, which is the outcome the lock half already rejected — an older
|
|
24248
|
+
// build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
|
|
24249
|
+
// value still fails, because the nested schema is re-run over the known
|
|
24250
|
+
// subset and its issues are re-raised on this parse.
|
|
24251
|
+
values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
|
|
23910
24252
|
// Which of those the user may not change. A key here with no matching value
|
|
23911
24253
|
// freezes whatever the user last chose; a value with no lock is a DEFAULT
|
|
23912
24254
|
// the user may still override. The two are separable on purpose.
|
|
23913
|
-
|
|
24255
|
+
//
|
|
24256
|
+
// Parsed as NAMES rather than as the enum, and split below: a name this
|
|
24257
|
+
// build does not know is dropped from the locked set and reported, never a
|
|
24258
|
+
// reason to refuse the file. The same shape reaches an older build whenever
|
|
24259
|
+
// an administrator locks a key a newer build added, and refusing it there
|
|
24260
|
+
// ran that build entirely unmanaged — every pin and lock gone — on exactly
|
|
24261
|
+
// the fleets most likely to carry a version skew. A name outside the enum
|
|
24262
|
+
// is still never HONOURED: the lockable set stays explicit above.
|
|
24263
|
+
lockedFields: external_exports.array(external_exports.string()).default([])
|
|
24264
|
+
}).transform(({ lockedFields, values, ...rest }, ctx) => {
|
|
24265
|
+
const known = [];
|
|
24266
|
+
const unknown2 = [];
|
|
24267
|
+
for (const name of lockedFields) {
|
|
24268
|
+
if (isManagedSettingKey(name)) known.push(name);
|
|
24269
|
+
else unknown2.push(name);
|
|
24270
|
+
}
|
|
24271
|
+
const knownValues = /* @__PURE__ */ Object.create(null);
|
|
24272
|
+
const unknownValues = [];
|
|
24273
|
+
for (const [name, value] of Object.entries(values)) {
|
|
24274
|
+
if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
|
|
24275
|
+
else unknownValues.push(name);
|
|
24276
|
+
}
|
|
24277
|
+
const pinned = ManagedSettingsValues.safeParse(knownValues);
|
|
24278
|
+
if (!pinned.success) {
|
|
24279
|
+
for (const issue2 of pinned.error.issues)
|
|
24280
|
+
ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
|
|
24281
|
+
return external_exports.NEVER;
|
|
24282
|
+
}
|
|
24283
|
+
return {
|
|
24284
|
+
...rest,
|
|
24285
|
+
values: pinned.data,
|
|
24286
|
+
lockedFields: known,
|
|
24287
|
+
...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
|
|
24288
|
+
...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
|
|
24289
|
+
};
|
|
23914
24290
|
}).meta({ id: "ManagedSettings" });
|
|
23915
24291
|
|
|
23916
24292
|
// ../../packages/schema/src/zod/project-files.ts
|
|
@@ -24034,7 +24410,11 @@ var FindingsTimeseriesPoint = external_exports.object({
|
|
|
24034
24410
|
timestamp: external_exports.iso.date(),
|
|
24035
24411
|
critical: external_exports.number().int().nonnegative(),
|
|
24036
24412
|
high: external_exports.number().int().nonnegative(),
|
|
24037
|
-
medium: external_exports.number().int().nonnegative()
|
|
24413
|
+
medium: external_exports.number().int().nonnegative(),
|
|
24414
|
+
// Optional and additive, so a producer written against the earlier
|
|
24415
|
+
// three-series contract keeps validating. A consumer plotting it resolves the
|
|
24416
|
+
// absent case itself — the chart point requires a number.
|
|
24417
|
+
low: external_exports.number().int().nonnegative().optional()
|
|
24038
24418
|
}).meta({ id: "FindingsTimeseriesPoint" });
|
|
24039
24419
|
var FindingsTimeseriesResponse = external_exports.object({
|
|
24040
24420
|
range: TimeRange,
|
|
@@ -24060,6 +24440,10 @@ var ResolvedFeedItem = external_exports.object({
|
|
|
24060
24440
|
findingKey: external_exports.string(),
|
|
24061
24441
|
ruleId: external_exports.string(),
|
|
24062
24442
|
severity: Severity,
|
|
24443
|
+
// Repository slug, and the file path RELATIVE to it. The pair is what
|
|
24444
|
+
// identifies the file: a bare path matches the same name in every repo.
|
|
24445
|
+
// Optional and additive; empty when the event carried no repo.
|
|
24446
|
+
repo: external_exports.string().optional(),
|
|
24063
24447
|
path: external_exports.string(),
|
|
24064
24448
|
// ISO-8601 datetime (matches FindingInstance.detectedAt / the rest of the
|
|
24065
24449
|
// findings domain). The reader `.toISOString()`s the DB epoch-ms values.
|
|
@@ -24165,7 +24549,23 @@ var SaveSettingsInput = external_exports.object({
|
|
|
24165
24549
|
modelJudgeConsent: ModelJudgeConsentChoice,
|
|
24166
24550
|
historySyncConsent: HistorySyncConsentChoice,
|
|
24167
24551
|
vaultConsent: external_exports.string(),
|
|
24168
|
-
vaultInlineReveal: external_exports.string()
|
|
24552
|
+
vaultInlineReveal: external_exports.string(),
|
|
24553
|
+
// Widened to `string` like its neighbours rather than typed as
|
|
24554
|
+
// `RedactFallback`, on this module's own layering rule: shape here, VALUE at
|
|
24555
|
+
// the call site, so the domain check receives the type it was written for.
|
|
24556
|
+
//
|
|
24557
|
+
// NOT because a narrower schema would reject differently. `parseActionInput`
|
|
24558
|
+
// is a `safeParse` wrapper and throws for no field schema, so either spelling
|
|
24559
|
+
// reaches a recoverable `{ ok: false }` and there is no rejected promise to
|
|
24560
|
+
// trade against. The real cost runs the other way and is the part worth
|
|
24561
|
+
// knowing: a value this schema admits and the domain enum then rejects lands
|
|
24562
|
+
// on the action's shared refusal, which names NO field, where a shape
|
|
24563
|
+
// rejection reaches `malformedInput` and names the schema key.
|
|
24564
|
+
redactFallback: external_exports.string(),
|
|
24565
|
+
// Shape only, the way the enum fields above are strings only: the RANGE is
|
|
24566
|
+
// `BodyRetention`'s and the action checks it there, so there is one place
|
|
24567
|
+
// that decides what a legal horizon is rather than two that can drift.
|
|
24568
|
+
bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
|
|
24169
24569
|
});
|
|
24170
24570
|
var AttachInput = external_exports.object({
|
|
24171
24571
|
endpoint: external_exports.string(),
|
|
@@ -24337,6 +24737,52 @@ function reviewSeverityRank(reasons) {
|
|
|
24337
24737
|
return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
|
|
24338
24738
|
}
|
|
24339
24739
|
|
|
24740
|
+
// ../../packages/schema/src/zod/web-capture.ts
|
|
24741
|
+
var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
|
|
24742
|
+
var WebUsage = external_exports.object({
|
|
24743
|
+
inputTokens: external_exports.number().int().nonnegative().optional(),
|
|
24744
|
+
outputTokens: external_exports.number().int().nonnegative().optional(),
|
|
24745
|
+
cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
|
|
24746
|
+
cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
|
|
24747
|
+
});
|
|
24748
|
+
var WebToolCall = external_exports.object({
|
|
24749
|
+
toolUseId: external_exports.string().min(1),
|
|
24750
|
+
toolName: external_exports.string().min(1),
|
|
24751
|
+
target: external_exports.string().optional(),
|
|
24752
|
+
isError: external_exports.boolean().optional(),
|
|
24753
|
+
inputSize: external_exports.number().int().nonnegative().optional(),
|
|
24754
|
+
outputSize: external_exports.number().int().nonnegative().optional()
|
|
24755
|
+
});
|
|
24756
|
+
var WebExchange = external_exports.object({
|
|
24757
|
+
messageId: external_exports.string().min(1),
|
|
24758
|
+
startedAt: external_exports.iso.datetime(),
|
|
24759
|
+
model: external_exports.string().optional(),
|
|
24760
|
+
usage: WebUsage.optional(),
|
|
24761
|
+
usageSource: WebUsageSource,
|
|
24762
|
+
stopReason: external_exports.string().optional(),
|
|
24763
|
+
conversationId: external_exports.string().optional(),
|
|
24764
|
+
turnIndex: external_exports.number().int().nonnegative().optional(),
|
|
24765
|
+
toolCalls: external_exports.array(WebToolCall).default([]),
|
|
24766
|
+
// Absent when the adapter recovered no text. Capped by the caller at
|
|
24767
|
+
// RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
|
|
24768
|
+
// short capture is never mistaken for a short reply.
|
|
24769
|
+
responseText: external_exports.string().optional(),
|
|
24770
|
+
truncated: external_exports.boolean().default(false)
|
|
24771
|
+
});
|
|
24772
|
+
var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
|
|
24773
|
+
var WebCaptureStatus = external_exports.object({
|
|
24774
|
+
patched: external_exports.boolean(),
|
|
24775
|
+
live: external_exports.boolean(),
|
|
24776
|
+
blind: external_exports.boolean(),
|
|
24777
|
+
sendsSeenDom: external_exports.number().int().nonnegative(),
|
|
24778
|
+
exchangesSeenNet: external_exports.number().int().nonnegative(),
|
|
24779
|
+
parseFailures: external_exports.number().int().nonnegative(),
|
|
24780
|
+
unparsedBodies: external_exports.number().int().nonnegative(),
|
|
24781
|
+
// The adapter-declared JSON key paths that were absent from a real payload —
|
|
24782
|
+
// the earliest signal that a site's contract moved.
|
|
24783
|
+
shapeMisses: external_exports.array(external_exports.string()).default([])
|
|
24784
|
+
});
|
|
24785
|
+
|
|
24340
24786
|
// ../../packages/persistence/src/paths.ts
|
|
24341
24787
|
import {
|
|
24342
24788
|
chmodSync,
|
|
@@ -24667,6 +25113,22 @@ function discardStore(file2, backup) {
|
|
|
24667
25113
|
}
|
|
24668
25114
|
}
|
|
24669
25115
|
|
|
25116
|
+
// ../../packages/persistence/src/internal/sql-functions.ts
|
|
25117
|
+
var utf8 = new TextDecoder();
|
|
25118
|
+
function akaLower(value) {
|
|
25119
|
+
if (value === null) return null;
|
|
25120
|
+
if (typeof value === "string") return value.toLowerCase();
|
|
25121
|
+
if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
|
|
25122
|
+
return utf8.decode(value).toLowerCase();
|
|
25123
|
+
}
|
|
25124
|
+
function registerSqlFunctions(db) {
|
|
25125
|
+
db.function(
|
|
25126
|
+
"aka_lower",
|
|
25127
|
+
{ deterministic: true, directOnly: true, useBigIntArguments: true },
|
|
25128
|
+
akaLower
|
|
25129
|
+
);
|
|
25130
|
+
}
|
|
25131
|
+
|
|
24670
25132
|
// ../../packages/persistence/src/internal/sql-text.ts
|
|
24671
25133
|
function escapeLikePattern(s) {
|
|
24672
25134
|
return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
|
|
@@ -24751,6 +25213,11 @@ function schemaObjectExists(db, kind, name) {
|
|
|
24751
25213
|
function indexExists(db, name) {
|
|
24752
25214
|
return schemaObjectExists(db, "index", name);
|
|
24753
25215
|
}
|
|
25216
|
+
function indexColumns(db, name) {
|
|
25217
|
+
if (!indexExists(db, name)) return [];
|
|
25218
|
+
const columns = db.prepare(`PRAGMA index_info(${name})`).all();
|
|
25219
|
+
return columns.map((c) => c.name).filter((c) => c !== null);
|
|
25220
|
+
}
|
|
24754
25221
|
function columnNames(db, table2, opts) {
|
|
24755
25222
|
const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
|
|
24756
25223
|
const columns = db.prepare(`PRAGMA ${pragma}(${table2})`).all();
|
|
@@ -24812,6 +25279,647 @@ function mapRowsTolerant(rows, map2) {
|
|
|
24812
25279
|
return out;
|
|
24813
25280
|
}
|
|
24814
25281
|
|
|
25282
|
+
// ../../packages/persistence/src/internal/outbox-lane.ts
|
|
25283
|
+
var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
|
|
25284
|
+
var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
25285
|
+
|
|
25286
|
+
// ../../packages/persistence/src/sync-failure.ts
|
|
25287
|
+
var SYNC_FAILURE_REASONS = SyncFailureReason.options;
|
|
25288
|
+
function syncFailureRejectCondition(column = "sync_failure") {
|
|
25289
|
+
const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
|
|
25290
|
+
return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
|
|
25291
|
+
}
|
|
25292
|
+
|
|
25293
|
+
// ../../packages/persistence/src/repositories/history-sync.ts
|
|
25294
|
+
var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
|
|
25295
|
+
var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
25296
|
+
var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
|
|
25297
|
+
var COUNTED_EVENT_TYPES = [
|
|
25298
|
+
...STRUCTURAL_EVENT_TYPES,
|
|
25299
|
+
...OUTBOX_CAPTURE_EVENT_TYPES
|
|
25300
|
+
];
|
|
25301
|
+
var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
25302
|
+
var PARTITION_BUCKETS = `
|
|
25303
|
+
SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
|
|
25304
|
+
SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
|
|
25305
|
+
SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
|
|
25306
|
+
SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
|
|
25307
|
+
AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
|
|
25308
|
+
SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
|
|
25309
|
+
AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
|
|
25310
|
+
-- Spelled as what it INCLUDES rather than what it excludes, so a reason
|
|
25311
|
+
-- added later lands in no bucket and fails the sum assertion, instead
|
|
25312
|
+
-- of silently joining this one.
|
|
25313
|
+
SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
|
|
25314
|
+
AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
|
|
25315
|
+
THEN 1 ELSE 0 END) AS failed,
|
|
25316
|
+
COUNT(*) AS total`;
|
|
25317
|
+
var COUNTED_SCOPE = `
|
|
25318
|
+
WHERE event_type IN (${COUNTED_TYPE_LIST})
|
|
25319
|
+
AND (
|
|
25320
|
+
event_type IN (${TYPE_LIST})
|
|
25321
|
+
OR synced_at IS NOT NULL
|
|
25322
|
+
OR outbox_owed = 1
|
|
25323
|
+
)`;
|
|
25324
|
+
var SKIPPED = -1;
|
|
25325
|
+
var ROW_COLUMNS = `id,
|
|
25326
|
+
parent_id AS parentId,
|
|
25327
|
+
root_session_id AS rootSessionId,
|
|
25328
|
+
event_type AS eventType,
|
|
25329
|
+
host_id AS hostId,
|
|
25330
|
+
harness_id AS harnessId,
|
|
25331
|
+
source_project_id AS sourceProjectId,
|
|
25332
|
+
started_at AS startedAt,
|
|
25333
|
+
ended_at AS endedAt,
|
|
25334
|
+
severity,
|
|
25335
|
+
priority,
|
|
25336
|
+
content,
|
|
25337
|
+
content_hash AS contentHash,
|
|
25338
|
+
attributes`;
|
|
25339
|
+
var SqliteHistorySyncRepository = class {
|
|
25340
|
+
constructor(db) {
|
|
25341
|
+
this.db = db;
|
|
25342
|
+
this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
|
|
25343
|
+
this.sessionsStmt = db.prepare(
|
|
25344
|
+
`SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
|
|
25345
|
+
FROM audit_events
|
|
25346
|
+
WHERE synced_at IS NULL
|
|
25347
|
+
AND event_type IN (${TYPE_LIST})
|
|
25348
|
+
AND started_at < :before
|
|
25349
|
+
GROUP BY sessionId
|
|
25350
|
+
ORDER BY earliest
|
|
25351
|
+
LIMIT :limit`
|
|
25352
|
+
);
|
|
25353
|
+
this.rowsStmt = db.prepare(
|
|
25354
|
+
`SELECT ${ROW_COLUMNS}
|
|
25355
|
+
FROM audit_events
|
|
25356
|
+
WHERE synced_at IS NULL
|
|
25357
|
+
AND event_type IN (${TYPE_LIST})
|
|
25358
|
+
AND started_at < :before
|
|
25359
|
+
AND COALESCE(root_session_id, id) = :sessionId
|
|
25360
|
+
ORDER BY (event_type = 'session') DESC, started_at
|
|
25361
|
+
LIMIT :limit`
|
|
25362
|
+
);
|
|
25363
|
+
this.captureRowsStmt = db.prepare(
|
|
25364
|
+
`SELECT ${ROW_COLUMNS}
|
|
25365
|
+
FROM audit_events
|
|
25366
|
+
WHERE synced_at IS NULL
|
|
25367
|
+
AND sync_claimed_at IS NULL
|
|
25368
|
+
AND outbox_owed = 1
|
|
25369
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})
|
|
25370
|
+
AND started_at < :before
|
|
25371
|
+
ORDER BY started_at
|
|
25372
|
+
LIMIT :limit`
|
|
25373
|
+
);
|
|
25374
|
+
this.markOwedStmt = db.prepare(
|
|
25375
|
+
`UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
|
|
25376
|
+
);
|
|
25377
|
+
this.markCaptureBacklogOwedStmt = db.prepare(
|
|
25378
|
+
`UPDATE audit_events SET outbox_owed = 1
|
|
25379
|
+
WHERE synced_at IS NULL
|
|
25380
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})
|
|
25381
|
+
AND started_at < :before`
|
|
25382
|
+
);
|
|
25383
|
+
this.stampStmt = db.prepare(
|
|
25384
|
+
`UPDATE audit_events
|
|
25385
|
+
SET synced_at = :at,
|
|
25386
|
+
sync_claimed_at = NULL,
|
|
25387
|
+
sync_failed_at = :failedAt,
|
|
25388
|
+
sync_failure = :failure
|
|
25389
|
+
WHERE id = :id`
|
|
25390
|
+
);
|
|
25391
|
+
this.claimRowStmt = db.prepare(
|
|
25392
|
+
`UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
|
|
25393
|
+
);
|
|
25394
|
+
this.releaseRowStmt = db.prepare(
|
|
25395
|
+
`UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
|
|
25396
|
+
);
|
|
25397
|
+
this.releaseStaleClaimsStmt = db.prepare(
|
|
25398
|
+
`UPDATE audit_events SET sync_claimed_at = NULL
|
|
25399
|
+
WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
|
|
25400
|
+
);
|
|
25401
|
+
this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
|
|
25402
|
+
FROM audit_events${COUNTED_SCOPE}`);
|
|
25403
|
+
this.partitionByKindStmt = db.prepare(
|
|
25404
|
+
`SELECT event_type AS kind,${PARTITION_BUCKETS}
|
|
25405
|
+
FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
|
|
25406
|
+
GROUP BY event_type`
|
|
25407
|
+
);
|
|
25408
|
+
this.countsStmt = db.prepare(
|
|
25409
|
+
`SELECT
|
|
25410
|
+
SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
|
|
25411
|
+
SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
|
|
25412
|
+
SUM(CASE WHEN synced_at = ${String(SKIPPED)}
|
|
25413
|
+
AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
|
|
25414
|
+
THEN 1 ELSE 0 END) AS skipped,
|
|
25415
|
+
SUM(CASE WHEN synced_at = ${String(SKIPPED)}
|
|
25416
|
+
AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
|
|
25417
|
+
SUM(CASE WHEN synced_at = ${String(SKIPPED)}
|
|
25418
|
+
AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
|
|
25419
|
+
FROM audit_events
|
|
25420
|
+
WHERE event_type IN (${TYPE_LIST})`
|
|
25421
|
+
);
|
|
25422
|
+
this.captureSkipCountStmt = db.prepare(
|
|
25423
|
+
// EVERY sentinel capture, whatever the reason — deliberately NOT split the
|
|
25424
|
+
// way the structural totals are. The split exists because a refusal is
|
|
25425
|
+
// terminal only against the deployment that gave it, and the structural
|
|
25426
|
+
// re-arm frees it on a change of deployment. The capture lane has no such
|
|
25427
|
+
// escape: re-arming a capture would offer one deployment's undelivered
|
|
25428
|
+
// prompts, with their text, to a deployment that never saw them, which is
|
|
25429
|
+
// exactly what disownCapturesStmt exists to prevent. So on this lane both
|
|
25430
|
+
// reasons mean the same thing — this row will not be sent — and splitting
|
|
25431
|
+
// them would put refused captures in a bucket nothing reads and nothing
|
|
25432
|
+
// frees.
|
|
25433
|
+
`SELECT COUNT(*) AS skipped
|
|
25434
|
+
FROM audit_events
|
|
25435
|
+
WHERE synced_at = ${String(SKIPPED)}
|
|
25436
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})`
|
|
25437
|
+
);
|
|
25438
|
+
this.fingerprintStmt = db.prepare(
|
|
25439
|
+
`SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
|
|
25440
|
+
FROM history_sync WHERE id = 1`
|
|
25441
|
+
);
|
|
25442
|
+
this.setFingerprintStmt = db.prepare(
|
|
25443
|
+
`UPDATE history_sync
|
|
25444
|
+
SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
|
|
25445
|
+
WHERE id = 1`
|
|
25446
|
+
);
|
|
25447
|
+
this.disownCapturesStmt = db.prepare(
|
|
25448
|
+
`UPDATE audit_events SET outbox_owed = NULL
|
|
25449
|
+
WHERE outbox_owed IS NOT NULL
|
|
25450
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})
|
|
25451
|
+
AND started_at < :attachedAt`
|
|
25452
|
+
);
|
|
25453
|
+
this.rearmStmt = db.prepare(
|
|
25454
|
+
`UPDATE audit_events
|
|
25455
|
+
SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
|
|
25456
|
+
WHERE (synced_at > 0
|
|
25457
|
+
OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
|
|
25458
|
+
AND event_type IN (${TYPE_LIST})`
|
|
25459
|
+
);
|
|
25460
|
+
this.claimStmt = db.prepare(
|
|
25461
|
+
`UPDATE history_sync
|
|
25462
|
+
SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
|
|
25463
|
+
WHERE id = 1
|
|
25464
|
+
AND (owner_pid IS NULL
|
|
25465
|
+
OR heartbeat_at IS NULL
|
|
25466
|
+
OR heartbeat_at < :staleBefore
|
|
25467
|
+
OR heartbeat_at > :now)`
|
|
25468
|
+
);
|
|
25469
|
+
this.heartbeatStmt = db.prepare(
|
|
25470
|
+
`UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
|
|
25471
|
+
);
|
|
25472
|
+
this.releaseStmt = db.prepare(
|
|
25473
|
+
`UPDATE history_sync
|
|
25474
|
+
SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
|
|
25475
|
+
WHERE id = 1 AND owner_pid = :pid`
|
|
25476
|
+
);
|
|
25477
|
+
this.closeWindowStmt = db.prepare(
|
|
25478
|
+
`UPDATE audit_events
|
|
25479
|
+
SET synced_at = ${String(SKIPPED)},
|
|
25480
|
+
sync_failed_at = :at,
|
|
25481
|
+
sync_failure = 'detached_undelivered'
|
|
25482
|
+
WHERE synced_at IS NULL
|
|
25483
|
+
AND event_type IN (${TYPE_LIST})
|
|
25484
|
+
AND started_at >= :attachedAt`
|
|
25485
|
+
);
|
|
25486
|
+
this.releaseBoundaryStmt = db.prepare(
|
|
25487
|
+
`UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
|
|
25488
|
+
);
|
|
25489
|
+
this.freezeBoundaryStmt = db.prepare(
|
|
25490
|
+
`UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
|
|
25491
|
+
);
|
|
25492
|
+
this.leaseStmt = db.prepare(
|
|
25493
|
+
`SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
|
|
25494
|
+
acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
|
|
25495
|
+
FROM history_sync WHERE id = 1`
|
|
25496
|
+
);
|
|
25497
|
+
this.inspectionsStmt = db.prepare(
|
|
25498
|
+
`SELECT d.rule_id AS ruleId,
|
|
25499
|
+
d.name AS ruleName,
|
|
25500
|
+
d.version AS ruleVersion,
|
|
25501
|
+
d.category AS category,
|
|
25502
|
+
d.severity AS severity,
|
|
25503
|
+
f.span_start AS spanStart,
|
|
25504
|
+
f.span_end AS spanEnd,
|
|
25505
|
+
f.masked_match AS maskedMatch,
|
|
25506
|
+
f.action_taken AS actionTaken,
|
|
25507
|
+
f.confidence AS confidence
|
|
25508
|
+
FROM inspection_findings f
|
|
25509
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
25510
|
+
WHERE f.audit_event_id = :auditEventId
|
|
25511
|
+
ORDER BY f.span_start, f.id`
|
|
25512
|
+
);
|
|
25513
|
+
}
|
|
25514
|
+
db;
|
|
25515
|
+
ensureRowStmt;
|
|
25516
|
+
sessionsStmt;
|
|
25517
|
+
rowsStmt;
|
|
25518
|
+
stampStmt;
|
|
25519
|
+
countsStmt;
|
|
25520
|
+
fingerprintStmt;
|
|
25521
|
+
setFingerprintStmt;
|
|
25522
|
+
rearmStmt;
|
|
25523
|
+
claimStmt;
|
|
25524
|
+
heartbeatStmt;
|
|
25525
|
+
releaseStmt;
|
|
25526
|
+
leaseStmt;
|
|
25527
|
+
inspectionsStmt;
|
|
25528
|
+
closeWindowStmt;
|
|
25529
|
+
releaseBoundaryStmt;
|
|
25530
|
+
freezeBoundaryStmt;
|
|
25531
|
+
captureRowsStmt;
|
|
25532
|
+
markOwedStmt;
|
|
25533
|
+
markCaptureBacklogOwedStmt;
|
|
25534
|
+
captureSkipCountStmt;
|
|
25535
|
+
disownCapturesStmt;
|
|
25536
|
+
partitionStmt;
|
|
25537
|
+
partitionByKindStmt;
|
|
25538
|
+
claimRowStmt;
|
|
25539
|
+
releaseRowStmt;
|
|
25540
|
+
releaseStaleClaimsStmt;
|
|
25541
|
+
/**
|
|
25542
|
+
* The masked detections recorded against one tool call.
|
|
25543
|
+
*
|
|
25544
|
+
* These travel with the event because a tool call's target is not
|
|
25545
|
+
* re-inspectable from the event alone — unlike a capture, where the text
|
|
25546
|
+
* itself is re-scannable. What crosses is the masked match and the rule that
|
|
25547
|
+
* produced it, never the value.
|
|
25548
|
+
*/
|
|
25549
|
+
inspectionsFor(auditEventId) {
|
|
25550
|
+
return allRows(this.inspectionsStmt, { auditEventId });
|
|
25551
|
+
}
|
|
25552
|
+
/**
|
|
25553
|
+
* Sessions with structural rows still to send, oldest first.
|
|
25554
|
+
*
|
|
25555
|
+
* BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
|
|
25556
|
+
* read. Anything recorded after the machine attached is the live forward
|
|
25557
|
+
* path's to deliver; this drain exists for what was recorded before it, and a
|
|
25558
|
+
* row both paths send is at best a duplicate request and at worst — for a
|
|
25559
|
+
* session root — an overwrite of the inventory ids the live path resolved.
|
|
25560
|
+
*/
|
|
25561
|
+
pendingSessions(limit, before) {
|
|
25562
|
+
return allRows(this.sessionsStmt, { limit, before }).map(
|
|
25563
|
+
(r) => r.sessionId
|
|
25564
|
+
);
|
|
25565
|
+
}
|
|
25566
|
+
/** One session's undelivered structural rows within the backlog, root first. */
|
|
25567
|
+
pendingRows(sessionId, limit, before) {
|
|
25568
|
+
return allRows(this.rowsStmt, { sessionId, limit, before });
|
|
25569
|
+
}
|
|
25570
|
+
/**
|
|
25571
|
+
* Captures this machine still owes the deployment, oldest first.
|
|
25572
|
+
*
|
|
25573
|
+
* Selected by the `outbox_owed` marker the attached forward path writes, not
|
|
25574
|
+
* by a time window — see captureRowsStmt for why a window could not express
|
|
25575
|
+
* this. `before` is the grace window that leaves a just-recorded capture to
|
|
25576
|
+
* the live path.
|
|
25577
|
+
*/
|
|
25578
|
+
pendingCaptureRows(limit, before) {
|
|
25579
|
+
return allRows(this.captureRowsStmt, { limit, before });
|
|
25580
|
+
}
|
|
25581
|
+
/**
|
|
25582
|
+
* Record that a capture is OWED to the deployment.
|
|
25583
|
+
*
|
|
25584
|
+
* Written by the attached forward path when a live send did not confirm
|
|
25585
|
+
* delivery, and read by the drain as the whole of its eligibility test. It is
|
|
25586
|
+
* a fact rather than an inference: the machine was attached, the send did not
|
|
25587
|
+
* land, so the row is owed — which no time window can state, because the same
|
|
25588
|
+
* window that holds the rows a past attachment left owed also holds every
|
|
25589
|
+
* capture recorded while the machine was DETACHED, and those were never
|
|
25590
|
+
* offered to anyone.
|
|
25591
|
+
*
|
|
25592
|
+
* Idempotent, and never un-set: `markSynced` settling the row is what takes it
|
|
25593
|
+
* out of the drain's read.
|
|
25594
|
+
*/
|
|
25595
|
+
markCaptureOwed(id) {
|
|
25596
|
+
this.markOwedStmt.run({ id });
|
|
25597
|
+
}
|
|
25598
|
+
/**
|
|
25599
|
+
* Mark every capture already on disk as owed, as of `before`.
|
|
25600
|
+
*
|
|
25601
|
+
* The consent-time backfill, called once from `aka attach` when a human
|
|
25602
|
+
* grants existing-history consent — never from an ongoing drain pass, and
|
|
25603
|
+
* never inferred from a boundary that could later move. `before` is the
|
|
25604
|
+
* caller's own "now" at the moment consent was granted, so what this marks
|
|
25605
|
+
* is exactly the backlog the consent prompt already counted, not whatever a
|
|
25606
|
+
* later re-attach or key rotation might widen it to.
|
|
25607
|
+
*
|
|
25608
|
+
* Returns how many rows matched, for the caller to log or test against. Not a
|
|
25609
|
+
* count of NEWLY marked rows — a row still unsynced from an earlier call
|
|
25610
|
+
* matches again and is counted again, the same as `UPDATE`'s own `changes`.
|
|
25611
|
+
*/
|
|
25612
|
+
markCaptureBacklogOwed(before) {
|
|
25613
|
+
return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
|
|
25614
|
+
}
|
|
25615
|
+
/**
|
|
25616
|
+
* Record delivery. Called only AFTER the far side has accepted the rows.
|
|
25617
|
+
*
|
|
25618
|
+
* CLEARS any failure reason in the same statement. A row that failed against
|
|
25619
|
+
* one deployment and then landed is delivered, and leaving the reason behind
|
|
25620
|
+
* would leave the store holding two contradictory answers about one row —
|
|
25621
|
+
* with the surface free to render either.
|
|
25622
|
+
*/
|
|
25623
|
+
markSynced(ids, atMs) {
|
|
25624
|
+
this.stampAll(ids, atMs, null);
|
|
25625
|
+
}
|
|
25626
|
+
/**
|
|
25627
|
+
* Record that THIS MACHINE cannot express the row on the wire.
|
|
25628
|
+
*
|
|
25629
|
+
* Reserved for a local defect — a row that cannot be rebuilt into a valid
|
|
25630
|
+
* payload, or a body the client itself refused to send. It fails identically
|
|
25631
|
+
* against every deployment, so it is terminal everywhere and the re-arm leaves
|
|
25632
|
+
* it alone. A row that merely failed to REACH the deployment stays NULL, so it
|
|
25633
|
+
* is retried; marking those would turn one outage into permanent data loss.
|
|
25634
|
+
*/
|
|
25635
|
+
markSkipped(ids, atMs) {
|
|
25636
|
+
this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
|
|
25637
|
+
}
|
|
25638
|
+
/**
|
|
25639
|
+
* Record that THIS DEPLOYMENT refused the row.
|
|
25640
|
+
*
|
|
25641
|
+
* The same sentinel as `markSkipped`, and deliberately so: both stop the row
|
|
25642
|
+
* being re-offered on this lane, and `synced_at` goes on answering whether a
|
|
25643
|
+
* row is outstanding rather than why. What separates them is the reason, and
|
|
25644
|
+
* what the reason buys is the re-arm — a refusal is one deployment's verdict
|
|
25645
|
+
* on one body, so it is terminal only for as long as this machine points at
|
|
25646
|
+
* that deployment, and `rearmFor` clears it when the deployment changes.
|
|
25647
|
+
*
|
|
25648
|
+
* Leaving such a row NULL instead would be worse than the loss it replaces:
|
|
25649
|
+
* these reads carry no cursor, so an unstamped row the deployment refuses is
|
|
25650
|
+
* the head of every subsequent page, and the lane stalls behind it for ever.
|
|
25651
|
+
*/
|
|
25652
|
+
markRefused(ids, atMs) {
|
|
25653
|
+
this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
|
|
25654
|
+
}
|
|
25655
|
+
eachInTransaction(ids, run) {
|
|
25656
|
+
if (ids.length === 0) return;
|
|
25657
|
+
withTransaction(
|
|
25658
|
+
this.db,
|
|
25659
|
+
() => {
|
|
25660
|
+
for (const id of ids) run(id);
|
|
25661
|
+
},
|
|
25662
|
+
"IMMEDIATE"
|
|
25663
|
+
);
|
|
25664
|
+
}
|
|
25665
|
+
stampAll(ids, value, failure, failedAtMs) {
|
|
25666
|
+
if (ids.length === 0) return;
|
|
25667
|
+
const failedAt = failure === null ? null : failedAtMs ?? null;
|
|
25668
|
+
withTransaction(
|
|
25669
|
+
this.db,
|
|
25670
|
+
() => {
|
|
25671
|
+
for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
|
|
25672
|
+
},
|
|
25673
|
+
"IMMEDIATE"
|
|
25674
|
+
);
|
|
25675
|
+
}
|
|
25676
|
+
/**
|
|
25677
|
+
* Claim rows as in-flight.
|
|
25678
|
+
*
|
|
25679
|
+
* Advisory in exactly the sense the lease is: it records that a send is in
|
|
25680
|
+
* progress so a surface can say so, and a lost claim costs a row showing as
|
|
25681
|
+
* queued while it is actually being sent. It is not exclusion — the far side
|
|
25682
|
+
* settles a duplicate on the row id.
|
|
25683
|
+
*/
|
|
25684
|
+
claimRows(ids, atMs) {
|
|
25685
|
+
this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
|
|
25686
|
+
}
|
|
25687
|
+
/** Give back a claim without settling — the send failed, the row is queued again. */
|
|
25688
|
+
releaseRows(ids) {
|
|
25689
|
+
this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
|
|
25690
|
+
}
|
|
25691
|
+
/**
|
|
25692
|
+
* Clear claims older than `staleBefore`, and report how many were cleared.
|
|
25693
|
+
*
|
|
25694
|
+
* A process killed between claiming and settling leaves rows claimed with
|
|
25695
|
+
* nothing left to settle them. Without this they read as "sending" for ever.
|
|
25696
|
+
*/
|
|
25697
|
+
releaseStaleClaims(staleBefore) {
|
|
25698
|
+
return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
|
|
25699
|
+
}
|
|
25700
|
+
/**
|
|
25701
|
+
* Every tracked row in exactly one delivery state.
|
|
25702
|
+
*
|
|
25703
|
+
* Takes no boundary on purpose. The boundary answers "what should the drain
|
|
25704
|
+
* pick up now", which is a different question from "what state is this row
|
|
25705
|
+
* in" — and a machine that has never attached has no boundary to pass, so
|
|
25706
|
+
* requiring one would force a caller to invent one and report the whole store
|
|
25707
|
+
* as queued.
|
|
25708
|
+
*/
|
|
25709
|
+
/**
|
|
25710
|
+
* The same partition, one row per kind that a lane carries.
|
|
25711
|
+
*
|
|
25712
|
+
* A kind with nothing to report is ABSENT rather than a row of zeros: the
|
|
25713
|
+
* scope decides which rows exist at all, so a kind that has never been
|
|
25714
|
+
* recorded — or whose captures nobody ever owed — produces no group. A caller
|
|
25715
|
+
* rendering a fixed list of kinds must therefore treat a missing one as "no
|
|
25716
|
+
* rows", never as "zero sent"; the two look identical in a bar and mean
|
|
25717
|
+
* different things.
|
|
25718
|
+
*/
|
|
25719
|
+
partitionByKind() {
|
|
25720
|
+
return allRows(
|
|
25721
|
+
this.partitionByKindStmt,
|
|
25722
|
+
{}
|
|
25723
|
+
).map((row) => ({
|
|
25724
|
+
kind: row.kind,
|
|
25725
|
+
queued: row.queued ?? 0,
|
|
25726
|
+
inProgress: row.inProgress ?? 0,
|
|
25727
|
+
synced: row.synced ?? 0,
|
|
25728
|
+
failed: row.failed ?? 0,
|
|
25729
|
+
refused: row.refused ?? 0,
|
|
25730
|
+
detached: row.detached ?? 0,
|
|
25731
|
+
total: row.total ?? 0
|
|
25732
|
+
}));
|
|
25733
|
+
}
|
|
25734
|
+
partition() {
|
|
25735
|
+
const row = getRow(this.partitionStmt, {});
|
|
25736
|
+
return {
|
|
25737
|
+
queued: row?.queued ?? 0,
|
|
25738
|
+
inProgress: row?.inProgress ?? 0,
|
|
25739
|
+
synced: row?.synced ?? 0,
|
|
25740
|
+
failed: row?.failed ?? 0,
|
|
25741
|
+
refused: row?.refused ?? 0,
|
|
25742
|
+
detached: row?.detached ?? 0,
|
|
25743
|
+
total: row?.total ?? 0
|
|
25744
|
+
};
|
|
25745
|
+
}
|
|
25746
|
+
/** `pending` counts only what is inside the backlog; sent and skipped are totals. */
|
|
25747
|
+
counts(before) {
|
|
25748
|
+
const row = getRow(this.countsStmt, { before });
|
|
25749
|
+
const captures = getRow(this.captureSkipCountStmt);
|
|
25750
|
+
return {
|
|
25751
|
+
pending: row?.pending ?? 0,
|
|
25752
|
+
sent: row?.sent ?? 0,
|
|
25753
|
+
skipped: row?.skipped ?? 0,
|
|
25754
|
+
refused: row?.refused ?? 0,
|
|
25755
|
+
detached: row?.detached ?? 0,
|
|
25756
|
+
capturesSkipped: captures?.skipped ?? 0
|
|
25757
|
+
};
|
|
25758
|
+
}
|
|
25759
|
+
/**
|
|
25760
|
+
* The deployment the current stamps were made against, and where its backlog
|
|
25761
|
+
* ends.
|
|
25762
|
+
*
|
|
25763
|
+
* READ-ONLY. An absent row reads as an absent deployment, which is what a
|
|
25764
|
+
* machine that has never drained is — and every writer below seeds the row
|
|
25765
|
+
* before it needs one, so nothing depends on this creating it. Keeping the
|
|
25766
|
+
* write off the gate path matters because the gate runs on every pass while a
|
|
25767
|
+
* write has to take the database's write lock.
|
|
25768
|
+
*/
|
|
25769
|
+
deployment() {
|
|
25770
|
+
const row = getRow(
|
|
25771
|
+
this.fingerprintStmt
|
|
25772
|
+
);
|
|
25773
|
+
return {
|
|
25774
|
+
fingerprint: row?.fingerprint ?? void 0,
|
|
25775
|
+
backlogBefore: row?.backlogBefore ?? void 0
|
|
25776
|
+
};
|
|
25777
|
+
}
|
|
25778
|
+
/**
|
|
25779
|
+
* Point the ledger at a different deployment, discarding what it recorded
|
|
25780
|
+
* about the previous one.
|
|
25781
|
+
*
|
|
25782
|
+
* Delivery is a fact about ONE recipient: rows sent to the deployment a
|
|
25783
|
+
* machine has just left are undelivered as far as the new one is concerned.
|
|
25784
|
+
* All four in one transaction, so a crash between them cannot leave stamps
|
|
25785
|
+
* attributed to the wrong deployment, a boundary that belongs to another, or
|
|
25786
|
+
* a disown with no re-mark to follow it.
|
|
25787
|
+
*
|
|
25788
|
+
* The boundary is written HERE and only here, which is what freezes it: a
|
|
25789
|
+
* re-attach to the SAME deployment (a key rotation) leaves the fingerprint
|
|
25790
|
+
* unchanged, so this never runs and the backlog does not widen back over rows
|
|
25791
|
+
* the live path has since delivered.
|
|
25792
|
+
*
|
|
25793
|
+
* `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
|
|
25794
|
+
* granted existing-history consent for the deployment this call is arming —
|
|
25795
|
+
* a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
|
|
25796
|
+
* instant, `backlogBefore` is the ATTACH instant, and the two can be far
|
|
25797
|
+
* apart. Passed only when that grant is valid, since this method has no way
|
|
25798
|
+
* to check consent itself and must not mark a row owed for a machine that
|
|
25799
|
+
* never agreed to it. Applied AFTER the disown above, in the SAME
|
|
25800
|
+
* transaction: what the disown clears is every marker below `backlogBefore`,
|
|
25801
|
+
* which includes this deployment's OWN pre-attach rows — `aka attach` calls
|
|
25802
|
+
* `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
|
|
25803
|
+
* on the cleared side of that bound — and the re-mark in the same
|
|
25804
|
+
* transaction is what puts those rows back. A crash between the two cannot
|
|
25805
|
+
* strand the ledger disowned with nothing re-marked — the transaction either
|
|
25806
|
+
* lands whole or not at all, and a fingerprint mismatch that has not yet
|
|
25807
|
+
* committed re-enters this method on the very next pass. Omit it (the
|
|
25808
|
+
* structural-only tests do) to exercise the disown in isolation.
|
|
25809
|
+
*
|
|
25810
|
+
* The disown is bounded by `backlogBefore`, which is what keeps it from
|
|
25811
|
+
* touching a marker the NEW deployment's OWN live path has already set: B's
|
|
25812
|
+
* live path can mark a capture owed from the moment `aka attach` writes the
|
|
25813
|
+
* descriptor, before the drain's first pass ever reaches this method, and
|
|
25814
|
+
* such a row sits at or after the bound rather than below it. What keeps the
|
|
25815
|
+
* disown from eating THIS SAME CALL's own re-mark is the order, not the
|
|
25816
|
+
* bound — disown runs first, re-mark second, both inside the one
|
|
25817
|
+
* transaction above.
|
|
25818
|
+
*/
|
|
25819
|
+
rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
|
|
25820
|
+
this.ensureRowStmt.run();
|
|
25821
|
+
withTransaction(
|
|
25822
|
+
this.db,
|
|
25823
|
+
() => {
|
|
25824
|
+
const previous = getRow(this.fingerprintStmt)?.fingerprint;
|
|
25825
|
+
this.rearmStmt.run();
|
|
25826
|
+
if (previous !== null && previous !== void 0 && previous !== fingerprint) {
|
|
25827
|
+
this.disownCapturesStmt.run({ attachedAt: backlogBefore });
|
|
25828
|
+
}
|
|
25829
|
+
if (backfillCapturesBefore !== void 0) {
|
|
25830
|
+
this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
|
|
25831
|
+
}
|
|
25832
|
+
this.setFingerprintStmt.run({ fingerprint, backlogBefore });
|
|
25833
|
+
},
|
|
25834
|
+
"IMMEDIATE"
|
|
25835
|
+
);
|
|
25836
|
+
}
|
|
25837
|
+
/**
|
|
25838
|
+
* End the attached period: hand its rows to the live path, and release the
|
|
25839
|
+
* boundary so the next attachment can freeze a new one.
|
|
25840
|
+
*
|
|
25841
|
+
* WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
|
|
25842
|
+
* nothing delivers. The fingerprint is unchanged, so the boundary is never
|
|
25843
|
+
* re-frozen and stays at the FIRST attachment — while nothing forwards at all
|
|
25844
|
+
* during the detached period, because the machine is not attached. Rows
|
|
25845
|
+
* recorded in that window sit after the boundary and before the re-attach, so
|
|
25846
|
+
* neither path takes them, and the pending count reports none outstanding.
|
|
25847
|
+
*
|
|
25848
|
+
* WHAT IT RECORDS, and what it deliberately does not. These rows were the
|
|
25849
|
+
* closing attachment's to deliver and are no longer outstanding — that is what
|
|
25850
|
+
* lets the boundary move. It is NOT a claim that any of them arrived, and the
|
|
25851
|
+
* distinction is not academic: this used to write a delivery TIME, which every
|
|
25852
|
+
* read treats as delivery, so one detach turned a window of undelivered rows
|
|
25853
|
+
* into a window of delivered ones and no surface could tell. It writes the
|
|
25854
|
+
* skip sentinel and a reason of its own instead, so "no longer owed" and
|
|
25855
|
+
* "received" stop being the same fact.
|
|
25856
|
+
*
|
|
25857
|
+
* A change of deployment still frees them (see the re-arm), because the next
|
|
25858
|
+
* deployment has seen none of this machine's history — so the rows reach it
|
|
25859
|
+
* exactly as they did when this wrote a delivery time.
|
|
25860
|
+
*
|
|
25861
|
+
* ONE TRANSACTION, so a crash cannot release the boundary while leaving the
|
|
25862
|
+
* window unstamped — that half-state would re-send the whole attached period
|
|
25863
|
+
* on the next attach, which is the failure the boundary exists to prevent.
|
|
25864
|
+
*/
|
|
25865
|
+
closeAttachedWindow(attachedAtMs, atMs) {
|
|
25866
|
+
this.ensureRowStmt.run();
|
|
25867
|
+
withTransaction(
|
|
25868
|
+
this.db,
|
|
25869
|
+
() => {
|
|
25870
|
+
const row = getRow(this.fingerprintStmt);
|
|
25871
|
+
const from = row?.backlogBefore ?? attachedAtMs;
|
|
25872
|
+
this.closeWindowStmt.run({ at: atMs, attachedAt: from });
|
|
25873
|
+
this.releaseBoundaryStmt.run();
|
|
25874
|
+
},
|
|
25875
|
+
"IMMEDIATE"
|
|
25876
|
+
);
|
|
25877
|
+
}
|
|
25878
|
+
/**
|
|
25879
|
+
* Freeze a boundary for the deployment already on file, KEEPING the stamps.
|
|
25880
|
+
*
|
|
25881
|
+
* The re-attach half of the above. Distinct from `rearmFor`, which is for a
|
|
25882
|
+
* different deployment and therefore discards what was delivered to the old
|
|
25883
|
+
* one: here the recipient is the same, so everything already sent to it stays
|
|
25884
|
+
* sent.
|
|
25885
|
+
*/
|
|
25886
|
+
freezeBoundary(backlogBefore) {
|
|
25887
|
+
this.ensureRowStmt.run();
|
|
25888
|
+
this.freezeBoundaryStmt.run({ backlogBefore });
|
|
25889
|
+
}
|
|
25890
|
+
/** Take the claim, or report that someone live already holds it. */
|
|
25891
|
+
claim(pid, host, nowMs, staleAfterMs) {
|
|
25892
|
+
this.ensureRowStmt.run();
|
|
25893
|
+
let taken = false;
|
|
25894
|
+
withTransaction(
|
|
25895
|
+
this.db,
|
|
25896
|
+
() => {
|
|
25897
|
+
const result = this.claimStmt.run({
|
|
25898
|
+
pid,
|
|
25899
|
+
host,
|
|
25900
|
+
now: nowMs,
|
|
25901
|
+
staleBefore: nowMs - staleAfterMs
|
|
25902
|
+
});
|
|
25903
|
+
taken = result.changes === 1;
|
|
25904
|
+
},
|
|
25905
|
+
"IMMEDIATE"
|
|
25906
|
+
);
|
|
25907
|
+
return taken;
|
|
25908
|
+
}
|
|
25909
|
+
/** Say the holder is still alive. A no-op once the claim has moved on. */
|
|
25910
|
+
heartbeat(pid, nowMs) {
|
|
25911
|
+
this.heartbeatStmt.run({ now: nowMs, pid });
|
|
25912
|
+
}
|
|
25913
|
+
/** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
|
|
25914
|
+
release(pid) {
|
|
25915
|
+
this.releaseStmt.run({ pid });
|
|
25916
|
+
}
|
|
25917
|
+
/** Who holds the claim, if anyone. Read-only, for the same reason as above. */
|
|
25918
|
+
lease() {
|
|
25919
|
+
return getRow(this.leaseStmt);
|
|
25920
|
+
}
|
|
25921
|
+
};
|
|
25922
|
+
|
|
24815
25923
|
// ../../packages/persistence/src/migrations.ts
|
|
24816
25924
|
function describeObject(object2) {
|
|
24817
25925
|
return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
|
|
@@ -24824,7 +25932,7 @@ function createdIndexName(statement) {
|
|
|
24824
25932
|
return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
|
|
24825
25933
|
}
|
|
24826
25934
|
var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
|
|
24827
|
-
function applyMigrations(db, file2) {
|
|
25935
|
+
function applyMigrations(db, file2, options = {}) {
|
|
24828
25936
|
const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
|
|
24829
25937
|
db.exec(
|
|
24830
25938
|
"CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
|
|
@@ -24838,6 +25946,7 @@ function applyMigrations(db, file2) {
|
|
|
24838
25946
|
);
|
|
24839
25947
|
for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
|
|
24840
25948
|
if (applied.has(migration.tag)) continue;
|
|
25949
|
+
if (options.skipTags?.has(migration.tag) === true) continue;
|
|
24841
25950
|
if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
|
|
24842
25951
|
const evidence = evidenceObjects(migration.sql);
|
|
24843
25952
|
const present = evidence.filter((o) => evidenceExists(db, o));
|
|
@@ -25244,10 +26353,62 @@ function ensureSyncedAtColumn(db, table2) {
|
|
|
25244
26353
|
if (!columns.includes("outbox_owed")) {
|
|
25245
26354
|
db.exec(`ALTER TABLE ${table2} ADD COLUMN outbox_owed integer`);
|
|
25246
26355
|
}
|
|
26356
|
+
if (!columns.includes("sync_failed_at")) {
|
|
26357
|
+
db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failed_at integer`);
|
|
26358
|
+
}
|
|
26359
|
+
if (!columns.includes("sync_failure")) {
|
|
26360
|
+
withTransaction(
|
|
26361
|
+
db,
|
|
26362
|
+
() => {
|
|
26363
|
+
db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failure text`);
|
|
26364
|
+
db.exec(
|
|
26365
|
+
`UPDATE ${table2} SET synced_at = NULL
|
|
26366
|
+
WHERE synced_at = -1
|
|
26367
|
+
AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
|
|
26368
|
+
);
|
|
26369
|
+
},
|
|
26370
|
+
"IMMEDIATE"
|
|
26371
|
+
);
|
|
26372
|
+
}
|
|
25247
26373
|
db.exec(
|
|
25248
|
-
`CREATE
|
|
25249
|
-
|
|
26374
|
+
`CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
|
|
26375
|
+
BEFORE UPDATE OF sync_failure ON ${table2}
|
|
26376
|
+
WHEN ${syncFailureRejectCondition()}
|
|
26377
|
+
BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
|
|
25250
26378
|
);
|
|
26379
|
+
const syncIndexColumns = [
|
|
26380
|
+
"event_type",
|
|
26381
|
+
"synced_at",
|
|
26382
|
+
"sync_claimed_at",
|
|
26383
|
+
"started_at",
|
|
26384
|
+
// Appended LAST on purpose. The delivery-state read now projects it, so it
|
|
26385
|
+
// has to be in the index for the read to stay covered — but putting it
|
|
26386
|
+
// ahead of `started_at` would reorder the prefix the structural drain's
|
|
26387
|
+
// reads match on.
|
|
26388
|
+
"sync_failure"
|
|
26389
|
+
// `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
|
|
26390
|
+
//
|
|
26391
|
+
// The delivery-state read tests it — a capture's state depends on whether a
|
|
26392
|
+
// live forward marked it owed — so carrying it here makes that read covering
|
|
26393
|
+
// rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
|
|
26394
|
+
// But a sixth column changes what the planner charges for this index, and
|
|
26395
|
+
// with no ANALYZE statistics it plans from schema shape alone: measured, it
|
|
26396
|
+
// then stops choosing the per-session index for the token rollup and walks
|
|
26397
|
+
// every `llm_call` in the store through the event-type index instead. That
|
|
26398
|
+
// read grows with the store; this one does not.
|
|
26399
|
+
//
|
|
26400
|
+
// 40 ms on the largest store measured, once per render, is a cost worth
|
|
26401
|
+
// paying to leave every other read's plan where it was.
|
|
26402
|
+
];
|
|
26403
|
+
const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
|
|
26404
|
+
const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
|
|
26405
|
+
if (!syncIndexMatches) {
|
|
26406
|
+
db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
|
|
26407
|
+
db.exec(
|
|
26408
|
+
`CREATE INDEX idx_audit_events_sync
|
|
26409
|
+
ON audit_events (${syncIndexColumns.join(", ")})`
|
|
26410
|
+
);
|
|
26411
|
+
}
|
|
25251
26412
|
db.exec(
|
|
25252
26413
|
`CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
|
|
25253
26414
|
ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
|
|
@@ -25469,7 +26630,11 @@ function buildAuditEvent(row) {
|
|
|
25469
26630
|
link: linkParsed?.success ? linkParsed.data : null,
|
|
25470
26631
|
targetId: row.target_id,
|
|
25471
26632
|
internal: intToBool(row.internal),
|
|
25472
|
-
flagged: intToBool(row.flagged)
|
|
26633
|
+
flagged: intToBool(row.flagged),
|
|
26634
|
+
// Only meaningful when the title came out empty — a row whose body was
|
|
26635
|
+
// expired but whose title fell back to `tool_name` still has something to
|
|
26636
|
+
// render, and flagging it would make the view apologise for nothing.
|
|
26637
|
+
bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
|
|
25473
26638
|
};
|
|
25474
26639
|
}
|
|
25475
26640
|
var TIMELINE_COLUMNS = `
|
|
@@ -25477,6 +26642,7 @@ var TIMELINE_COLUMNS = `
|
|
|
25477
26642
|
event_type,
|
|
25478
26643
|
started_at,
|
|
25479
26644
|
coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
|
|
26645
|
+
content_expired_at,
|
|
25480
26646
|
coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
|
|
25481
26647
|
coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
|
|
25482
26648
|
json_extract(attributes, '$.severity') AS severity,
|
|
@@ -25603,7 +26769,8 @@ var SqliteActivityRepository = class {
|
|
|
25603
26769
|
SELECT 1 FROM audit_events d
|
|
25604
26770
|
WHERE d.root_session_id = audit_events.id
|
|
25605
26771
|
AND (d.content LIKE ? ESCAPE '\\'
|
|
25606
|
-
OR json_extract(d.attributes, '$.detail')
|
|
26772
|
+
OR coalesce(json_extract(d.attributes, '$.detail'),
|
|
26773
|
+
json_extract(d.attributes, '$.target')) LIKE ? ESCAPE '\\')))`
|
|
25607
26774
|
);
|
|
25608
26775
|
params.push(pattern, pattern, pattern, pattern, pattern, pattern);
|
|
25609
26776
|
}
|
|
@@ -26141,6 +27308,88 @@ var SqliteAuditEventsRepository = class {
|
|
|
26141
27308
|
}
|
|
26142
27309
|
};
|
|
26143
27310
|
|
|
27311
|
+
// ../../packages/persistence/src/repositories/body-retention.ts
|
|
27312
|
+
var DEFAULT_BATCH_SIZE = 500;
|
|
27313
|
+
var DEFAULT_MAX_ROWS = 5e4;
|
|
27314
|
+
var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
|
|
27315
|
+
var SqliteBodyRetentionRepository = class {
|
|
27316
|
+
constructor(db) {
|
|
27317
|
+
this.db = db;
|
|
27318
|
+
const select = (laneClause) => `
|
|
27319
|
+
SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
|
|
27320
|
+
FROM audit_events
|
|
27321
|
+
WHERE content IS NOT NULL
|
|
27322
|
+
AND started_at < :cutoff
|
|
27323
|
+
AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
|
|
27324
|
+
${laneClause}
|
|
27325
|
+
ORDER BY started_at
|
|
27326
|
+
LIMIT :limit`;
|
|
27327
|
+
this.candidatesStmt = this.db.prepare(select(""));
|
|
27328
|
+
this.candidatesSyncSafeStmt = this.db.prepare(
|
|
27329
|
+
select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
|
|
27330
|
+
);
|
|
27331
|
+
this.heldBySyncStmt = this.db.prepare(`
|
|
27332
|
+
SELECT COUNT(*) AS n
|
|
27333
|
+
FROM audit_events
|
|
27334
|
+
WHERE content IS NOT NULL
|
|
27335
|
+
AND started_at < :cutoff
|
|
27336
|
+
AND event_type IN (${SYNC_LANE_TYPES_SQL})
|
|
27337
|
+
AND synced_at IS NULL`);
|
|
27338
|
+
this.expireStmt = this.db.prepare(
|
|
27339
|
+
`UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
|
|
27340
|
+
);
|
|
27341
|
+
}
|
|
27342
|
+
db;
|
|
27343
|
+
candidatesStmt;
|
|
27344
|
+
candidatesSyncSafeStmt;
|
|
27345
|
+
heldBySyncStmt;
|
|
27346
|
+
expireStmt;
|
|
27347
|
+
/** How many bytes a pass with these options would free, changing nothing. */
|
|
27348
|
+
preview(opts) {
|
|
27349
|
+
const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
|
|
27350
|
+
const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
|
|
27351
|
+
const rows = stmt.all({ cutoff: opts.cutoff, limit });
|
|
27352
|
+
return {
|
|
27353
|
+
rowsExpired: rows.length,
|
|
27354
|
+
bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
|
|
27355
|
+
rowsHeldBySync: this.countHeldBySync(opts)
|
|
27356
|
+
};
|
|
27357
|
+
}
|
|
27358
|
+
/** Clear eligible bodies, in bounded batches. */
|
|
27359
|
+
expire(opts) {
|
|
27360
|
+
const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
|
|
27361
|
+
const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
|
|
27362
|
+
const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
|
|
27363
|
+
let rowsExpired = 0;
|
|
27364
|
+
let bytesFreed = 0;
|
|
27365
|
+
let done = true;
|
|
27366
|
+
while (rowsExpired < maxRows) {
|
|
27367
|
+
const remaining = Math.min(batchSize, maxRows - rowsExpired);
|
|
27368
|
+
const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
|
|
27369
|
+
if (batch.length === 0) break;
|
|
27370
|
+
withTransaction(
|
|
27371
|
+
this.db,
|
|
27372
|
+
() => {
|
|
27373
|
+
for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
|
|
27374
|
+
},
|
|
27375
|
+
"IMMEDIATE"
|
|
27376
|
+
);
|
|
27377
|
+
rowsExpired += batch.length;
|
|
27378
|
+
bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
|
|
27379
|
+
if (batch.length < remaining) break;
|
|
27380
|
+
if (rowsExpired >= maxRows) {
|
|
27381
|
+
done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
|
|
27382
|
+
}
|
|
27383
|
+
}
|
|
27384
|
+
return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
|
|
27385
|
+
}
|
|
27386
|
+
countHeldBySync(opts) {
|
|
27387
|
+
if (opts.sweepSyncLane) return 0;
|
|
27388
|
+
const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
|
|
27389
|
+
return row.n;
|
|
27390
|
+
}
|
|
27391
|
+
};
|
|
27392
|
+
|
|
26144
27393
|
// ../../packages/persistence/src/repositories/classified-data.ts
|
|
26145
27394
|
var SqliteClassifiedDataRepository = class {
|
|
26146
27395
|
constructor(db) {
|
|
@@ -26941,23 +28190,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
|
|
|
26941
28190
|
)`;
|
|
26942
28191
|
|
|
26943
28192
|
// ../../packages/persistence/src/repositories/findings.ts
|
|
26944
|
-
var PREVIEW_INSTANCES_PER_GROUP = 200;
|
|
26945
|
-
var DEFAULT_LOCATIONS_LIMIT = 100;
|
|
26946
|
-
var LOCATION_RULE_IDS_CAP = 20;
|
|
26947
|
-
function compareLocationOrder(a, b) {
|
|
26948
|
-
return compareFindingGroupOrder(
|
|
26949
|
-
{
|
|
26950
|
-
severity: a.maxSeverity,
|
|
26951
|
-
latestDetectedAt: a.latestDetectedAt,
|
|
26952
|
-
id: ""
|
|
26953
|
-
},
|
|
26954
|
-
{
|
|
26955
|
-
severity: b.maxSeverity,
|
|
26956
|
-
latestDetectedAt: b.latestDetectedAt,
|
|
26957
|
-
id: ""
|
|
26958
|
-
}
|
|
26959
|
-
);
|
|
26960
|
-
}
|
|
26961
28193
|
var CONCAT_SEP = ",";
|
|
26962
28194
|
var TUPLE_SEP = "|";
|
|
26963
28195
|
function splitConcat(value) {
|
|
@@ -26986,7 +28218,15 @@ function toFlatFindingRow(r) {
|
|
|
26986
28218
|
...r.tool_name === null ? {} : { toolName: r.tool_name },
|
|
26987
28219
|
eventId: r.event_id,
|
|
26988
28220
|
...r.session_id === null ? {} : { sessionId: r.session_id },
|
|
26989
|
-
status: deriveInstanceStatus(r)
|
|
28221
|
+
status: deriveInstanceStatus(r),
|
|
28222
|
+
delivery: deriveFindingDelivery({
|
|
28223
|
+
kind: r.kind,
|
|
28224
|
+
syncedAt: r.synced_at,
|
|
28225
|
+
syncClaimedAt: r.sync_claimed_at,
|
|
28226
|
+
syncFailedAt: r.sync_failed_at,
|
|
28227
|
+
syncFailure: r.sync_failure,
|
|
28228
|
+
outboxOwed: r.outbox_owed
|
|
28229
|
+
})
|
|
26990
28230
|
};
|
|
26991
28231
|
}
|
|
26992
28232
|
function encodeGroupCursor(group) {
|
|
@@ -27009,13 +28249,51 @@ function decodeGroupCursor(cursor) {
|
|
|
27009
28249
|
return null;
|
|
27010
28250
|
}
|
|
27011
28251
|
function firstAfter(sorted, cursor) {
|
|
27012
|
-
const index = sorted.findIndex((
|
|
28252
|
+
const index = sorted.findIndex((t) => compareFindingGroupOrder(t, cursor) > 0);
|
|
27013
28253
|
return index === -1 ? sorted.length : index;
|
|
27014
28254
|
}
|
|
27015
28255
|
function findDeepLinked(sorted, page, id) {
|
|
27016
|
-
if (page.some((
|
|
27017
|
-
return sorted.find((
|
|
28256
|
+
if (page.some((t) => t.id === id)) return void 0;
|
|
28257
|
+
return sorted.find((t) => t.id === id);
|
|
28258
|
+
}
|
|
28259
|
+
function encodeLocationCursor(location) {
|
|
28260
|
+
const payload = {
|
|
28261
|
+
sev: location.maxSeverity,
|
|
28262
|
+
t: location.latestDetectedAt,
|
|
28263
|
+
r: location.repo,
|
|
28264
|
+
f: location.file
|
|
28265
|
+
};
|
|
28266
|
+
return Buffer.from(JSON.stringify(payload)).toString("base64url");
|
|
28267
|
+
}
|
|
28268
|
+
function decodeLocationCursor(cursor) {
|
|
28269
|
+
const parsed2 = parseJsonObject(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
28270
|
+
if (parsed2 !== void 0 && typeof parsed2.sev === "string" && typeof parsed2.t === "string" && typeof parsed2.r === "string" && typeof parsed2.f === "string") {
|
|
28271
|
+
return { maxSeverity: parsed2.sev, latestDetectedAt: parsed2.t, repo: parsed2.r, file: parsed2.f };
|
|
28272
|
+
}
|
|
28273
|
+
return null;
|
|
27018
28274
|
}
|
|
28275
|
+
function firstLocationAfter(sorted, cursor) {
|
|
28276
|
+
const index = sorted.findIndex((l) => compareLocationOrder(l, cursor) > 0);
|
|
28277
|
+
return index === -1 ? sorted.length : index;
|
|
28278
|
+
}
|
|
28279
|
+
function findDeepLinkedLocation(sorted, page, id) {
|
|
28280
|
+
if (page.some((l) => l.id === id)) return void 0;
|
|
28281
|
+
return sorted.find((l) => l.id === id);
|
|
28282
|
+
}
|
|
28283
|
+
var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS category,
|
|
28284
|
+
d.severity AS severity, f.masked_match AS masked_match,
|
|
28285
|
+
f.action_taken AS action_taken, f.confidence AS confidence,
|
|
28286
|
+
e.started_at AS occurred_at,
|
|
28287
|
+
e.source_tool AS source_tool,
|
|
28288
|
+
e.repo AS repo,
|
|
28289
|
+
e.file_path AS file,
|
|
28290
|
+
e.tool_name AS tool_name,
|
|
28291
|
+
f.audit_event_id AS event_id, e.root_session_id AS session_id,
|
|
28292
|
+
e.event_type AS kind, f.finding_key AS finding_key,
|
|
28293
|
+
${latestResolutionStatusSql("f")} AS latest_status,
|
|
28294
|
+
e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
|
|
28295
|
+
e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
|
|
28296
|
+
e.outbox_owed AS outbox_owed`;
|
|
27019
28297
|
var DAY_MS3 = 864e5;
|
|
27020
28298
|
var SqliteFindingsRepository = class {
|
|
27021
28299
|
constructor(db) {
|
|
@@ -27136,30 +28414,26 @@ var SqliteFindingsRepository = class {
|
|
|
27136
28414
|
);
|
|
27137
28415
|
}
|
|
27138
28416
|
/**
|
|
27139
|
-
*
|
|
27140
|
-
*
|
|
27141
|
-
*
|
|
27142
|
-
*
|
|
27143
|
-
*
|
|
27144
|
-
*
|
|
27145
|
-
*
|
|
27146
|
-
*
|
|
27147
|
-
*
|
|
27148
|
-
*
|
|
27149
|
-
*
|
|
27150
|
-
*
|
|
28417
|
+
* Finding TYPES for the dashboard — one row per rule, scoped to the four
|
|
28418
|
+
* capture kinds (audit_events also holds structural/reconciler/scan rows this
|
|
28419
|
+
* list must never surface), with per-filter-excluded facets, the requested
|
|
28420
|
+
* filters applied, and sorted by severity then recency. Filtering and faceting
|
|
28421
|
+
* run in JS via the shared @akasecurity/schema helpers. `totals` reflect the
|
|
28422
|
+
* full filtered set; `items` is the requested page (default 50), keyset-paged.
|
|
28423
|
+
* Under a `status` filter, `totals.findings` counts only findings whose
|
|
28424
|
+
* derived status was requested.
|
|
28425
|
+
*
|
|
28426
|
+
* ONE read, which materializes no findings: a single aggregate per rule_id,
|
|
28427
|
+
* folding EVERY finding into the numbers a type row and the filters need
|
|
28428
|
+
* (count, severity, category, providers, actions, statuses, latest, search
|
|
28429
|
+
* text). The findings OF a type come from listFindingInstances scoped to
|
|
28430
|
+
* `subtype`, so neither list bounds the other and no per-type cap exists.
|
|
27151
28431
|
*
|
|
27152
|
-
* Two reads, neither of which materializes a row per finding:
|
|
27153
|
-
* 1. one aggregate row per rule_id, folding EVERY instance into the numbers
|
|
27154
|
-
* the group and the filters need (count, providers, actions, statuses,
|
|
27155
|
-
* latest, search text);
|
|
27156
|
-
* 2. each group's newest PREVIEW_INSTANCES_PER_GROUP instances, which
|
|
27157
|
-
* populate `instances` for the table's expanded rows.
|
|
27158
28432
|
* The aggregates carry raw DB values and are translated by the same
|
|
27159
|
-
* @akasecurity/schema mappers
|
|
27160
|
-
* rule is ever restated in SQL.
|
|
28433
|
+
* @akasecurity/schema mappers every other path uses, so no enum mapping or
|
|
28434
|
+
* status rule is ever restated in SQL.
|
|
27161
28435
|
*/
|
|
27162
|
-
|
|
28436
|
+
listFindingTypes(query) {
|
|
27163
28437
|
const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
|
|
27164
28438
|
const fromMs = query.from === void 0 ? void 0 : isoToEpochMillis(query.from);
|
|
27165
28439
|
const fromPredicate = fromMs === void 0 ? "" : ` AND e.started_at >= :fromMs`;
|
|
@@ -27172,12 +28446,7 @@ var SqliteFindingsRepository = class {
|
|
|
27172
28446
|
predicate,
|
|
27173
28447
|
params: sessionParams
|
|
27174
28448
|
});
|
|
27175
|
-
const
|
|
27176
|
-
sessionId: query.sessionId,
|
|
27177
|
-
from: query.from
|
|
27178
|
-
});
|
|
27179
|
-
const groupable = rows.map(toFlatFindingRow);
|
|
27180
|
-
const allGroups = buildFindingGroups(groupable, { aggregates });
|
|
28449
|
+
const allTypes = buildFindingTypes(aggregates);
|
|
27181
28450
|
const filterOpts = {
|
|
27182
28451
|
severity: query.severity,
|
|
27183
28452
|
providers: query.provider,
|
|
@@ -27186,30 +28455,25 @@ var SqliteFindingsRepository = class {
|
|
|
27186
28455
|
subtype: query.subtype,
|
|
27187
28456
|
q: query.q
|
|
27188
28457
|
};
|
|
27189
|
-
const facets = computeFindingFacets(
|
|
27190
|
-
const sorted =
|
|
28458
|
+
const facets = computeFindingFacets(allTypes, filterOpts);
|
|
28459
|
+
const sorted = sortFindingTypes(applyFindingFilters(allTypes, filterOpts));
|
|
27191
28460
|
const statusFilter = query.status ?? [];
|
|
27192
28461
|
const totals = {
|
|
27193
|
-
findings: sorted.reduce((acc,
|
|
27194
|
-
if (statusFilter.length === 0) return acc +
|
|
27195
|
-
const agg = aggregates.get(
|
|
27196
|
-
return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ??
|
|
28462
|
+
findings: sorted.reduce((acc, t) => {
|
|
28463
|
+
if (statusFilter.length === 0) return acc + t.instanceCount;
|
|
28464
|
+
const agg = aggregates.get(t.id);
|
|
28465
|
+
return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? t.instanceCount : t.instanceCount);
|
|
27197
28466
|
}, 0),
|
|
27198
|
-
|
|
28467
|
+
types: sorted.length
|
|
27199
28468
|
};
|
|
27200
|
-
const limit = query.limit ??
|
|
28469
|
+
const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
|
|
27201
28470
|
const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
|
|
27202
28471
|
const start = cursor === null ? 0 : firstAfter(sorted, cursor);
|
|
27203
28472
|
const page = sorted.slice(start, start + limit);
|
|
27204
28473
|
const lastOnPage = page.at(-1);
|
|
27205
28474
|
const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
|
|
27206
28475
|
const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinked(sorted, page, query.includeId);
|
|
27207
|
-
const
|
|
27208
|
-
const narrow = (g) => statusSet ? {
|
|
27209
|
-
...g,
|
|
27210
|
-
instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
|
|
27211
|
-
} : g;
|
|
27212
|
-
const items = [...page, ...deepLinked ? [deepLinked] : []].map(narrow);
|
|
28476
|
+
const items = [...page, ...deepLinked ? [deepLinked] : []];
|
|
27213
28477
|
return Promise.resolve({
|
|
27214
28478
|
totals,
|
|
27215
28479
|
facets,
|
|
@@ -27220,7 +28484,7 @@ var SqliteFindingsRepository = class {
|
|
|
27220
28484
|
}
|
|
27221
28485
|
/**
|
|
27222
28486
|
* One row per rule_id, folding EVERY instance of the group into the values
|
|
27223
|
-
*
|
|
28487
|
+
* buildFindingTypes cannot recover from an aggregate. Bounded by the number of
|
|
27224
28488
|
* distinct rule_ids (the installed packs' rules), not by the store's size.
|
|
27225
28489
|
*
|
|
27226
28490
|
* A single scan, folded in two levels: the inner SELECT groups by
|
|
@@ -27274,6 +28538,7 @@ var SqliteFindingsRepository = class {
|
|
|
27274
28538
|
providers: query.provider,
|
|
27275
28539
|
actions: query.action,
|
|
27276
28540
|
statuses: query.status,
|
|
28541
|
+
deliveries: query.deployment,
|
|
27277
28542
|
tools: query.tool,
|
|
27278
28543
|
repo: query.repo,
|
|
27279
28544
|
file: query.file,
|
|
@@ -27314,13 +28579,25 @@ var SqliteFindingsRepository = class {
|
|
|
27314
28579
|
});
|
|
27315
28580
|
}
|
|
27316
28581
|
/**
|
|
27317
|
-
* The same findings folded by
|
|
28582
|
+
* The same findings folded by WHERE they live — one row per (repo, file) pair.
|
|
27318
28583
|
*
|
|
27319
28584
|
* The grouping keys come from the capturing event's attributes, which is what
|
|
27320
|
-
* the local store relates a finding to
|
|
27321
|
-
*
|
|
27322
|
-
* empty-string bucket, which
|
|
27323
|
-
*
|
|
28585
|
+
* the local store relates a finding to; there is no finding↔asset row to group
|
|
28586
|
+
* by instead. A repo or file the event did not record folds into the
|
|
28587
|
+
* empty-string bucket, which is a real location like any other: it is listed,
|
|
28588
|
+
* it is selectable, and its `?loc=` token is as good as any other row's.
|
|
28589
|
+
*
|
|
28590
|
+
* ONE flat list rather than repos nesting files. A rollup can only be paged by
|
|
28591
|
+
* repo, which leaves the file list inside it unbounded — the shape the by-type
|
|
28592
|
+
* list was rebuilt to remove — and two-level pagination inside an
|
|
28593
|
+
* expand/collapse table is what pushed that view to master/detail in the first
|
|
28594
|
+
* place.
|
|
28595
|
+
*
|
|
28596
|
+
* Every filter narrows the FINDINGS and the locations fall out of what
|
|
28597
|
+
* survives, so each row's `instanceCount` is exactly what listFindingInstances
|
|
28598
|
+
* reports for the same filters scoped to that pair. The view depends on it:
|
|
28599
|
+
* one toolbar sits over both panels precisely because a location owns none of
|
|
28600
|
+
* its fields.
|
|
27324
28601
|
*/
|
|
27325
28602
|
listFindingLocations(query) {
|
|
27326
28603
|
const opts = {
|
|
@@ -27329,16 +28606,20 @@ var SqliteFindingsRepository = class {
|
|
|
27329
28606
|
providers: query.provider,
|
|
27330
28607
|
actions: query.action,
|
|
27331
28608
|
statuses: query.status,
|
|
28609
|
+
deliveries: query.deployment,
|
|
27332
28610
|
tools: query.tool,
|
|
27333
28611
|
q: query.q
|
|
27334
28612
|
};
|
|
27335
|
-
const limit = query.limit ??
|
|
28613
|
+
const limit = query.limit ?? DEFAULT_FINDING_LOCATIONS_LIMIT;
|
|
28614
|
+
const cursor = query.cursor === void 0 ? null : decodeLocationCursor(query.cursor);
|
|
27336
28615
|
const byRepo = /* @__PURE__ */ new Map();
|
|
28616
|
+
const accumulator = createInstanceFacetAccumulator(opts);
|
|
27337
28617
|
let total = 0;
|
|
27338
28618
|
for (const row of this.scanFindingRows({
|
|
27339
28619
|
sessionId: query.sessionId,
|
|
27340
28620
|
from: query.from
|
|
27341
28621
|
})) {
|
|
28622
|
+
accumulator.add(row);
|
|
27342
28623
|
if (!matchesInstanceFilters(row, opts)) continue;
|
|
27343
28624
|
total += 1;
|
|
27344
28625
|
let files = byRepo.get(row.repo);
|
|
@@ -27353,103 +28634,35 @@ var SqliteFindingsRepository = class {
|
|
|
27353
28634
|
}
|
|
27354
28635
|
addToLocation(acc, row);
|
|
27355
28636
|
}
|
|
27356
|
-
|
|
27357
|
-
const
|
|
27358
|
-
|
|
27359
|
-
|
|
27360
|
-
|
|
27361
|
-
|
|
27362
|
-
|
|
27363
|
-
|
|
27364
|
-
|
|
27365
|
-
|
|
27366
|
-
|
|
27367
|
-
|
|
27368
|
-
|
|
27369
|
-
|
|
27370
|
-
|
|
27371
|
-
|
|
27372
|
-
|
|
27373
|
-
|
|
27374
|
-
|
|
27375
|
-
|
|
27376
|
-
|
|
27377
|
-
|
|
27378
|
-
);
|
|
27379
|
-
const statuses = fileRows.map((f) => f.status);
|
|
27380
|
-
const folded = foldGroupStatus(statuses);
|
|
27381
|
-
return {
|
|
27382
|
-
repo,
|
|
27383
|
-
instanceCount: rollup.instanceCount,
|
|
27384
|
-
maxSeverity: rollup.maxSeverity,
|
|
27385
|
-
latestDetectedAt: rollup.latestDetectedAt,
|
|
27386
|
-
...folded === void 0 ? {} : { status: folded },
|
|
27387
|
-
files: fileRows
|
|
27388
|
-
};
|
|
27389
|
-
});
|
|
27390
|
-
repos.sort(compareLocationOrder);
|
|
28637
|
+
const sorted = [];
|
|
28638
|
+
for (const [repo, files] of byRepo) {
|
|
28639
|
+
for (const [file2, acc] of files) {
|
|
28640
|
+
const status = foldGroupStatus(acc.statuses);
|
|
28641
|
+
sorted.push({
|
|
28642
|
+
id: encodeLocationId(repo, file2),
|
|
28643
|
+
repo,
|
|
28644
|
+
file: file2,
|
|
28645
|
+
instanceCount: acc.instanceCount,
|
|
28646
|
+
maxSeverity: acc.maxSeverity,
|
|
28647
|
+
latestDetectedAt: acc.latestDetectedAt,
|
|
28648
|
+
...status === void 0 ? {} : { status },
|
|
28649
|
+
ruleIds: [...acc.ruleIds]
|
|
28650
|
+
});
|
|
28651
|
+
}
|
|
28652
|
+
}
|
|
28653
|
+
sorted.sort(compareLocationOrder);
|
|
28654
|
+
const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
|
|
28655
|
+
const page = sorted.slice(start, start + limit);
|
|
28656
|
+
const lastOnPage = page.at(-1);
|
|
28657
|
+
const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
|
|
28658
|
+
const deepLinked = query.includeId === void 0 || query.includeId === "" ? void 0 : findDeepLinkedLocation(sorted, page, query.includeId);
|
|
27391
28659
|
return Promise.resolve({
|
|
27392
|
-
totals: { findings: total,
|
|
27393
|
-
|
|
27394
|
-
|
|
28660
|
+
totals: { findings: total, locations: sorted.length },
|
|
28661
|
+
facets: accumulator.facets(),
|
|
28662
|
+
items: [...page, ...deepLinked ? [deepLinked] : []],
|
|
28663
|
+
nextCursor
|
|
27395
28664
|
});
|
|
27396
28665
|
}
|
|
27397
|
-
/**
|
|
27398
|
-
* Each group's newest instances, for the table's expanded rows.
|
|
27399
|
-
*
|
|
27400
|
-
* ONE index-ordered scan with early termination, and the shape is the point.
|
|
27401
|
-
* The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
|
|
27402
|
-
* started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
|
|
27403
|
-
* through a temp B-tree to keep a bounded preview of each group, and then
|
|
27404
|
-
* sorts the survivors again for the page order. Both sorts grow with the
|
|
27405
|
-
* store while the answer does not.
|
|
27406
|
-
*
|
|
27407
|
-
* Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
|
|
27408
|
-
* (or the session or window index the scope names — see `findingScanSql`),
|
|
27409
|
-
* which is already the order the page wants, and keeps rows per rule until
|
|
27410
|
-
* each rule has as many as it can show. The aggregate the caller already holds
|
|
27411
|
-
* says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
|
|
27412
|
-
* per rule, summed, is the number of rows this scan has to find, and it stops
|
|
27413
|
-
* on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
|
|
27414
|
-
* (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
|
|
27415
|
-
* store with many firing rules widens it. The bound that DOES hold
|
|
27416
|
-
* unconditionally is the sorted form's floor: this scan visits at most as
|
|
27417
|
-
* many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
|
|
27418
|
-
* sorted, and stops the moment every rule has its cap, where the sorted form
|
|
27419
|
-
* sorts the whole scope regardless. The true worst case — the rarest rule's
|
|
27420
|
-
* wanted instances sitting at the tail of the scope — is one pass over
|
|
27421
|
-
* everything in scope with a block sort of the id tie-break only, never a
|
|
27422
|
-
* sort of the scope, which is still that floor.
|
|
27423
|
-
*
|
|
27424
|
-
* A row whose rule the aggregate did not see is skipped: the two statements
|
|
27425
|
-
* run without a shared snapshot, so a capture landing between them can add a
|
|
27426
|
-
* rule here that has no counts there, and the counts are what the group is
|
|
27427
|
-
* built from.
|
|
27428
|
-
*/
|
|
27429
|
-
previewRows(aggregates, scope) {
|
|
27430
|
-
const wanted = /* @__PURE__ */ new Map();
|
|
27431
|
-
let remaining = 0;
|
|
27432
|
-
for (const [ruleId, agg] of aggregates) {
|
|
27433
|
-
const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
|
|
27434
|
-
wanted.set(ruleId, n);
|
|
27435
|
-
remaining += n;
|
|
27436
|
-
}
|
|
27437
|
-
const rows = [];
|
|
27438
|
-
if (remaining === 0) return rows;
|
|
27439
|
-
const { sql, params } = this.findingScanSql(scope);
|
|
27440
|
-
const taken = /* @__PURE__ */ new Map();
|
|
27441
|
-
for (const r of iterateRows(this.db.prepare(sql), params)) {
|
|
27442
|
-
const want = wanted.get(r.rule_id);
|
|
27443
|
-
if (want === void 0) continue;
|
|
27444
|
-
const have = taken.get(r.rule_id) ?? 0;
|
|
27445
|
-
if (have >= want) continue;
|
|
27446
|
-
taken.set(r.rule_id, have + 1);
|
|
27447
|
-
rows.push(r);
|
|
27448
|
-
remaining -= 1;
|
|
27449
|
-
if (remaining === 0) break;
|
|
27450
|
-
}
|
|
27451
|
-
return rows;
|
|
27452
|
-
}
|
|
27453
28666
|
/**
|
|
27454
28667
|
* Every finding in scope as a FlatFindingRow, newest first, streamed.
|
|
27455
28668
|
*
|
|
@@ -27476,6 +28689,33 @@ var SqliteFindingsRepository = class {
|
|
|
27476
28689
|
yield toFlatFindingRow(r);
|
|
27477
28690
|
}
|
|
27478
28691
|
}
|
|
28692
|
+
/**
|
|
28693
|
+
* One finding by its own id, or null when no such row exists.
|
|
28694
|
+
*
|
|
28695
|
+
* A primary-key seek on `inspection_findings`, so its cost does not grow with
|
|
28696
|
+
* the store — and, unlike anything derived from a list page, it resolves a
|
|
28697
|
+
* finding of ANY age. That is what the Findings page's one-shot `?finding=`
|
|
28698
|
+
* deep link needs: the id it carries may name a finding thousands of rows
|
|
28699
|
+
* older than anything a first page holds.
|
|
28700
|
+
*
|
|
28701
|
+
* Deliberately UNFILTERED — no capture-kind, session or time predicate. It
|
|
28702
|
+
* RESOLVES an id; whether that row would survive the list's current filters is
|
|
28703
|
+
* a different question, and hiding the target because a filter excludes it is
|
|
28704
|
+
* worse than showing it.
|
|
28705
|
+
*
|
|
28706
|
+
* `groupId` on the result IS the rule id, so this one read answers both "which
|
|
28707
|
+
* type should the list select?" and "what does the drawer show?".
|
|
28708
|
+
*/
|
|
28709
|
+
findingInstance(id) {
|
|
28710
|
+
const row = this.db.prepare(
|
|
28711
|
+
`SELECT ${FINDING_ROW_COLUMNS_SQL}
|
|
28712
|
+
FROM inspection_findings f
|
|
28713
|
+
JOIN audit_events e ON e.id = f.audit_event_id
|
|
28714
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
28715
|
+
WHERE f.id = ?`
|
|
28716
|
+
).get(id);
|
|
28717
|
+
return Promise.resolve(row === void 0 ? null : toInstanceDetail(toFlatFindingRow(row)));
|
|
28718
|
+
}
|
|
27479
28719
|
/**
|
|
27480
28720
|
* The one statement both instance-level scans run: every finding in scope,
|
|
27481
28721
|
* joined to its event and definition, newest first.
|
|
@@ -27509,17 +28749,7 @@ var SqliteFindingsRepository = class {
|
|
|
27509
28749
|
conditions.push("e.started_at >= ?");
|
|
27510
28750
|
params.push(isoToEpochMillis(scope.from));
|
|
27511
28751
|
}
|
|
27512
|
-
const sql = `SELECT
|
|
27513
|
-
d.severity AS severity, f.masked_match AS masked_match,
|
|
27514
|
-
f.action_taken AS action_taken, f.confidence AS confidence,
|
|
27515
|
-
e.started_at AS occurred_at,
|
|
27516
|
-
e.source_tool AS source_tool,
|
|
27517
|
-
e.repo AS repo,
|
|
27518
|
-
e.file_path AS file,
|
|
27519
|
-
e.tool_name AS tool_name,
|
|
27520
|
-
f.audit_event_id AS event_id, e.root_session_id AS session_id,
|
|
27521
|
-
e.event_type AS kind, f.finding_key AS finding_key,
|
|
27522
|
-
${latestResolutionStatusSql("f")} AS latest_status
|
|
28752
|
+
const sql = `SELECT ${FINDING_ROW_COLUMNS_SQL}
|
|
27523
28753
|
FROM audit_events e
|
|
27524
28754
|
CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
|
|
27525
28755
|
CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
@@ -27533,6 +28763,26 @@ var SqliteFindingsRepository = class {
|
|
|
27533
28763
|
group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
|
|
27534
28764
|
const rows = this.db.prepare(
|
|
27535
28765
|
`SELECT rule_id,
|
|
28766
|
+
-- BARE columns beside max(latest_at), which is deliberate and
|
|
28767
|
+
-- is SQLite's documented behaviour: with a single min()/max()
|
|
28768
|
+
-- in an aggregate query, every bare column takes its value from
|
|
28769
|
+
-- the row that produced the extremum. So these are the severity
|
|
28770
|
+
-- and category of the definition whose finding is NEWEST, which
|
|
28771
|
+
-- is what the row-based build they replaced read off its first
|
|
28772
|
+
-- (newest-first) row.
|
|
28773
|
+
--
|
|
28774
|
+
-- min() is WRONG here and was the defect: inspection_definitions
|
|
28775
|
+
-- holds one row per rule VERSION (see its writer \u2014 a version bump
|
|
28776
|
+
-- mints a new row), so a rule whose severity moved between
|
|
28777
|
+
-- versions has several, and min() picks the ALPHABETICALLY
|
|
28778
|
+
-- smallest \u2014 'low' over 'medium', but 'critical' over 'high'.
|
|
28779
|
+
-- That is arbitrary in direction, and it feeds the badge, the
|
|
28780
|
+
-- filter, the facet counts and the primary sort key.
|
|
28781
|
+
--
|
|
28782
|
+
-- Adding a second min()/max() aggregate here would make these
|
|
28783
|
+
-- bare columns ambiguous again; keep max(latest_at) the only one.
|
|
28784
|
+
severity,
|
|
28785
|
+
category,
|
|
27536
28786
|
sum(tuple_count) AS instance_count,
|
|
27537
28787
|
max(latest_at) AS latest_at,
|
|
27538
28788
|
group_concat(source_tools) AS source_tools,
|
|
@@ -27543,6 +28793,14 @@ var SqliteFindingsRepository = class {
|
|
|
27543
28793
|
group_concat(tool_names) AS tool_names
|
|
27544
28794
|
FROM (
|
|
27545
28795
|
SELECT d.rule_id AS rule_id,
|
|
28796
|
+
-- Severity and category are columns of the DEFINITION, and
|
|
28797
|
+
-- a rule can have SEVERAL definitions (one per version), so
|
|
28798
|
+
-- these are grouped on below and resolved to the newest
|
|
28799
|
+
-- firing version by the outer query's bare-column select.
|
|
28800
|
+
-- They ride the aggregate because the type build has no rows
|
|
28801
|
+
-- to read them off \u2014 see buildFindingTypes.
|
|
28802
|
+
d.severity AS severity,
|
|
28803
|
+
d.category AS category,
|
|
27546
28804
|
e.event_type || '${TUPLE_SEP}' ||
|
|
27547
28805
|
(CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
|
|
27548
28806
|
coalesce(latest.status, '') AS status_tuple,
|
|
@@ -27557,7 +28815,7 @@ var SqliteFindingsRepository = class {
|
|
|
27557
28815
|
LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
|
|
27558
28816
|
ON latest.finding_key = f.finding_key
|
|
27559
28817
|
${scope.predicate}
|
|
27560
|
-
GROUP BY d.rule_id, status_tuple
|
|
28818
|
+
GROUP BY d.rule_id, d.severity, d.category, status_tuple
|
|
27561
28819
|
)
|
|
27562
28820
|
GROUP BY rule_id`
|
|
27563
28821
|
).all(scope.params);
|
|
@@ -27566,6 +28824,8 @@ var SqliteFindingsRepository = class {
|
|
|
27566
28824
|
r.rule_id,
|
|
27567
28825
|
{
|
|
27568
28826
|
instanceCount: r.instance_count,
|
|
28827
|
+
severity: r.severity,
|
|
28828
|
+
category: r.category,
|
|
27569
28829
|
sourceTools: splitConcat(r.source_tools),
|
|
27570
28830
|
actionsTaken: splitConcat(r.actions_taken),
|
|
27571
28831
|
statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
|
|
@@ -27582,7 +28842,7 @@ var SqliteFindingsRepository = class {
|
|
|
27582
28842
|
latestDetectedAt: epochMillisToIso(r.latest_at),
|
|
27583
28843
|
// Free text only — joined and substring-matched, so group_concat's
|
|
27584
28844
|
// commas need no unpicking (a repo/path containing one still matches).
|
|
27585
|
-
// Left undefined (not '') when unfetched, so
|
|
28845
|
+
// Left undefined (not '') when unfetched, so buildFindingTypes can
|
|
27586
28846
|
// tell "no q this request" from "a group with no repo/file at all"
|
|
27587
28847
|
// and skip priming a haystack nothing will read.
|
|
27588
28848
|
...withSearchText ? {
|
|
@@ -27610,7 +28870,9 @@ var SqliteFindingsRepository = class {
|
|
|
27610
28870
|
)
|
|
27611
28871
|
);
|
|
27612
28872
|
for (const row of grouped) {
|
|
27613
|
-
if (
|
|
28873
|
+
if (Object.hasOwn(byAction, row.action_taken)) {
|
|
28874
|
+
byAction[row.action_taken] = row.c;
|
|
28875
|
+
}
|
|
27614
28876
|
}
|
|
27615
28877
|
const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
|
|
27616
28878
|
const sevRows = allRows(
|
|
@@ -27627,7 +28889,9 @@ var SqliteFindingsRepository = class {
|
|
|
27627
28889
|
)
|
|
27628
28890
|
);
|
|
27629
28891
|
for (const row of sevRows) {
|
|
27630
|
-
if (
|
|
28892
|
+
if (Object.hasOwn(bySeverity, row.severity)) {
|
|
28893
|
+
bySeverity[row.severity] = row.c;
|
|
28894
|
+
}
|
|
27631
28895
|
}
|
|
27632
28896
|
const categories = ENFORCEABLE_CATEGORIES;
|
|
27633
28897
|
const enabledRows = allRows(
|
|
@@ -27676,469 +28940,6 @@ function isoDay(ms) {
|
|
|
27676
28940
|
return new Date(ms).toISOString().slice(0, 10);
|
|
27677
28941
|
}
|
|
27678
28942
|
|
|
27679
|
-
// ../../packages/persistence/src/repositories/history-sync.ts
|
|
27680
|
-
var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
|
|
27681
|
-
var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
27682
|
-
var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
|
|
27683
|
-
var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
27684
|
-
var SKIPPED = -1;
|
|
27685
|
-
var ROW_COLUMNS = `id,
|
|
27686
|
-
parent_id AS parentId,
|
|
27687
|
-
root_session_id AS rootSessionId,
|
|
27688
|
-
event_type AS eventType,
|
|
27689
|
-
host_id AS hostId,
|
|
27690
|
-
harness_id AS harnessId,
|
|
27691
|
-
source_project_id AS sourceProjectId,
|
|
27692
|
-
started_at AS startedAt,
|
|
27693
|
-
ended_at AS endedAt,
|
|
27694
|
-
severity,
|
|
27695
|
-
priority,
|
|
27696
|
-
content,
|
|
27697
|
-
content_hash AS contentHash,
|
|
27698
|
-
attributes`;
|
|
27699
|
-
var SqliteHistorySyncRepository = class {
|
|
27700
|
-
constructor(db) {
|
|
27701
|
-
this.db = db;
|
|
27702
|
-
this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
|
|
27703
|
-
this.sessionsStmt = db.prepare(
|
|
27704
|
-
`SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
|
|
27705
|
-
FROM audit_events
|
|
27706
|
-
WHERE synced_at IS NULL
|
|
27707
|
-
AND event_type IN (${TYPE_LIST})
|
|
27708
|
-
AND started_at < :before
|
|
27709
|
-
GROUP BY sessionId
|
|
27710
|
-
ORDER BY earliest
|
|
27711
|
-
LIMIT :limit`
|
|
27712
|
-
);
|
|
27713
|
-
this.rowsStmt = db.prepare(
|
|
27714
|
-
`SELECT ${ROW_COLUMNS}
|
|
27715
|
-
FROM audit_events
|
|
27716
|
-
WHERE synced_at IS NULL
|
|
27717
|
-
AND event_type IN (${TYPE_LIST})
|
|
27718
|
-
AND started_at < :before
|
|
27719
|
-
AND COALESCE(root_session_id, id) = :sessionId
|
|
27720
|
-
ORDER BY (event_type = 'session') DESC, started_at
|
|
27721
|
-
LIMIT :limit`
|
|
27722
|
-
);
|
|
27723
|
-
this.captureRowsStmt = db.prepare(
|
|
27724
|
-
`SELECT ${ROW_COLUMNS}
|
|
27725
|
-
FROM audit_events
|
|
27726
|
-
WHERE synced_at IS NULL
|
|
27727
|
-
AND sync_claimed_at IS NULL
|
|
27728
|
-
AND outbox_owed = 1
|
|
27729
|
-
AND event_type IN (${CAPTURE_TYPE_LIST})
|
|
27730
|
-
AND started_at < :before
|
|
27731
|
-
ORDER BY started_at
|
|
27732
|
-
LIMIT :limit`
|
|
27733
|
-
);
|
|
27734
|
-
this.markOwedStmt = db.prepare(
|
|
27735
|
-
`UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
|
|
27736
|
-
);
|
|
27737
|
-
this.stampStmt = db.prepare(
|
|
27738
|
-
`UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
|
|
27739
|
-
);
|
|
27740
|
-
this.claimRowStmt = db.prepare(
|
|
27741
|
-
`UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
|
|
27742
|
-
);
|
|
27743
|
-
this.releaseRowStmt = db.prepare(
|
|
27744
|
-
`UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
|
|
27745
|
-
);
|
|
27746
|
-
this.releaseStaleClaimsStmt = db.prepare(
|
|
27747
|
-
`UPDATE audit_events SET sync_claimed_at = NULL
|
|
27748
|
-
WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
|
|
27749
|
-
);
|
|
27750
|
-
this.partitionStmt = db.prepare(
|
|
27751
|
-
`SELECT
|
|
27752
|
-
SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
|
|
27753
|
-
SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
|
|
27754
|
-
SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
|
|
27755
|
-
SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
|
|
27756
|
-
COUNT(*) AS total
|
|
27757
|
-
FROM audit_events
|
|
27758
|
-
WHERE event_type IN (${TYPE_LIST})`
|
|
27759
|
-
);
|
|
27760
|
-
this.countsStmt = db.prepare(
|
|
27761
|
-
`SELECT
|
|
27762
|
-
SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
|
|
27763
|
-
SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
|
|
27764
|
-
SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
|
|
27765
|
-
FROM audit_events
|
|
27766
|
-
WHERE event_type IN (${TYPE_LIST})`
|
|
27767
|
-
);
|
|
27768
|
-
this.captureSkipCountStmt = db.prepare(
|
|
27769
|
-
`SELECT COUNT(*) AS skipped
|
|
27770
|
-
FROM audit_events
|
|
27771
|
-
WHERE synced_at = ${String(SKIPPED)}
|
|
27772
|
-
AND event_type IN (${CAPTURE_TYPE_LIST})`
|
|
27773
|
-
);
|
|
27774
|
-
this.fingerprintStmt = db.prepare(
|
|
27775
|
-
`SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
|
|
27776
|
-
FROM history_sync WHERE id = 1`
|
|
27777
|
-
);
|
|
27778
|
-
this.setFingerprintStmt = db.prepare(
|
|
27779
|
-
`UPDATE history_sync
|
|
27780
|
-
SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
|
|
27781
|
-
WHERE id = 1`
|
|
27782
|
-
);
|
|
27783
|
-
this.disownCapturesStmt = db.prepare(
|
|
27784
|
-
`UPDATE audit_events SET outbox_owed = NULL
|
|
27785
|
-
WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
|
|
27786
|
-
);
|
|
27787
|
-
this.rearmStmt = db.prepare(
|
|
27788
|
-
`UPDATE audit_events SET synced_at = NULL
|
|
27789
|
-
WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
|
|
27790
|
-
);
|
|
27791
|
-
this.claimStmt = db.prepare(
|
|
27792
|
-
`UPDATE history_sync
|
|
27793
|
-
SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
|
|
27794
|
-
WHERE id = 1
|
|
27795
|
-
AND (owner_pid IS NULL
|
|
27796
|
-
OR heartbeat_at IS NULL
|
|
27797
|
-
OR heartbeat_at < :staleBefore
|
|
27798
|
-
OR heartbeat_at > :now)`
|
|
27799
|
-
);
|
|
27800
|
-
this.heartbeatStmt = db.prepare(
|
|
27801
|
-
`UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
|
|
27802
|
-
);
|
|
27803
|
-
this.releaseStmt = db.prepare(
|
|
27804
|
-
`UPDATE history_sync
|
|
27805
|
-
SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
|
|
27806
|
-
WHERE id = 1 AND owner_pid = :pid`
|
|
27807
|
-
);
|
|
27808
|
-
this.closeWindowStmt = db.prepare(
|
|
27809
|
-
`UPDATE audit_events SET synced_at = :at
|
|
27810
|
-
WHERE synced_at IS NULL
|
|
27811
|
-
AND event_type IN (${TYPE_LIST})
|
|
27812
|
-
AND started_at >= :attachedAt`
|
|
27813
|
-
);
|
|
27814
|
-
this.releaseBoundaryStmt = db.prepare(
|
|
27815
|
-
`UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
|
|
27816
|
-
);
|
|
27817
|
-
this.freezeBoundaryStmt = db.prepare(
|
|
27818
|
-
`UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
|
|
27819
|
-
);
|
|
27820
|
-
this.leaseStmt = db.prepare(
|
|
27821
|
-
`SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
|
|
27822
|
-
acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
|
|
27823
|
-
FROM history_sync WHERE id = 1`
|
|
27824
|
-
);
|
|
27825
|
-
this.inspectionsStmt = db.prepare(
|
|
27826
|
-
`SELECT d.rule_id AS ruleId,
|
|
27827
|
-
d.name AS ruleName,
|
|
27828
|
-
d.version AS ruleVersion,
|
|
27829
|
-
d.category AS category,
|
|
27830
|
-
d.severity AS severity,
|
|
27831
|
-
f.span_start AS spanStart,
|
|
27832
|
-
f.span_end AS spanEnd,
|
|
27833
|
-
f.masked_match AS maskedMatch,
|
|
27834
|
-
f.action_taken AS actionTaken,
|
|
27835
|
-
f.confidence AS confidence
|
|
27836
|
-
FROM inspection_findings f
|
|
27837
|
-
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
27838
|
-
WHERE f.audit_event_id = :auditEventId
|
|
27839
|
-
ORDER BY f.span_start, f.id`
|
|
27840
|
-
);
|
|
27841
|
-
}
|
|
27842
|
-
db;
|
|
27843
|
-
ensureRowStmt;
|
|
27844
|
-
sessionsStmt;
|
|
27845
|
-
rowsStmt;
|
|
27846
|
-
stampStmt;
|
|
27847
|
-
countsStmt;
|
|
27848
|
-
fingerprintStmt;
|
|
27849
|
-
setFingerprintStmt;
|
|
27850
|
-
rearmStmt;
|
|
27851
|
-
claimStmt;
|
|
27852
|
-
heartbeatStmt;
|
|
27853
|
-
releaseStmt;
|
|
27854
|
-
leaseStmt;
|
|
27855
|
-
inspectionsStmt;
|
|
27856
|
-
closeWindowStmt;
|
|
27857
|
-
releaseBoundaryStmt;
|
|
27858
|
-
freezeBoundaryStmt;
|
|
27859
|
-
captureRowsStmt;
|
|
27860
|
-
markOwedStmt;
|
|
27861
|
-
captureSkipCountStmt;
|
|
27862
|
-
disownCapturesStmt;
|
|
27863
|
-
partitionStmt;
|
|
27864
|
-
claimRowStmt;
|
|
27865
|
-
releaseRowStmt;
|
|
27866
|
-
releaseStaleClaimsStmt;
|
|
27867
|
-
/**
|
|
27868
|
-
* The masked detections recorded against one tool call.
|
|
27869
|
-
*
|
|
27870
|
-
* These travel with the event because a tool call's target is not
|
|
27871
|
-
* re-inspectable from the event alone — unlike a capture, where the text
|
|
27872
|
-
* itself is re-scannable. What crosses is the masked match and the rule that
|
|
27873
|
-
* produced it, never the value.
|
|
27874
|
-
*/
|
|
27875
|
-
inspectionsFor(auditEventId) {
|
|
27876
|
-
return allRows(this.inspectionsStmt, { auditEventId });
|
|
27877
|
-
}
|
|
27878
|
-
/**
|
|
27879
|
-
* Sessions with structural rows still to send, oldest first.
|
|
27880
|
-
*
|
|
27881
|
-
* BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
|
|
27882
|
-
* read. Anything recorded after the machine attached is the live forward
|
|
27883
|
-
* path's to deliver; this drain exists for what was recorded before it, and a
|
|
27884
|
-
* row both paths send is at best a duplicate request and at worst — for a
|
|
27885
|
-
* session root — an overwrite of the inventory ids the live path resolved.
|
|
27886
|
-
*/
|
|
27887
|
-
pendingSessions(limit, before) {
|
|
27888
|
-
return allRows(this.sessionsStmt, { limit, before }).map(
|
|
27889
|
-
(r) => r.sessionId
|
|
27890
|
-
);
|
|
27891
|
-
}
|
|
27892
|
-
/** One session's undelivered structural rows within the backlog, root first. */
|
|
27893
|
-
pendingRows(sessionId, limit, before) {
|
|
27894
|
-
return allRows(this.rowsStmt, { sessionId, limit, before });
|
|
27895
|
-
}
|
|
27896
|
-
/**
|
|
27897
|
-
* Captures this machine still owes the deployment, oldest first.
|
|
27898
|
-
*
|
|
27899
|
-
* Selected by the `outbox_owed` marker the attached forward path writes, not
|
|
27900
|
-
* by a time window — see captureRowsStmt for why a window could not express
|
|
27901
|
-
* this. `before` is the grace window that leaves a just-recorded capture to
|
|
27902
|
-
* the live path.
|
|
27903
|
-
*/
|
|
27904
|
-
pendingCaptureRows(limit, before) {
|
|
27905
|
-
return allRows(this.captureRowsStmt, { limit, before });
|
|
27906
|
-
}
|
|
27907
|
-
/**
|
|
27908
|
-
* Record that a capture is OWED to the deployment.
|
|
27909
|
-
*
|
|
27910
|
-
* Written by the attached forward path when a live send did not confirm
|
|
27911
|
-
* delivery, and read by the drain as the whole of its eligibility test. It is
|
|
27912
|
-
* a fact rather than an inference: the machine was attached, the send did not
|
|
27913
|
-
* land, so the row is owed — which no time window can state, because the same
|
|
27914
|
-
* window that holds the rows a past attachment left owed also holds every
|
|
27915
|
-
* capture recorded while the machine was DETACHED, and those were never
|
|
27916
|
-
* offered to anyone.
|
|
27917
|
-
*
|
|
27918
|
-
* Idempotent, and never un-set: `markSynced` settling the row is what takes it
|
|
27919
|
-
* out of the drain's read.
|
|
27920
|
-
*/
|
|
27921
|
-
markCaptureOwed(id) {
|
|
27922
|
-
this.markOwedStmt.run({ id });
|
|
27923
|
-
}
|
|
27924
|
-
/** Record delivery. Called only AFTER the far side has accepted the rows. */
|
|
27925
|
-
markSynced(ids, atMs) {
|
|
27926
|
-
this.stampAll(ids, atMs);
|
|
27927
|
-
}
|
|
27928
|
-
/**
|
|
27929
|
-
* Record that a row will never be sent.
|
|
27930
|
-
*
|
|
27931
|
-
* Reserved for a local defect — a row that cannot be rebuilt into a valid
|
|
27932
|
-
* payload. A row that merely failed to reach the deployment stays NULL, so it
|
|
27933
|
-
* is retried; marking those would turn one outage into permanent data loss.
|
|
27934
|
-
*/
|
|
27935
|
-
markSkipped(ids) {
|
|
27936
|
-
this.stampAll(ids, SKIPPED);
|
|
27937
|
-
}
|
|
27938
|
-
eachInTransaction(ids, run) {
|
|
27939
|
-
if (ids.length === 0) return;
|
|
27940
|
-
withTransaction(
|
|
27941
|
-
this.db,
|
|
27942
|
-
() => {
|
|
27943
|
-
for (const id of ids) run(id);
|
|
27944
|
-
},
|
|
27945
|
-
"IMMEDIATE"
|
|
27946
|
-
);
|
|
27947
|
-
}
|
|
27948
|
-
stampAll(ids, value) {
|
|
27949
|
-
if (ids.length === 0) return;
|
|
27950
|
-
withTransaction(
|
|
27951
|
-
this.db,
|
|
27952
|
-
() => {
|
|
27953
|
-
for (const id of ids) this.stampStmt.run({ at: value, id });
|
|
27954
|
-
},
|
|
27955
|
-
"IMMEDIATE"
|
|
27956
|
-
);
|
|
27957
|
-
}
|
|
27958
|
-
/**
|
|
27959
|
-
* Claim rows as in-flight.
|
|
27960
|
-
*
|
|
27961
|
-
* Advisory in exactly the sense the lease is: it records that a send is in
|
|
27962
|
-
* progress so a surface can say so, and a lost claim costs a row showing as
|
|
27963
|
-
* queued while it is actually being sent. It is not exclusion — the far side
|
|
27964
|
-
* settles a duplicate on the row id.
|
|
27965
|
-
*/
|
|
27966
|
-
claimRows(ids, atMs) {
|
|
27967
|
-
this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
|
|
27968
|
-
}
|
|
27969
|
-
/** Give back a claim without settling — the send failed, the row is queued again. */
|
|
27970
|
-
releaseRows(ids) {
|
|
27971
|
-
this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
|
|
27972
|
-
}
|
|
27973
|
-
/**
|
|
27974
|
-
* Clear claims older than `staleBefore`, and report how many were cleared.
|
|
27975
|
-
*
|
|
27976
|
-
* A process killed between claiming and settling leaves rows claimed with
|
|
27977
|
-
* nothing left to settle them. Without this they read as "sending" for ever.
|
|
27978
|
-
*/
|
|
27979
|
-
releaseStaleClaims(staleBefore) {
|
|
27980
|
-
return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
|
|
27981
|
-
}
|
|
27982
|
-
/**
|
|
27983
|
-
* Every tracked row in exactly one delivery state.
|
|
27984
|
-
*
|
|
27985
|
-
* Takes no boundary on purpose. The boundary answers "what should the drain
|
|
27986
|
-
* pick up now", which is a different question from "what state is this row
|
|
27987
|
-
* in" — and a machine that has never attached has no boundary to pass, so
|
|
27988
|
-
* requiring one would force a caller to invent one and report the whole store
|
|
27989
|
-
* as queued.
|
|
27990
|
-
*/
|
|
27991
|
-
partition() {
|
|
27992
|
-
const row = getRow(this.partitionStmt, {});
|
|
27993
|
-
return {
|
|
27994
|
-
queued: row?.queued ?? 0,
|
|
27995
|
-
inProgress: row?.inProgress ?? 0,
|
|
27996
|
-
synced: row?.synced ?? 0,
|
|
27997
|
-
failed: row?.failed ?? 0,
|
|
27998
|
-
total: row?.total ?? 0
|
|
27999
|
-
};
|
|
28000
|
-
}
|
|
28001
|
-
/** `pending` counts only what is inside the backlog; sent and skipped are totals. */
|
|
28002
|
-
counts(before) {
|
|
28003
|
-
const row = getRow(
|
|
28004
|
-
this.countsStmt,
|
|
28005
|
-
{ before }
|
|
28006
|
-
);
|
|
28007
|
-
const captures = getRow(this.captureSkipCountStmt);
|
|
28008
|
-
return {
|
|
28009
|
-
pending: row?.pending ?? 0,
|
|
28010
|
-
sent: row?.sent ?? 0,
|
|
28011
|
-
skipped: row?.skipped ?? 0,
|
|
28012
|
-
capturesSkipped: captures?.skipped ?? 0
|
|
28013
|
-
};
|
|
28014
|
-
}
|
|
28015
|
-
/**
|
|
28016
|
-
* The deployment the current stamps were made against, and where its backlog
|
|
28017
|
-
* ends.
|
|
28018
|
-
*
|
|
28019
|
-
* READ-ONLY. An absent row reads as an absent deployment, which is what a
|
|
28020
|
-
* machine that has never drained is — and every writer below seeds the row
|
|
28021
|
-
* before it needs one, so nothing depends on this creating it. Keeping the
|
|
28022
|
-
* write off the gate path matters because the gate runs on every pass while a
|
|
28023
|
-
* write has to take the database's write lock.
|
|
28024
|
-
*/
|
|
28025
|
-
deployment() {
|
|
28026
|
-
const row = getRow(
|
|
28027
|
-
this.fingerprintStmt
|
|
28028
|
-
);
|
|
28029
|
-
return {
|
|
28030
|
-
fingerprint: row?.fingerprint ?? void 0,
|
|
28031
|
-
backlogBefore: row?.backlogBefore ?? void 0
|
|
28032
|
-
};
|
|
28033
|
-
}
|
|
28034
|
-
/**
|
|
28035
|
-
* Point the ledger at a different deployment, discarding what it recorded
|
|
28036
|
-
* about the previous one.
|
|
28037
|
-
*
|
|
28038
|
-
* Delivery is a fact about ONE recipient: rows sent to the deployment a
|
|
28039
|
-
* machine has just left are undelivered as far as the new one is concerned.
|
|
28040
|
-
* All three in one transaction, so a crash between them cannot leave stamps
|
|
28041
|
-
* attributed to the wrong deployment, or a boundary that belongs to another.
|
|
28042
|
-
*
|
|
28043
|
-
* The boundary is written HERE and only here, which is what freezes it: a
|
|
28044
|
-
* re-attach to the SAME deployment (a key rotation) leaves the fingerprint
|
|
28045
|
-
* unchanged, so this never runs and the backlog does not widen back over rows
|
|
28046
|
-
* the live path has since delivered.
|
|
28047
|
-
*/
|
|
28048
|
-
rearmFor(fingerprint, backlogBefore) {
|
|
28049
|
-
this.ensureRowStmt.run();
|
|
28050
|
-
withTransaction(
|
|
28051
|
-
this.db,
|
|
28052
|
-
() => {
|
|
28053
|
-
const previous = getRow(this.fingerprintStmt)?.fingerprint;
|
|
28054
|
-
this.rearmStmt.run();
|
|
28055
|
-
if (previous !== null && previous !== void 0 && previous !== fingerprint) {
|
|
28056
|
-
this.disownCapturesStmt.run();
|
|
28057
|
-
}
|
|
28058
|
-
this.setFingerprintStmt.run({ fingerprint, backlogBefore });
|
|
28059
|
-
},
|
|
28060
|
-
"IMMEDIATE"
|
|
28061
|
-
);
|
|
28062
|
-
}
|
|
28063
|
-
/**
|
|
28064
|
-
* End the attached period: hand its rows to the live path, and release the
|
|
28065
|
-
* boundary so the next attachment can freeze a new one.
|
|
28066
|
-
*
|
|
28067
|
-
* WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
|
|
28068
|
-
* nothing delivers. The fingerprint is unchanged, so the boundary is never
|
|
28069
|
-
* re-frozen and stays at the FIRST attachment — while nothing forwards at all
|
|
28070
|
-
* during the detached period, because the machine is not attached. Rows
|
|
28071
|
-
* recorded in that window sit after the boundary and before the re-attach, so
|
|
28072
|
-
* neither path takes them, and the pending count reports none outstanding.
|
|
28073
|
-
*
|
|
28074
|
-
* Stamping the attached window is not a claim that every one of those rows
|
|
28075
|
-
* reached the deployment — the live path drops on failure and says so
|
|
28076
|
-
* elsewhere. It records that they were ITS to deliver, which is exactly the
|
|
28077
|
-
* status quo: they sit outside the frozen boundary today and are equally never
|
|
28078
|
-
* re-sent. Making it explicit is what lets the boundary move.
|
|
28079
|
-
*
|
|
28080
|
-
* ONE TRANSACTION, so a crash cannot release the boundary while leaving the
|
|
28081
|
-
* window unstamped — that half-state would re-send the whole attached period
|
|
28082
|
-
* on the next attach, which is the failure the boundary exists to prevent.
|
|
28083
|
-
*/
|
|
28084
|
-
closeAttachedWindow(attachedAtMs, atMs) {
|
|
28085
|
-
this.ensureRowStmt.run();
|
|
28086
|
-
withTransaction(
|
|
28087
|
-
this.db,
|
|
28088
|
-
() => {
|
|
28089
|
-
const row = getRow(this.fingerprintStmt);
|
|
28090
|
-
const from = row?.backlogBefore ?? attachedAtMs;
|
|
28091
|
-
this.closeWindowStmt.run({ at: atMs, attachedAt: from });
|
|
28092
|
-
this.releaseBoundaryStmt.run();
|
|
28093
|
-
},
|
|
28094
|
-
"IMMEDIATE"
|
|
28095
|
-
);
|
|
28096
|
-
}
|
|
28097
|
-
/**
|
|
28098
|
-
* Freeze a boundary for the deployment already on file, KEEPING the stamps.
|
|
28099
|
-
*
|
|
28100
|
-
* The re-attach half of the above. Distinct from `rearmFor`, which is for a
|
|
28101
|
-
* different deployment and therefore discards what was delivered to the old
|
|
28102
|
-
* one: here the recipient is the same, so everything already sent to it stays
|
|
28103
|
-
* sent.
|
|
28104
|
-
*/
|
|
28105
|
-
freezeBoundary(backlogBefore) {
|
|
28106
|
-
this.ensureRowStmt.run();
|
|
28107
|
-
this.freezeBoundaryStmt.run({ backlogBefore });
|
|
28108
|
-
}
|
|
28109
|
-
/** Take the claim, or report that someone live already holds it. */
|
|
28110
|
-
claim(pid, host, nowMs, staleAfterMs) {
|
|
28111
|
-
this.ensureRowStmt.run();
|
|
28112
|
-
let taken = false;
|
|
28113
|
-
withTransaction(
|
|
28114
|
-
this.db,
|
|
28115
|
-
() => {
|
|
28116
|
-
const result = this.claimStmt.run({
|
|
28117
|
-
pid,
|
|
28118
|
-
host,
|
|
28119
|
-
now: nowMs,
|
|
28120
|
-
staleBefore: nowMs - staleAfterMs
|
|
28121
|
-
});
|
|
28122
|
-
taken = result.changes === 1;
|
|
28123
|
-
},
|
|
28124
|
-
"IMMEDIATE"
|
|
28125
|
-
);
|
|
28126
|
-
return taken;
|
|
28127
|
-
}
|
|
28128
|
-
/** Say the holder is still alive. A no-op once the claim has moved on. */
|
|
28129
|
-
heartbeat(pid, nowMs) {
|
|
28130
|
-
this.heartbeatStmt.run({ now: nowMs, pid });
|
|
28131
|
-
}
|
|
28132
|
-
/** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
|
|
28133
|
-
release(pid) {
|
|
28134
|
-
this.releaseStmt.run({ pid });
|
|
28135
|
-
}
|
|
28136
|
-
/** Who holds the claim, if anyone. Read-only, for the same reason as above. */
|
|
28137
|
-
lease() {
|
|
28138
|
-
return getRow(this.leaseStmt);
|
|
28139
|
-
}
|
|
28140
|
-
};
|
|
28141
|
-
|
|
28142
28943
|
// ../../packages/persistence/src/repositories/inspection-definitions.ts
|
|
28143
28944
|
var SqliteInspectionDefinitionsRepository = class {
|
|
28144
28945
|
constructor(db) {
|
|
@@ -28330,7 +29131,8 @@ function managedSettingsPaths(platform2 = process.platform) {
|
|
|
28330
29131
|
}
|
|
28331
29132
|
return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
|
|
28332
29133
|
}
|
|
28333
|
-
|
|
29134
|
+
var testOnlyManagedPaths = null;
|
|
29135
|
+
function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPaths()) {
|
|
28334
29136
|
for (const path of paths) {
|
|
28335
29137
|
let text;
|
|
28336
29138
|
try {
|
|
@@ -28365,6 +29167,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
|
|
|
28365
29167
|
if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
|
|
28366
29168
|
if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
|
|
28367
29169
|
if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
|
|
29170
|
+
if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
|
|
28368
29171
|
if (values.vaultConsent !== void 0) {
|
|
28369
29172
|
merged.vaultConsent = values.vaultConsent ? (
|
|
28370
29173
|
// Keep an existing valid grant so its acknowledgedAt survives; mint one
|
|
@@ -30810,7 +31613,7 @@ function toUtcDateString(ms) {
|
|
|
30810
31613
|
return new Date(ms).toISOString().slice(0, 10);
|
|
30811
31614
|
}
|
|
30812
31615
|
function isTimeseriesSeverity(s) {
|
|
30813
|
-
return s === "critical" || s === "high" || s === "medium";
|
|
31616
|
+
return s === "critical" || s === "high" || s === "medium" || s === "low";
|
|
30814
31617
|
}
|
|
30815
31618
|
var SqliteSecurityRepository = class {
|
|
30816
31619
|
constructor(db, now = () => Date.now()) {
|
|
@@ -30872,7 +31675,7 @@ var SqliteSecurityRepository = class {
|
|
|
30872
31675
|
ELSE 0
|
|
30873
31676
|
END) AS open_at_rest
|
|
30874
31677
|
FROM inspection_findings f
|
|
30875
|
-
JOIN audit_events e ON e.id = f.audit_event_id
|
|
31678
|
+
JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
|
|
30876
31679
|
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
30877
31680
|
LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
|
|
30878
31681
|
ON latest.finding_key = f.finding_key
|
|
@@ -30939,12 +31742,16 @@ var SqliteSecurityRepository = class {
|
|
|
30939
31742
|
const now = this.now();
|
|
30940
31743
|
const windowStart = startOfUtcDay2(now) - (lenDays - 1) * DAY_MS4;
|
|
30941
31744
|
const rows = this.findingsInRange(windowStart, now);
|
|
30942
|
-
const points = Array.from(
|
|
30943
|
-
|
|
30944
|
-
|
|
30945
|
-
|
|
30946
|
-
|
|
30947
|
-
|
|
31745
|
+
const points = Array.from(
|
|
31746
|
+
{ length: numBuckets },
|
|
31747
|
+
(_, i) => ({
|
|
31748
|
+
timestamp: toUtcDateString(windowStart + i * bucketMs),
|
|
31749
|
+
critical: 0,
|
|
31750
|
+
high: 0,
|
|
31751
|
+
medium: 0,
|
|
31752
|
+
low: 0
|
|
31753
|
+
})
|
|
31754
|
+
);
|
|
30948
31755
|
for (const r of rows) {
|
|
30949
31756
|
const idx = Math.floor((r.occurredAt - windowStart) / bucketMs);
|
|
30950
31757
|
const bucket = points[idx];
|
|
@@ -31094,7 +31901,7 @@ var SqliteSecurityRepository = class {
|
|
|
31094
31901
|
this.db.prepare(
|
|
31095
31902
|
`SELECT e.repo AS repo, count(*) AS c
|
|
31096
31903
|
FROM inspection_findings f
|
|
31097
|
-
JOIN audit_events e ON e.id = f.audit_event_id
|
|
31904
|
+
JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
|
|
31098
31905
|
WHERE e.started_at >= :from AND e.started_at < :to
|
|
31099
31906
|
AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
|
|
31100
31907
|
AND e.repo IS NOT NULL
|
|
@@ -31162,6 +31969,7 @@ var SqliteSecurityRepository = class {
|
|
|
31162
31969
|
`SELECT f.finding_key AS finding_key,
|
|
31163
31970
|
d.rule_id AS rule_id,
|
|
31164
31971
|
d.severity AS severity,
|
|
31972
|
+
e.repo AS repo,
|
|
31165
31973
|
e.file_path AS path,
|
|
31166
31974
|
COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
|
|
31167
31975
|
latest.resolved_at AS latest_resolved_at
|
|
@@ -31181,6 +31989,7 @@ var SqliteSecurityRepository = class {
|
|
|
31181
31989
|
const items = rows.map((r) => ({
|
|
31182
31990
|
findingKey: r.finding_key,
|
|
31183
31991
|
ruleId: r.rule_id,
|
|
31992
|
+
repo: r.repo ?? "",
|
|
31184
31993
|
severity: r.severity,
|
|
31185
31994
|
path: r.path ?? "",
|
|
31186
31995
|
resolvedAt: new Date(r.latest_resolved_at).toISOString(),
|
|
@@ -31190,15 +31999,68 @@ var SqliteSecurityRepository = class {
|
|
|
31190
31999
|
}));
|
|
31191
32000
|
return Promise.resolve({ items });
|
|
31192
32001
|
}
|
|
32002
|
+
/**
|
|
32003
|
+
* Per-rule tallies of the findings that are still OPEN, whole-store.
|
|
32004
|
+
*
|
|
32005
|
+
* Scoped by status rather than by time, because the card this feeds is a to-do
|
|
32006
|
+
* list: a secret committed three weeks ago and never rotated is still the most
|
|
32007
|
+
* important thing to fix, and any window hides it. It carried a "newest N
|
|
32008
|
+
* findings" cap and then a range; the first meant a different span on every
|
|
32009
|
+
* machine, and the second reported "no recommendations" over live exposure.
|
|
32010
|
+
*
|
|
32011
|
+
* `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
|
|
32012
|
+
* so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
|
|
32013
|
+
* is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
|
|
32014
|
+
* dismissal is a judgement, not a remediation) and drops untracked legacy rows.
|
|
32015
|
+
* The two answer different questions and only this one has to match a link.
|
|
32016
|
+
*
|
|
32017
|
+
* Aggregated in SQL: the result is O(distinct rule × category × severity), so a
|
|
32018
|
+
* whole-store scope costs a grouped scan rather than a row per finding.
|
|
32019
|
+
*/
|
|
32020
|
+
recommendationInputs() {
|
|
32021
|
+
const rows = allRows(
|
|
32022
|
+
this.db.prepare(
|
|
32023
|
+
`SELECT d.rule_id AS rule_id,
|
|
32024
|
+
d.category AS category,
|
|
32025
|
+
d.severity AS severity,
|
|
32026
|
+
COUNT(*) AS count
|
|
32027
|
+
FROM inspection_findings f
|
|
32028
|
+
JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
|
|
32029
|
+
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
32030
|
+
LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
|
|
32031
|
+
ON latest.finding_key = f.finding_key
|
|
32032
|
+
WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
|
|
32033
|
+
AND e.event_type = 'code_change'
|
|
32034
|
+
AND (
|
|
32035
|
+
f.finding_key IS NULL
|
|
32036
|
+
OR latest.status IS NULL
|
|
32037
|
+
OR latest.status NOT IN ('resolved', 'dismissed')
|
|
32038
|
+
)
|
|
32039
|
+
GROUP BY d.rule_id, d.category, d.severity`
|
|
32040
|
+
)
|
|
32041
|
+
);
|
|
32042
|
+
return Promise.resolve(
|
|
32043
|
+
rows.map((r) => ({
|
|
32044
|
+
ruleId: r.rule_id,
|
|
32045
|
+
category: r.category,
|
|
32046
|
+
severity: r.severity,
|
|
32047
|
+
count: r.count
|
|
32048
|
+
}))
|
|
32049
|
+
);
|
|
32050
|
+
}
|
|
31193
32051
|
// Findings whose parent event occurred in [fromMs, toMs), with the parent's
|
|
31194
32052
|
// epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
|
|
31195
32053
|
// numeric and the JS aggregations bucket/split on ms directly.
|
|
31196
32054
|
findingsInRange(fromMs, toMs) {
|
|
31197
32055
|
const rows = allRows(
|
|
31198
32056
|
this.db.prepare(
|
|
31199
|
-
`
|
|
32057
|
+
// `rule_id`/`category` cost nothing extra: inspection_definitions is already
|
|
32058
|
+
// joined for `severity`, so they are two more columns off a row this read
|
|
32059
|
+
// already fetches. They feed the recommended-actions rollup.
|
|
32060
|
+
`SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
|
|
32061
|
+
d.rule_id AS rule_id, d.category AS category
|
|
31200
32062
|
FROM inspection_findings f
|
|
31201
|
-
JOIN audit_events e ON e.id = f.audit_event_id
|
|
32063
|
+
JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
|
|
31202
32064
|
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
31203
32065
|
WHERE e.started_at >= :from AND e.started_at < :to
|
|
31204
32066
|
AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
|
|
@@ -31209,7 +32071,9 @@ var SqliteSecurityRepository = class {
|
|
|
31209
32071
|
return rows.map((r) => ({
|
|
31210
32072
|
occurredAt: r.occurred_at,
|
|
31211
32073
|
severity: r.severity,
|
|
31212
|
-
actionTaken: r.action_taken
|
|
32074
|
+
actionTaken: r.action_taken,
|
|
32075
|
+
ruleId: r.rule_id,
|
|
32076
|
+
category: r.category
|
|
31213
32077
|
}));
|
|
31214
32078
|
}
|
|
31215
32079
|
};
|
|
@@ -32037,6 +32901,7 @@ function openWithPragmas(file2) {
|
|
|
32037
32901
|
db.exec("PRAGMA journal_mode = WAL");
|
|
32038
32902
|
db.exec("PRAGMA busy_timeout = 2000");
|
|
32039
32903
|
db.exec("PRAGMA foreign_keys = ON");
|
|
32904
|
+
registerSqlFunctions(db);
|
|
32040
32905
|
} catch (err) {
|
|
32041
32906
|
closeQuietly(db);
|
|
32042
32907
|
throw err;
|
|
@@ -32066,7 +32931,7 @@ function backupLegacyStore(db, file2) {
|
|
|
32066
32931
|
discardStore(file2, backup);
|
|
32067
32932
|
return backup;
|
|
32068
32933
|
}
|
|
32069
|
-
function openAndInitialize(file2, base) {
|
|
32934
|
+
function openAndInitialize(file2, base, skipTags) {
|
|
32070
32935
|
let db = openWithPragmas(file2);
|
|
32071
32936
|
try {
|
|
32072
32937
|
if (isForeignSqliteLineage(db)) {
|
|
@@ -32076,7 +32941,7 @@ function openAndInitialize(file2, base) {
|
|
|
32076
32941
|
`Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
|
|
32077
32942
|
);
|
|
32078
32943
|
}
|
|
32079
|
-
applyMigrations(db, file2);
|
|
32944
|
+
applyMigrations(db, file2, { skipTags });
|
|
32080
32945
|
tightenPerms(file2);
|
|
32081
32946
|
const policies = new SqlitePoliciesRepository(db);
|
|
32082
32947
|
const installedPacks = new SqliteInstalledPacksRepository(db, base);
|
|
@@ -32091,6 +32956,7 @@ function openAndInitialize(file2, base) {
|
|
|
32091
32956
|
exceptions: new SqliteExceptionsRepository(db),
|
|
32092
32957
|
resolutions: new SqliteResolutionsRepository(db),
|
|
32093
32958
|
ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
|
|
32959
|
+
bodyRetention: new SqliteBodyRetentionRepository(db),
|
|
32094
32960
|
security: new SqliteSecurityRepository(db),
|
|
32095
32961
|
detections: new SqliteDetectionsRepository(db),
|
|
32096
32962
|
shares: new SqliteSharesRepository(db),
|
|
@@ -32113,7 +32979,8 @@ function openAndInitialize(file2, base) {
|
|
|
32113
32979
|
throw err;
|
|
32114
32980
|
}
|
|
32115
32981
|
}
|
|
32116
|
-
|
|
32982
|
+
var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
|
|
32983
|
+
function openLocalDatabase(dir, options = {}) {
|
|
32117
32984
|
ensureDataDirSync(dir);
|
|
32118
32985
|
const file2 = join7(dir, DB_FILENAME);
|
|
32119
32986
|
reapStalePartials(file2);
|
|
@@ -32125,6 +32992,7 @@ function openLocalDatabase(dir) {
|
|
|
32125
32992
|
installedPacks,
|
|
32126
32993
|
scanLedger,
|
|
32127
32994
|
historySync,
|
|
32995
|
+
bodyRetention,
|
|
32128
32996
|
secretVault,
|
|
32129
32997
|
exceptions,
|
|
32130
32998
|
resolutions,
|
|
@@ -32148,7 +33016,8 @@ function openLocalDatabase(dir) {
|
|
|
32148
33016
|
// `dir` is always `<base>/data` — every caller resolves it through
|
|
32149
33017
|
// `dataDir()` — so its parent is the `~/.aka` base the layout splits into
|
|
32150
33018
|
// settings/ and data/, and the pack-policy floor needs both halves.
|
|
32151
|
-
dirname2(dir)
|
|
33019
|
+
dirname2(dir),
|
|
33020
|
+
options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
|
|
32152
33021
|
);
|
|
32153
33022
|
function captureRowId(event) {
|
|
32154
33023
|
return captureId(
|
|
@@ -32341,6 +33210,7 @@ function openLocalDatabase(dir) {
|
|
|
32341
33210
|
installedPacks,
|
|
32342
33211
|
scanLedger,
|
|
32343
33212
|
historySync,
|
|
33213
|
+
bodyRetention,
|
|
32344
33214
|
secretVault,
|
|
32345
33215
|
exceptions,
|
|
32346
33216
|
resolutions,
|
|
@@ -32379,8 +33249,72 @@ function openLocalDatabase(dir) {
|
|
|
32379
33249
|
};
|
|
32380
33250
|
}
|
|
32381
33251
|
|
|
32382
|
-
// ../../packages/persistence/src/
|
|
33252
|
+
// ../../packages/persistence/src/egress-wire.ts
|
|
32383
33253
|
import { createHash as createHash3 } from "crypto";
|
|
33254
|
+
var PROJECT_KEY_DIGEST_VERSION = "v2";
|
|
33255
|
+
var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
|
|
33256
|
+
var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
|
|
33257
|
+
var FILE_URL = /^file:\/\//i;
|
|
33258
|
+
var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
|
|
33259
|
+
var SLASH = "/".charCodeAt(0);
|
|
33260
|
+
var GIT_SUFFIX = ".git";
|
|
33261
|
+
function trimSlashes(path) {
|
|
33262
|
+
let start = 0;
|
|
33263
|
+
let end = path.length;
|
|
33264
|
+
while (start < end && path.charCodeAt(start) === SLASH) start += 1;
|
|
33265
|
+
while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
|
|
33266
|
+
return path.slice(start, end);
|
|
33267
|
+
}
|
|
33268
|
+
function canonicalGitUrl(url2) {
|
|
33269
|
+
const trimmed = url2.trim();
|
|
33270
|
+
if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
|
|
33271
|
+
const scheme = SCHEME_FORM.exec(trimmed);
|
|
33272
|
+
const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
|
|
33273
|
+
const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
|
|
33274
|
+
if (host === void 0) return trimmed;
|
|
33275
|
+
const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
|
|
33276
|
+
const bare = trimSlashes(path);
|
|
33277
|
+
const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
|
|
33278
|
+
return cleaned === "" ? host : `${host}/${cleaned}`;
|
|
33279
|
+
}
|
|
33280
|
+
function hashProjectKey(projectKey) {
|
|
33281
|
+
const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
|
|
33282
|
+
return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
|
|
33283
|
+
}
|
|
33284
|
+
function toIngestHit(hit) {
|
|
33285
|
+
return {
|
|
33286
|
+
host: hit.host,
|
|
33287
|
+
kind: hit.kind,
|
|
33288
|
+
name: hit.name,
|
|
33289
|
+
category: hit.category,
|
|
33290
|
+
trust: hit.trust,
|
|
33291
|
+
network: hit.network,
|
|
33292
|
+
method: hit.method,
|
|
33293
|
+
transport: hit.transport,
|
|
33294
|
+
url: hit.url,
|
|
33295
|
+
template: hit.template,
|
|
33296
|
+
dataClass: hit.dataClass,
|
|
33297
|
+
site: {
|
|
33298
|
+
file: hit.site.file,
|
|
33299
|
+
line: hit.site.line,
|
|
33300
|
+
dynamic: hit.site.dynamic,
|
|
33301
|
+
vendored: hit.site.vendored
|
|
33302
|
+
}
|
|
33303
|
+
};
|
|
33304
|
+
}
|
|
33305
|
+
function toEgressIngestRequest(input2) {
|
|
33306
|
+
const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
|
|
33307
|
+
const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
|
|
33308
|
+
return {
|
|
33309
|
+
projectKey: hashProjectKey(input2.projectKey),
|
|
33310
|
+
project: input2.project,
|
|
33311
|
+
reconcile,
|
|
33312
|
+
hits: hits.map(toIngestHit)
|
|
33313
|
+
};
|
|
33314
|
+
}
|
|
33315
|
+
|
|
33316
|
+
// ../../packages/persistence/src/finding-key.ts
|
|
33317
|
+
import { createHash as createHash4 } from "crypto";
|
|
32384
33318
|
|
|
32385
33319
|
// ../../packages/persistence/src/fingerprint.ts
|
|
32386
33320
|
import { createHmac, randomBytes } from "crypto";
|
|
@@ -32421,14 +33355,50 @@ function readFingerprintKey(dataDir2) {
|
|
|
32421
33355
|
return parseKeyFile(raw);
|
|
32422
33356
|
}
|
|
32423
33357
|
|
|
32424
|
-
// ../../packages/persistence/src/
|
|
32425
|
-
import {
|
|
33358
|
+
// ../../packages/persistence/src/forward-health.ts
|
|
33359
|
+
import { readFileSync as readFileSync7 } from "fs";
|
|
32426
33360
|
import { join as join9 } from "path";
|
|
33361
|
+
var FAILURES = /* @__PURE__ */ new Set([
|
|
33362
|
+
"unauthorized",
|
|
33363
|
+
"forbidden",
|
|
33364
|
+
"unreachable"
|
|
33365
|
+
]);
|
|
33366
|
+
var BREAKER_COOLDOWN_MS = 3e4;
|
|
33367
|
+
function parseForwardHealth(raw, nowMs) {
|
|
33368
|
+
try {
|
|
33369
|
+
const parsed2 = JSON.parse(raw);
|
|
33370
|
+
if (typeof parsed2 !== "object" || parsed2 === null) return null;
|
|
33371
|
+
const record2 = parsed2;
|
|
33372
|
+
const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
|
|
33373
|
+
const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
|
|
33374
|
+
const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
|
|
33375
|
+
return { consecutiveFailures: failures, openedAtMs, lastFailure };
|
|
33376
|
+
} catch {
|
|
33377
|
+
return null;
|
|
33378
|
+
}
|
|
33379
|
+
}
|
|
33380
|
+
function isForwardPaused(health, nowMs) {
|
|
33381
|
+
const openedAtMs = health?.openedAtMs ?? null;
|
|
33382
|
+
if (openedAtMs === null) return false;
|
|
33383
|
+
return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
|
|
33384
|
+
}
|
|
33385
|
+
|
|
33386
|
+
// ../../packages/persistence/src/history-backfill.ts
|
|
33387
|
+
import { existsSync as existsSync4 } from "fs";
|
|
33388
|
+
import { join as join10 } from "path";
|
|
33389
|
+
|
|
33390
|
+
// ../../packages/persistence/src/history-preview.ts
|
|
33391
|
+
import { existsSync as existsSync5 } from "fs";
|
|
33392
|
+
import { join as join11 } from "path";
|
|
32427
33393
|
import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
|
|
32428
33394
|
|
|
33395
|
+
// ../../packages/persistence/src/history-sync-state.ts
|
|
33396
|
+
import { readFileSync as readFileSync8 } from "fs";
|
|
33397
|
+
import { join as join12 } from "path";
|
|
33398
|
+
|
|
32429
33399
|
// ../../packages/persistence/src/store-symlinks.ts
|
|
32430
|
-
import { existsSync as
|
|
32431
|
-
import { dirname as dirname3, join as
|
|
33400
|
+
import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
|
|
33401
|
+
import { dirname as dirname3, join as join13, resolve } from "path";
|
|
32432
33402
|
|
|
32433
33403
|
// ../../packages/persistence/src/vault/crypto.ts
|
|
32434
33404
|
import {
|
|
@@ -32442,63 +33412,26 @@ import {
|
|
|
32442
33412
|
// ../../packages/persistence/src/vault/key-provider.ts
|
|
32443
33413
|
import { execFileSync } from "child_process";
|
|
32444
33414
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
32445
|
-
import { chmodSync as chmodSync3, readFileSync as
|
|
32446
|
-
import { join as
|
|
33415
|
+
import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
|
|
33416
|
+
import { join as join14 } from "path";
|
|
32447
33417
|
|
|
32448
33418
|
// ../../packages/persistence/src/vault/vault.ts
|
|
32449
33419
|
import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
|
|
32450
33420
|
|
|
32451
33421
|
// ../../packages/persistence/src/warn-era-cap.ts
|
|
32452
|
-
import { existsSync as
|
|
32453
|
-
import { join as
|
|
33422
|
+
import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
|
|
33423
|
+
import { join as join15 } from "path";
|
|
32454
33424
|
var MARKER = "warn-era-capped";
|
|
32455
33425
|
function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
|
|
32456
33426
|
if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
|
|
32457
|
-
const marker =
|
|
32458
|
-
if (
|
|
33427
|
+
const marker = join15(dataDir2, MARKER);
|
|
33428
|
+
if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
|
|
32459
33429
|
const capped = db.policies.capCategoryActions();
|
|
32460
33430
|
writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
|
|
32461
33431
|
`, { mode: DATA_FILE_MODE });
|
|
32462
33432
|
return { capped };
|
|
32463
33433
|
}
|
|
32464
33434
|
|
|
32465
|
-
// ../../packages/plugin-runtime/src/attached/egress-wire.ts
|
|
32466
|
-
import { createHash as createHash4 } from "crypto";
|
|
32467
|
-
function hashProjectKey(projectKey) {
|
|
32468
|
-
return createHash4("sha256").update(projectKey, "utf8").digest("hex");
|
|
32469
|
-
}
|
|
32470
|
-
function toIngestHit(hit) {
|
|
32471
|
-
return {
|
|
32472
|
-
host: hit.host,
|
|
32473
|
-
kind: hit.kind,
|
|
32474
|
-
name: hit.name,
|
|
32475
|
-
category: hit.category,
|
|
32476
|
-
trust: hit.trust,
|
|
32477
|
-
network: hit.network,
|
|
32478
|
-
method: hit.method,
|
|
32479
|
-
transport: hit.transport,
|
|
32480
|
-
url: hit.url,
|
|
32481
|
-
template: hit.template,
|
|
32482
|
-
dataClass: hit.dataClass,
|
|
32483
|
-
site: {
|
|
32484
|
-
file: hit.site.file,
|
|
32485
|
-
line: hit.site.line,
|
|
32486
|
-
dynamic: hit.site.dynamic,
|
|
32487
|
-
vendored: hit.site.vendored
|
|
32488
|
-
}
|
|
32489
|
-
};
|
|
32490
|
-
}
|
|
32491
|
-
function toEgressIngestRequest(input2) {
|
|
32492
|
-
const { hits, droppedFiles } = capHits(input2.hits, input2.reconcile.mode);
|
|
32493
|
-
const reconcile = withoutDroppedFiles(input2.reconcile, droppedFiles);
|
|
32494
|
-
return {
|
|
32495
|
-
projectKey: hashProjectKey(input2.projectKey),
|
|
32496
|
-
project: input2.project,
|
|
32497
|
-
reconcile,
|
|
32498
|
-
hits: hits.map(toIngestHit)
|
|
32499
|
-
};
|
|
32500
|
-
}
|
|
32501
|
-
|
|
32502
33435
|
// ../../packages/remote/src/http.ts
|
|
32503
33436
|
import { request as httpRequest } from "http";
|
|
32504
33437
|
import { request as httpsRequest } from "https";
|
|
@@ -32682,10 +33615,10 @@ function parsed(schema, body, route) {
|
|
|
32682
33615
|
}
|
|
32683
33616
|
function withoutTrailingSlashes(endpoint) {
|
|
32684
33617
|
let end = endpoint.length;
|
|
32685
|
-
while (end > 0 && endpoint.charCodeAt(end - 1) ===
|
|
33618
|
+
while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
|
|
32686
33619
|
return endpoint.slice(0, end);
|
|
32687
33620
|
}
|
|
32688
|
-
var
|
|
33621
|
+
var SLASH2 = "/".charCodeAt(0);
|
|
32689
33622
|
function createRemoteClient(options) {
|
|
32690
33623
|
const base = withoutTrailingSlashes(options.endpoint);
|
|
32691
33624
|
const url2 = (route) => `${base}${route}`;
|
|
@@ -32778,6 +33711,7 @@ function createRemoteClient(options) {
|
|
|
32778
33711
|
url: url2(ROUTES.shares),
|
|
32779
33712
|
body: JSON.stringify(validated.data)
|
|
32780
33713
|
});
|
|
33714
|
+
if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
|
|
32781
33715
|
okBody(response);
|
|
32782
33716
|
},
|
|
32783
33717
|
async pollCommand() {
|
|
@@ -32800,19 +33734,51 @@ function createRemoteClient(options) {
|
|
|
32800
33734
|
};
|
|
32801
33735
|
}
|
|
32802
33736
|
|
|
32803
|
-
// ../../packages/
|
|
33737
|
+
// ../../packages/remote/src/failure-kind.ts
|
|
32804
33738
|
function statusOf(err) {
|
|
32805
33739
|
if (typeof err !== "object" || err === null || !("status" in err)) return null;
|
|
32806
33740
|
const { status } = err;
|
|
32807
33741
|
if (typeof status !== "number" || !Number.isInteger(status)) return null;
|
|
32808
33742
|
return status >= 100 && status <= 599 ? status : null;
|
|
32809
33743
|
}
|
|
32810
|
-
function
|
|
32811
|
-
|
|
33744
|
+
function nameOf(err) {
|
|
33745
|
+
if (typeof err !== "object" || err === null || !("name" in err)) return null;
|
|
33746
|
+
return typeof err.name === "string" ? err.name : null;
|
|
33747
|
+
}
|
|
33748
|
+
function classifyRemoteFailure(err) {
|
|
33749
|
+
switch (nameOf(err)) {
|
|
33750
|
+
case "RemoteRouteAbsent":
|
|
33751
|
+
return "route-absent";
|
|
33752
|
+
case "RemoteRequestInvalid":
|
|
33753
|
+
return "invalid-request";
|
|
33754
|
+
case "RemoteResponseInvalid":
|
|
33755
|
+
return "rejected";
|
|
33756
|
+
default:
|
|
33757
|
+
break;
|
|
33758
|
+
}
|
|
33759
|
+
const status = statusOf(err);
|
|
33760
|
+
if (status === null) return "unreachable";
|
|
33761
|
+
switch (status) {
|
|
32812
33762
|
case 401:
|
|
32813
33763
|
return "unauthorized";
|
|
32814
33764
|
case 403:
|
|
32815
33765
|
return "forbidden";
|
|
33766
|
+
case 429:
|
|
33767
|
+
return "unreachable";
|
|
33768
|
+
case 404:
|
|
33769
|
+
return "unreachable";
|
|
33770
|
+
default:
|
|
33771
|
+
return status >= 400 && status <= 499 ? "rejected" : "unreachable";
|
|
33772
|
+
}
|
|
33773
|
+
}
|
|
33774
|
+
|
|
33775
|
+
// ../../packages/plugin-runtime/src/attached/failure.ts
|
|
33776
|
+
function classifyFailure(err) {
|
|
33777
|
+
switch (classifyRemoteFailure(err)) {
|
|
33778
|
+
case "unauthorized":
|
|
33779
|
+
return "unauthorized";
|
|
33780
|
+
case "forbidden":
|
|
33781
|
+
return "forbidden";
|
|
32816
33782
|
default:
|
|
32817
33783
|
return "unreachable";
|
|
32818
33784
|
}
|
|
@@ -32834,11 +33800,11 @@ function withTimeout(promise2, ms) {
|
|
|
32834
33800
|
}
|
|
32835
33801
|
|
|
32836
33802
|
// ../../packages/plugin-runtime/src/attached/forward-drops.ts
|
|
32837
|
-
import { readFileSync as
|
|
32838
|
-
import { join as
|
|
33803
|
+
import { readFileSync as readFileSync10 } from "fs";
|
|
33804
|
+
import { join as join16 } from "path";
|
|
32839
33805
|
var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
|
|
32840
33806
|
function forwardDropsPath(dataDir2) {
|
|
32841
|
-
return
|
|
33807
|
+
return join16(dataDir2, FORWARD_DROPS_FILENAME);
|
|
32842
33808
|
}
|
|
32843
33809
|
function recordForwardDrops(dataDir2, count, nowMs) {
|
|
32844
33810
|
if (count <= 0) return;
|
|
@@ -32856,7 +33822,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
|
|
|
32856
33822
|
}
|
|
32857
33823
|
function readForwardDrops(dataDir2) {
|
|
32858
33824
|
try {
|
|
32859
|
-
const parsed2 = JSON.parse(
|
|
33825
|
+
const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
|
|
32860
33826
|
if (typeof parsed2 !== "object" || parsed2 === null) return null;
|
|
32861
33827
|
const record2 = parsed2;
|
|
32862
33828
|
if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
|
|
@@ -32874,13 +33840,12 @@ function readForwardDrops(dataDir2) {
|
|
|
32874
33840
|
|
|
32875
33841
|
// ../../packages/plugin-runtime/src/attached/forward-policy.ts
|
|
32876
33842
|
import { randomUUID as randomUUID15 } from "crypto";
|
|
32877
|
-
import { readFileSync as readFileSync14 } from "fs";
|
|
32878
33843
|
import { readFile, rename, writeFile } from "fs/promises";
|
|
32879
|
-
import { join as
|
|
33844
|
+
import { join as join26 } from "path";
|
|
32880
33845
|
|
|
32881
33846
|
// ../../packages/plugin-sdk/src/config.ts
|
|
32882
|
-
import { existsSync as
|
|
32883
|
-
import { join as
|
|
33847
|
+
import { existsSync as existsSync8 } from "fs";
|
|
33848
|
+
import { join as join17 } from "path";
|
|
32884
33849
|
|
|
32885
33850
|
// ../../packages/plugin-sdk/src/provider-env.ts
|
|
32886
33851
|
var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
|
|
@@ -32934,8 +33899,8 @@ function resolveProvider() {
|
|
|
32934
33899
|
function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
|
|
32935
33900
|
try {
|
|
32936
33901
|
ensureLayoutDirSync(base);
|
|
32937
|
-
const settingsFile =
|
|
32938
|
-
if (
|
|
33902
|
+
const settingsFile = join17(settingsDir(base), "settings.json");
|
|
33903
|
+
if (existsSync8(settingsFile)) tightenFile(settingsFile);
|
|
32939
33904
|
} catch {
|
|
32940
33905
|
}
|
|
32941
33906
|
migrateLegacyLayout(base);
|
|
@@ -32958,9 +33923,9 @@ function resolveProviderSafe(resolveProviderFn) {
|
|
|
32958
33923
|
}
|
|
32959
33924
|
|
|
32960
33925
|
// ../../packages/plugin-sdk/src/config-inventory.ts
|
|
32961
|
-
import { readdirSync as readdirSync2, readFileSync as
|
|
33926
|
+
import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
|
|
32962
33927
|
import { homedir as homedir2 } from "os";
|
|
32963
|
-
import { basename as basename3, join as
|
|
33928
|
+
import { basename as basename3, join as join19 } from "path";
|
|
32964
33929
|
|
|
32965
33930
|
// ../../packages/detections/src/egress/registry.ts
|
|
32966
33931
|
var EXTRACTOR_VERSION = "1";
|
|
@@ -35743,24 +36708,20 @@ function bundledDetections() {
|
|
|
35743
36708
|
}
|
|
35744
36709
|
|
|
35745
36710
|
// ../../packages/plugin-sdk/src/repo.ts
|
|
35746
|
-
import { existsSync as
|
|
35747
|
-
import { basename as basename2, dirname as dirname4, isAbsolute, join as
|
|
36711
|
+
import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
|
|
36712
|
+
import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
|
|
35748
36713
|
|
|
35749
36714
|
// ../../packages/plugin-sdk/src/events.ts
|
|
35750
36715
|
import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
|
|
35751
36716
|
|
|
35752
36717
|
// ../../packages/plugin-sdk/src/isolated-scan.ts
|
|
35753
|
-
import { existsSync as
|
|
36718
|
+
import { existsSync as existsSync10 } from "fs";
|
|
35754
36719
|
import { fileURLToPath } from "url";
|
|
35755
36720
|
import { Worker } from "worker_threads";
|
|
35756
36721
|
|
|
35757
|
-
// ../../packages/plugin-sdk/src/
|
|
35758
|
-
|
|
35759
|
-
import {
|
|
35760
|
-
import { join as join17 } from "path";
|
|
35761
|
-
|
|
35762
|
-
// ../../packages/plugin-sdk/src/inventory-resolver.ts
|
|
35763
|
-
import { arch, hostname as hostname4, platform, release } from "os";
|
|
36722
|
+
// ../../packages/plugin-sdk/src/host-floor.ts
|
|
36723
|
+
import { readFileSync as readFileSync14 } from "fs";
|
|
36724
|
+
import { join as join21 } from "path";
|
|
35764
36725
|
|
|
35765
36726
|
// ../../packages/plugin-sdk/src/model-governance.ts
|
|
35766
36727
|
import {
|
|
@@ -35768,24 +36729,99 @@ import {
|
|
|
35768
36729
|
fstatSync,
|
|
35769
36730
|
mkdirSync as mkdirSync2,
|
|
35770
36731
|
openSync as openSync2,
|
|
35771
|
-
readFileSync as
|
|
36732
|
+
readFileSync as readFileSync13,
|
|
35772
36733
|
readSync,
|
|
35773
36734
|
writeFileSync as writeFileSync5
|
|
35774
36735
|
} from "fs";
|
|
35775
|
-
import { join as
|
|
36736
|
+
import { join as join20 } from "path";
|
|
35776
36737
|
var TAIL_BYTES = 256 * 1024;
|
|
35777
36738
|
|
|
36739
|
+
// ../../packages/plugin-sdk/src/host-floor.ts
|
|
36740
|
+
var HOST_FEATURE = {
|
|
36741
|
+
ModelSwitch: "model-switch",
|
|
36742
|
+
VaultPointerDisplay: "vault-pointer-display"
|
|
36743
|
+
};
|
|
36744
|
+
var HOST_FLOORS = {
|
|
36745
|
+
[HOST_FEATURE.ModelSwitch]: {
|
|
36746
|
+
label: "model-switch protection",
|
|
36747
|
+
hookEvents: ["PreModelSwitch", "PostModelSwitch"],
|
|
36748
|
+
since: "2.1.251"
|
|
36749
|
+
},
|
|
36750
|
+
[HOST_FEATURE.VaultPointerDisplay]: {
|
|
36751
|
+
label: "vault pointer display",
|
|
36752
|
+
hookEvents: ["MessageDisplay"],
|
|
36753
|
+
since: "2.1.152"
|
|
36754
|
+
}
|
|
36755
|
+
};
|
|
36756
|
+
function hostFloorGaps(hostVersion) {
|
|
36757
|
+
if (hostVersion === void 0) return [];
|
|
36758
|
+
const gaps = [];
|
|
36759
|
+
for (const [feature, row] of Object.entries(HOST_FLOORS)) {
|
|
36760
|
+
if (compareBinaryVersions(hostVersion, row.since) < 0) {
|
|
36761
|
+
gaps.push({ feature, label: row.label, since: row.since });
|
|
36762
|
+
}
|
|
36763
|
+
}
|
|
36764
|
+
return gaps;
|
|
36765
|
+
}
|
|
36766
|
+
function requiredHostVersion(gaps) {
|
|
36767
|
+
let highest;
|
|
36768
|
+
for (const gap of gaps) {
|
|
36769
|
+
if (highest === void 0 || compareBinaryVersions(gap.since, highest) > 0) highest = gap.since;
|
|
36770
|
+
}
|
|
36771
|
+
return highest;
|
|
36772
|
+
}
|
|
36773
|
+
var MAX_TESTED_HOST = "2.1.260";
|
|
36774
|
+
function hostCeilingNotice(hostVersion) {
|
|
36775
|
+
if (hostVersion === void 0) return null;
|
|
36776
|
+
if (compareBinaryVersions(hostVersion, MAX_TESTED_HOST) <= 0) return null;
|
|
36777
|
+
return `This Claude Code (${hostVersion}) is newer than AKA has been tested against (${MAX_TESTED_HOST}). If something here looks wrong, that is the likely cause \u2014 we'll look into it.`;
|
|
36778
|
+
}
|
|
36779
|
+
function hostCompatibilityLines(cache) {
|
|
36780
|
+
if (cache === null) return [];
|
|
36781
|
+
const lines = [`Claude Code: ${cache.version} (last seen)`];
|
|
36782
|
+
const gaps = hostFloorGaps(cache.version);
|
|
36783
|
+
const required2 = requiredHostVersion(gaps);
|
|
36784
|
+
if (required2 !== void 0) {
|
|
36785
|
+
lines.push(` inactive: ${gaps.map((g) => g.label).join(", ")}`);
|
|
36786
|
+
lines.push(` update Claude Code to ${required2} or newer to turn them on`);
|
|
36787
|
+
}
|
|
36788
|
+
const ceiling = hostCeilingNotice(cache.version);
|
|
36789
|
+
if (ceiling !== null) lines.push(` ${ceiling}`);
|
|
36790
|
+
return lines;
|
|
36791
|
+
}
|
|
36792
|
+
var HOST_VERSION_MARKER = "host-version.json";
|
|
36793
|
+
function readHostVersionCache(dataDir2) {
|
|
36794
|
+
try {
|
|
36795
|
+
const parsed2 = JSON.parse(readFileSync14(join21(dataDir2, HOST_VERSION_MARKER), "utf8"));
|
|
36796
|
+
if (typeof parsed2 !== "object" || parsed2 === null) return null;
|
|
36797
|
+
const { version: version2, observedAt } = parsed2;
|
|
36798
|
+
if (typeof version2 !== "string" || !isParseableBinaryVersion(version2)) return null;
|
|
36799
|
+
if (typeof observedAt !== "number" || !Number.isFinite(observedAt)) return null;
|
|
36800
|
+
return { version: version2, observedAt };
|
|
36801
|
+
} catch {
|
|
36802
|
+
return null;
|
|
36803
|
+
}
|
|
36804
|
+
}
|
|
36805
|
+
|
|
36806
|
+
// ../../packages/plugin-sdk/src/ignore-layers.ts
|
|
36807
|
+
var import_ignore = __toESM(require_ignore(), 1);
|
|
36808
|
+
import { readFileSync as readFileSync15 } from "fs";
|
|
36809
|
+
import { join as join22 } from "path";
|
|
36810
|
+
|
|
36811
|
+
// ../../packages/plugin-sdk/src/inventory-resolver.ts
|
|
36812
|
+
import { arch, hostname as hostname4, platform, release } from "os";
|
|
36813
|
+
|
|
35778
36814
|
// ../../packages/plugin-sdk/src/nudge.ts
|
|
35779
|
-
import { mkdirSync as mkdirSync3, readFileSync as
|
|
35780
|
-
import { join as
|
|
36815
|
+
import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
|
|
36816
|
+
import { join as join23 } from "path";
|
|
35781
36817
|
|
|
35782
36818
|
// ../../packages/plugin-sdk/src/paths.ts
|
|
35783
36819
|
import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
|
|
35784
36820
|
import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
|
|
35785
36821
|
|
|
35786
36822
|
// ../../packages/plugin-sdk/src/project-files.ts
|
|
35787
|
-
import { existsSync as
|
|
35788
|
-
import { basename as basename5, join as
|
|
36823
|
+
import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
|
|
36824
|
+
import { basename as basename5, join as join24 } from "path";
|
|
35789
36825
|
|
|
35790
36826
|
// ../../packages/plugin-sdk/src/provider-env-antigravity.ts
|
|
35791
36827
|
var optionalBaseUrl2 = external_exports.preprocess((v) => {
|
|
@@ -35821,7 +36857,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
|
35821
36857
|
|
|
35822
36858
|
// ../../packages/plugin-sdk/src/throttle.ts
|
|
35823
36859
|
import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
|
|
35824
|
-
import { join as
|
|
36860
|
+
import { join as join25 } from "path";
|
|
35825
36861
|
|
|
35826
36862
|
// ../../packages/plugin-runtime/src/attached/forward-policy.ts
|
|
35827
36863
|
function isInvalidRequest(err) {
|
|
@@ -35837,31 +36873,12 @@ function isServerRejection(err) {
|
|
|
35837
36873
|
var FORWARD_BUDGET_MS = 1500;
|
|
35838
36874
|
var DECISION_PATH_BUDGET_MS = 800;
|
|
35839
36875
|
var BREAKER_FAILURE_THRESHOLD = 3;
|
|
35840
|
-
var BREAKER_COOLDOWN_MS = 3e4;
|
|
35841
36876
|
var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
|
|
35842
|
-
var FAILURES = /* @__PURE__ */ new Set([
|
|
35843
|
-
"unauthorized",
|
|
35844
|
-
"forbidden",
|
|
35845
|
-
"unreachable"
|
|
35846
|
-
]);
|
|
35847
36877
|
var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
|
|
35848
36878
|
var STATE_FILENAME = FORWARD_STATE_FILENAME;
|
|
35849
|
-
function parseBreakerState(raw, nowMs) {
|
|
35850
|
-
try {
|
|
35851
|
-
const parsed2 = JSON.parse(raw);
|
|
35852
|
-
if (typeof parsed2 !== "object" || parsed2 === null) return null;
|
|
35853
|
-
const record2 = parsed2;
|
|
35854
|
-
const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
|
|
35855
|
-
const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
|
|
35856
|
-
const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
|
|
35857
|
-
return { consecutiveFailures: failures, openedAtMs, lastFailure };
|
|
35858
|
-
} catch {
|
|
35859
|
-
return null;
|
|
35860
|
-
}
|
|
35861
|
-
}
|
|
35862
36879
|
function createForwardPolicy(deps) {
|
|
35863
36880
|
const now = deps.now ?? (() => Date.now());
|
|
35864
|
-
const file2 =
|
|
36881
|
+
const file2 = join26(deps.dir, STATE_FILENAME);
|
|
35865
36882
|
let state = null;
|
|
35866
36883
|
let loading = null;
|
|
35867
36884
|
async function readState() {
|
|
@@ -35871,7 +36888,7 @@ function createForwardPolicy(deps) {
|
|
|
35871
36888
|
} catch {
|
|
35872
36889
|
return { ...CLOSED };
|
|
35873
36890
|
}
|
|
35874
|
-
return
|
|
36891
|
+
return parseForwardHealth(raw, now()) ?? { ...CLOSED };
|
|
35875
36892
|
}
|
|
35876
36893
|
async function load() {
|
|
35877
36894
|
if (state !== null) return state;
|
|
@@ -35917,7 +36934,7 @@ function createForwardPolicy(deps) {
|
|
|
35917
36934
|
};
|
|
35918
36935
|
const at = now();
|
|
35919
36936
|
if (current.openedAtMs !== null) {
|
|
35920
|
-
if (
|
|
36937
|
+
if (isForwardPaused(current, at)) {
|
|
35921
36938
|
return { ok: false, reason: "breaker-open" };
|
|
35922
36939
|
}
|
|
35923
36940
|
await persist({
|
|
@@ -36454,7 +37471,18 @@ var AttachedDataGateway = class {
|
|
|
36454
37471
|
// and the spread above would otherwise drop the field silently — which is
|
|
36455
37472
|
// exactly what it did, leaving the whole control inert on every device
|
|
36456
37473
|
// while every test around it stayed green.
|
|
36457
|
-
prohibitedModels: cached2.prohibitedModels
|
|
37474
|
+
prohibitedModels: cached2.prohibitedModels,
|
|
37475
|
+
// NAMED for the same reason as the line above, and it is the same defect
|
|
37476
|
+
// if it is not: `...local` above spreads the DEVICE's bundle, so a field
|
|
37477
|
+
// only the cache carries is dropped in silence. That is what left
|
|
37478
|
+
// `prohibitedModels` inert on every attached device with every test
|
|
37479
|
+
// around it green.
|
|
37480
|
+
//
|
|
37481
|
+
// Taken from the cache rather than merged here, because merging it needs
|
|
37482
|
+
// the device's own SETTING — which is not a bundle field and is not in
|
|
37483
|
+
// scope at this seam. The runtime does that merge, raise-only, where both
|
|
37484
|
+
// values are in hand (createPluginRuntime's ensureInitialized).
|
|
37485
|
+
redactFallback: cached2.redactFallback
|
|
36458
37486
|
// ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
|
|
36459
37487
|
// merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
|
|
36460
37488
|
// it emits, so an 'authored' policy arriving from the control plane
|
|
@@ -36582,10 +37610,6 @@ function toolAuditEvent(input2) {
|
|
|
36582
37610
|
};
|
|
36583
37611
|
}
|
|
36584
37612
|
|
|
36585
|
-
// ../../packages/plugin-runtime/src/attached/history-state.ts
|
|
36586
|
-
import { readFileSync as readFileSync15 } from "fs";
|
|
36587
|
-
import { join as join23 } from "path";
|
|
36588
|
-
|
|
36589
37613
|
// ../../packages/plugin-runtime/src/attached/history-sync.ts
|
|
36590
37614
|
import { createHash as createHash6 } from "crypto";
|
|
36591
37615
|
import { hostname as hostname5 } from "os";
|
|
@@ -36594,6 +37618,10 @@ import { hostname as hostname5 } from "os";
|
|
|
36594
37618
|
var CORRELATION_ID = EventMetadata.shape.correlationId;
|
|
36595
37619
|
var TRACE_ID = EventMetadata.shape.traceId;
|
|
36596
37620
|
var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
|
|
37621
|
+
var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
|
|
37622
|
+
|
|
37623
|
+
// ../../packages/plugin-runtime/src/attached/history-sync.ts
|
|
37624
|
+
var CAPTURE_BATCH_BYTES = 1024 * 1024;
|
|
36597
37625
|
|
|
36598
37626
|
// ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
|
|
36599
37627
|
import { spawn } from "child_process";
|
|
@@ -36601,7 +37629,7 @@ import { fileURLToPath as fileURLToPath2 } from "url";
|
|
|
36601
37629
|
var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
|
|
36602
37630
|
|
|
36603
37631
|
// ../../packages/plugin-runtime/src/attached/plugin-block.ts
|
|
36604
|
-
import { readFileSync as
|
|
37632
|
+
import { readFileSync as readFileSync17 } from "fs";
|
|
36605
37633
|
function createPluginBlock(build, policyStore) {
|
|
36606
37634
|
return async () => {
|
|
36607
37635
|
const cached2 = await policyStore.read();
|
|
@@ -36620,7 +37648,7 @@ function createPluginBlock(build, policyStore) {
|
|
|
36620
37648
|
// ../../packages/plugin-runtime/src/attached/policy-store.ts
|
|
36621
37649
|
import { randomUUID as randomUUID16 } from "crypto";
|
|
36622
37650
|
import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
|
|
36623
|
-
import { join as
|
|
37651
|
+
import { join as join27 } from "path";
|
|
36624
37652
|
|
|
36625
37653
|
// ../../packages/plugin-runtime/src/attached/atomic-publish.ts
|
|
36626
37654
|
import { rename as rename2 } from "fs/promises";
|
|
@@ -36644,7 +37672,7 @@ async function publishByRename(tmp, file2, move = rename2) {
|
|
|
36644
37672
|
|
|
36645
37673
|
// ../../packages/plugin-runtime/src/attached/policy-store.ts
|
|
36646
37674
|
function createPolicyStore(dir = dataDir()) {
|
|
36647
|
-
const file2 =
|
|
37675
|
+
const file2 = join27(dir, "policy-cache.json");
|
|
36648
37676
|
async function read() {
|
|
36649
37677
|
try {
|
|
36650
37678
|
const raw = await readFile2(file2, "utf8");
|
|
@@ -36875,11 +37903,11 @@ function readStorePosture(dbPath2) {
|
|
|
36875
37903
|
// ../../packages/plugin-runtime/src/attached/posture-store.ts
|
|
36876
37904
|
import { randomUUID as randomUUID17 } from "crypto";
|
|
36877
37905
|
import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
|
|
36878
|
-
import { join as
|
|
37906
|
+
import { join as join28 } from "path";
|
|
36879
37907
|
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
36880
37908
|
function createPostureStore(dir = settingsDir(), legacyDir) {
|
|
36881
|
-
const file2 =
|
|
36882
|
-
const legacyFile = legacyDir === void 0 ? null :
|
|
37909
|
+
const file2 = join28(dir, "posture-state.json");
|
|
37910
|
+
const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
|
|
36883
37911
|
async function persist(state) {
|
|
36884
37912
|
await ensureDataDir(dir);
|
|
36885
37913
|
const tmp = `${file2}.${randomUUID17()}.tmp`;
|
|
@@ -36947,8 +37975,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
|
|
|
36947
37975
|
}
|
|
36948
37976
|
|
|
36949
37977
|
// ../../packages/plugin-runtime/src/attached/sync-state.ts
|
|
36950
|
-
import { readFileSync as
|
|
36951
|
-
import { join as
|
|
37978
|
+
import { readFileSync as readFileSync18 } from "fs";
|
|
37979
|
+
import { join as join29 } from "path";
|
|
36952
37980
|
|
|
36953
37981
|
// ../../packages/plugin-runtime/src/attached/status.ts
|
|
36954
37982
|
var REFUSAL_LINES = {
|
|
@@ -36969,6 +37997,14 @@ import { spawn as spawn2 } from "child_process";
|
|
|
36969
37997
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
36970
37998
|
var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
|
|
36971
37999
|
|
|
38000
|
+
// ../../packages/plugin-runtime/src/content-retention-pass.ts
|
|
38001
|
+
var MAX_ROWS_PER_SWEEP = 50 * 1e3;
|
|
38002
|
+
|
|
38003
|
+
// ../../packages/plugin-runtime/src/content-retention-trigger.ts
|
|
38004
|
+
import { spawn as spawn3 } from "child_process";
|
|
38005
|
+
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
38006
|
+
var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
|
|
38007
|
+
|
|
36972
38008
|
// ../../packages/plugin-runtime/src/attached/factory.ts
|
|
36973
38009
|
import { hostname as hostname6 } from "os";
|
|
36974
38010
|
|
|
@@ -37536,7 +38572,7 @@ function fenced(body) {
|
|
|
37536
38572
|
|
|
37537
38573
|
// ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
|
|
37538
38574
|
import { writeFileSync as writeFileSync8 } from "fs";
|
|
37539
|
-
import { join as
|
|
38575
|
+
import { join as join30 } from "path";
|
|
37540
38576
|
|
|
37541
38577
|
// ../../packages/setup-wizard/src/triage/merge.ts
|
|
37542
38578
|
var RANK = Object.fromEntries(
|
|
@@ -37544,9 +38580,9 @@ var RANK = Object.fromEntries(
|
|
|
37544
38580
|
);
|
|
37545
38581
|
|
|
37546
38582
|
// ../../packages/setup-wizard/src/triage/plan-file.ts
|
|
37547
|
-
import { mkdtempSync, readFileSync as
|
|
38583
|
+
import { mkdtempSync, readFileSync as readFileSync19, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
|
|
37548
38584
|
import { tmpdir } from "os";
|
|
37549
|
-
import { basename as basename6, dirname as dirname6, join as
|
|
38585
|
+
import { basename as basename6, dirname as dirname6, join as join31 } from "path";
|
|
37550
38586
|
var SuppressionEntrySchema = external_exports.object({
|
|
37551
38587
|
ruleId: external_exports.string(),
|
|
37552
38588
|
category: DetectionCategory,
|
|
@@ -37589,11 +38625,10 @@ var PersistedPlanSchema = external_exports.object({
|
|
|
37589
38625
|
|
|
37590
38626
|
// src/command-registry.ts
|
|
37591
38627
|
import { readdirSync as readdirSync5 } from "fs";
|
|
37592
|
-
import { fileURLToPath as
|
|
37593
|
-
var COMMANDS_DIR =
|
|
38628
|
+
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
38629
|
+
var COMMANDS_DIR = fileURLToPath5(new URL("../commands", import.meta.url));
|
|
37594
38630
|
|
|
37595
38631
|
// src/render.ts
|
|
37596
|
-
var SEVERITY_WEIGHT = { critical: 4, high: 3, medium: 2, low: 1 };
|
|
37597
38632
|
var SEVERITY_GLYPH = {
|
|
37598
38633
|
critical: SHADE.full,
|
|
37599
38634
|
high: SHADE.dark,
|
|
@@ -37603,15 +38638,6 @@ var SEVERITY_GLYPH = {
|
|
|
37603
38638
|
function severityGlyph(severity) {
|
|
37604
38639
|
return SEVERITY_GLYPH[severity] ?? SHADE.light;
|
|
37605
38640
|
}
|
|
37606
|
-
var ADVICE = {
|
|
37607
|
-
secret: "Rotate the exposed credentials and move them out of prompts (secrets manager / env vars).",
|
|
37608
|
-
pii: "Remove or mask personal data before it reaches the model.",
|
|
37609
|
-
financial: "Strip card and account numbers; share only non-sensitive references.",
|
|
37610
|
-
phi: "Remove protected health information \u2014 it should never reach an external model.",
|
|
37611
|
-
code_context: "Confirm this proprietary code context is safe to share.",
|
|
37612
|
-
code_flaw: "Review the flagged pattern and apply the secure alternative (parameterized queries, safe deserializers, etc.).",
|
|
37613
|
-
custom: "Review against your organization\u2019s custom policy."
|
|
37614
|
-
};
|
|
37615
38641
|
function shortTime(iso) {
|
|
37616
38642
|
if (!iso) return "\u2014";
|
|
37617
38643
|
return iso.length >= 16 ? `${iso.slice(5, 10)} ${iso.slice(11, 16)}` : iso;
|
|
@@ -37620,11 +38646,6 @@ function empty(message) {
|
|
|
37620
38646
|
return message;
|
|
37621
38647
|
}
|
|
37622
38648
|
var CATEGORY_ORDER2 = DetectionCategory.options;
|
|
37623
|
-
function healthScore(summary) {
|
|
37624
|
-
const handled = summary.byAction.block + summary.byAction.redact + summary.byAction.warn;
|
|
37625
|
-
const handledRatio = summary.findings === 0 ? 1 : handled / summary.findings;
|
|
37626
|
-
return Math.round(100 * (0.6 * summary.coverage + 0.4 * handledRatio));
|
|
37627
|
-
}
|
|
37628
38649
|
function renderFindings(findings, status, severity) {
|
|
37629
38650
|
if (findings.length === 0) {
|
|
37630
38651
|
return empty(
|
|
@@ -37680,13 +38701,6 @@ function renderStatusBar(s, opts = {}) {
|
|
|
37680
38701
|
const open3 = `${flag} ${String(s.openFindings)} open findings`;
|
|
37681
38702
|
return `${paint.brand("\u25B8\u25B8 AKA")}${sep4}${score}${sep4}${tally}${sep4}${open3}`;
|
|
37682
38703
|
}
|
|
37683
|
-
function findingStatus(summary) {
|
|
37684
|
-
return {
|
|
37685
|
-
score: healthScore(summary),
|
|
37686
|
-
unreviewed: { ...summary.bySeverity },
|
|
37687
|
-
openFindings: summary.findings
|
|
37688
|
-
};
|
|
37689
|
-
}
|
|
37690
38704
|
function renderHealth(r) {
|
|
37691
38705
|
const lines = [`\u25CF ${r.title}`, ""];
|
|
37692
38706
|
for (const g of r.gauges) lines.push(indent(renderGauge(g)));
|
|
@@ -37694,6 +38708,10 @@ function renderHealth(r) {
|
|
|
37694
38708
|
const pct = Math.round(r.scanCoverage * 100);
|
|
37695
38709
|
const stats = `Open findings ${String(r.openFindings)} Scan coverage ${String(pct)}%`;
|
|
37696
38710
|
lines.push(indent(stats), "");
|
|
38711
|
+
if (r.host.length > 0) {
|
|
38712
|
+
for (const line of r.host) lines.push(indent(line));
|
|
38713
|
+
lines.push("");
|
|
38714
|
+
}
|
|
37697
38715
|
lines.push(indent("Detections & actions \u2014 last 7 days"));
|
|
37698
38716
|
const maxDay = Math.max(1, ...r.week.map((d) => d.total));
|
|
37699
38717
|
for (const d of r.week) {
|
|
@@ -37718,7 +38736,9 @@ function renderHealth(r) {
|
|
|
37718
38736
|
);
|
|
37719
38737
|
lines.push(indent(`${String(r.weekFindings)} findings in the last 7 days`));
|
|
37720
38738
|
lines.push("");
|
|
37721
|
-
lines.push(
|
|
38739
|
+
lines.push(
|
|
38740
|
+
indent(`Run /aka:recommend to review ${String(r.recommendCount)} prioritized actions.`)
|
|
38741
|
+
);
|
|
37722
38742
|
lines.push("");
|
|
37723
38743
|
lines.push(
|
|
37724
38744
|
indent(
|
|
@@ -37732,7 +38752,7 @@ function weekday(isoDay2) {
|
|
|
37732
38752
|
const date5 = /* @__PURE__ */ new Date(`${isoDay2}T00:00:00Z`);
|
|
37733
38753
|
return Number.isNaN(date5.getTime()) ? isoDay2 : WEEKDAYS[date5.getUTCDay()] ?? isoDay2;
|
|
37734
38754
|
}
|
|
37735
|
-
function buildHealthReport(summary, findings, activity) {
|
|
38755
|
+
function buildHealthReport(summary, findings, activity, hostLines = []) {
|
|
37736
38756
|
const status = findingStatus(summary);
|
|
37737
38757
|
const handled = summary.byAction.block + summary.byAction.redact + summary.byAction.warn;
|
|
37738
38758
|
const handledPct = summary.findings === 0 ? 100 : Math.round(handled / summary.findings * 100);
|
|
@@ -37769,48 +38789,10 @@ function buildHealthReport(summary, findings, activity) {
|
|
|
37769
38789
|
// so "review N prioritized actions" always matches that screen.
|
|
37770
38790
|
recommendCount: buildRecommendations(findings).length,
|
|
37771
38791
|
unreviewed: status.unreviewed,
|
|
37772
|
-
score: status.score
|
|
38792
|
+
score: status.score,
|
|
38793
|
+
host: [...hostLines]
|
|
37773
38794
|
};
|
|
37774
38795
|
}
|
|
37775
|
-
var REC_TEMPLATE = {
|
|
37776
|
-
secret: { title: "Exposed secret detected", action: "Rotate" },
|
|
37777
|
-
pii: { title: "Personal data in a prompt", action: "Remove" },
|
|
37778
|
-
financial: { title: "Financial data detected", action: "Strip" },
|
|
37779
|
-
phi: { title: "Health information detected", action: "Remove" },
|
|
37780
|
-
code_context: { title: "Proprietary code shared", action: "Review" },
|
|
37781
|
-
custom: { title: "Custom policy match", action: "Review" }
|
|
37782
|
-
};
|
|
37783
|
-
var MAX_RECOMMENDATIONS = 10;
|
|
37784
|
-
function buildRecommendations(findings) {
|
|
37785
|
-
const buckets = /* @__PURE__ */ new Map();
|
|
37786
|
-
for (const f of findings) {
|
|
37787
|
-
const b = buckets.get(f.category) ?? {
|
|
37788
|
-
category: f.category,
|
|
37789
|
-
count: 0,
|
|
37790
|
-
severity: f.severity,
|
|
37791
|
-
weight: 0,
|
|
37792
|
-
ruleId: f.ruleId
|
|
37793
|
-
};
|
|
37794
|
-
b.count++;
|
|
37795
|
-
const w = SEVERITY_WEIGHT[f.severity] ?? 0;
|
|
37796
|
-
if (w > b.weight) {
|
|
37797
|
-
b.weight = w;
|
|
37798
|
-
b.severity = f.severity;
|
|
37799
|
-
b.ruleId = f.ruleId;
|
|
37800
|
-
}
|
|
37801
|
-
buckets.set(f.category, b);
|
|
37802
|
-
}
|
|
37803
|
-
return [...buckets.values()].sort((a, b) => b.weight - a.weight || b.count - a.count).slice(0, MAX_RECOMMENDATIONS).map((b) => {
|
|
37804
|
-
const t = REC_TEMPLATE[b.category] ?? { title: `${b.category} finding`, action: "Review" };
|
|
37805
|
-
return {
|
|
37806
|
-
severity: b.severity,
|
|
37807
|
-
title: t.title,
|
|
37808
|
-
description: ADVICE[b.category] ?? "Review this finding against your policy.",
|
|
37809
|
-
context: `${b.ruleId} \xB7 ${String(b.count)} finding${b.count === 1 ? "" : "s"}`,
|
|
37810
|
-
action: t.action
|
|
37811
|
-
};
|
|
37812
|
-
});
|
|
37813
|
-
}
|
|
37814
38796
|
var REC_DESC_WIDTH = 72;
|
|
37815
38797
|
var REC_BODY_INDENT = " ";
|
|
37816
38798
|
function renderRecommend(recs, status) {
|
|
@@ -37830,7 +38812,7 @@ function renderRecommend(recs, status) {
|
|
|
37830
38812
|
lines.push("", indent(`${REC_BODY_INDENT}${r.context} \u2192 ${r.action}`), "");
|
|
37831
38813
|
});
|
|
37832
38814
|
lines.push(
|
|
37833
|
-
indent("Run /recommend <n> to act on one, or /health for the summary."),
|
|
38815
|
+
indent("Run /aka:recommend <n> to act on one, or /aka:health for the summary."),
|
|
37834
38816
|
"",
|
|
37835
38817
|
indent(renderStatusBar(status))
|
|
37836
38818
|
);
|
|
@@ -37991,7 +38973,7 @@ async function runQuery(sub2, gateway, opts = {}) {
|
|
|
37991
38973
|
gateway.recentFindings({ limit: 500 }),
|
|
37992
38974
|
gateway.activityByDay(7)
|
|
37993
38975
|
]);
|
|
37994
|
-
return renderHealth(buildHealthReport(summary, findings, activity));
|
|
38976
|
+
return renderHealth(buildHealthReport(summary, findings, activity, opts.hostLines));
|
|
37995
38977
|
}
|
|
37996
38978
|
case "recommend": {
|
|
37997
38979
|
const [findings, summary] = await Promise.all([
|
|
@@ -38047,7 +39029,16 @@ try {
|
|
|
38047
39029
|
try {
|
|
38048
39030
|
const severity = parseSeverity(args);
|
|
38049
39031
|
process.stdout.write(
|
|
38050
|
-
`${fenced(
|
|
39032
|
+
`${fenced(
|
|
39033
|
+
await runQuery(sub, gateway, {
|
|
39034
|
+
...severity !== void 0 ? { severity } : {},
|
|
39035
|
+
// Resolved here rather than inside runQuery, which holds a gateway
|
|
39036
|
+
// and not the data dir. Read from the cache a hook wrote: probing
|
|
39037
|
+
// `claude --version` would answer for the install on PATH, which
|
|
39038
|
+
// need not be the one running any session.
|
|
39039
|
+
hostLines: hostCompatibilityLines(readHostVersionCache(config2.dataDir))
|
|
39040
|
+
})
|
|
39041
|
+
)}
|
|
38051
39042
|
`
|
|
38052
39043
|
);
|
|
38053
39044
|
} finally {
|