@akasecurity/ai-tc-claude-code 0.9.0 → 0.9.2

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.
@@ -493,7 +493,7 @@ var require_ignore = __commonJS({
493
493
 
494
494
  // ../../packages/persistence/src/database.ts
495
495
  import { randomUUID as randomUUID8 } from "crypto";
496
- import { existsSync, renameSync, rmSync } from "fs";
496
+ import { existsSync, renameSync as renameSync2, rmSync as rmSync2 } from "fs";
497
497
  import { join, sep } from "path";
498
498
  import { DatabaseSync } from "node:sqlite";
499
499
 
@@ -542,6 +542,22 @@ var SQLITE_MIGRATIONS = [
542
542
  {
543
543
  tag: "0010_events_session_expression_index",
544
544
  sql: "-- Custom migration: partial expression index for session-scoped finding reads.\n--\n-- sessionFindingsCount, the session-scoped listGroupedFindings paths, and the\n-- insert-time session dedup all filter live-capture events by\n-- json_extract(e.metadata, '$.sessionId') = :sessionId\n-- \u2014 previously a full findings-join scan with a JSON parse per row. The\n-- IS NOT NULL predicate keeps the index to session-stamped events only (an\n-- equality probe implies non-null, so SQLite still uses it).\nCREATE INDEX `idx_events_session_id` ON `events` (json_extract(`metadata`, '$.sessionId')) WHERE json_extract(`metadata`, '$.sessionId') IS NOT NULL;\n"
545
+ },
546
+ {
547
+ tag: "0011_egress_writer",
548
+ sql: '-- Stable per-project reconcile key for egress call sites, plus a host-keyed\n-- egress decision override that survives destination pruning.\n--\n-- DROP INDEX IF EXISTS, not a bare DROP: the applier replays a pending\n-- migration\'s non-index statements verbatim, so a store that lost\n-- uq_share_call_site out of band would throw here \u2014 and on the plugin hook path\n-- that throw is swallowed fail-open, silently stopping capture.\n--\n-- Existing rows carry the old key\'s discriminator into project_key\n-- (\'legacy:\' || project), so the new unique index is a re-encoding of the old\n-- one and cannot collide on rows the old one allowed. Leaving them on the\n-- column default would collapse two projects\' identical file/line hits onto\n-- one key and abort the whole migration. Writer keys are \'git:\'/\'path:\'-\n-- prefixed, so a backfilled row never collides with a captured one either.\n--\n-- egress_decision_override.destination_id becomes nullable with ON DELETE SET\n-- NULL, which SQLite can only do by rebuilding the table. `host` is ADDed\n-- before the rebuild so the copy has a column to read and so the migration\n-- still presents two probeable columns to the applier\'s evidence check.\nALTER TABLE `share_call_site` ADD `project_key` text DEFAULT \'\' NOT NULL;--> statement-breakpoint\nUPDATE `share_call_site` SET `project_key` = \'legacy:\' || `project`;--> statement-breakpoint\nDROP INDEX IF EXISTS `uq_share_call_site`;--> statement-breakpoint\nCREATE UNIQUE INDEX `uq_share_call_site` ON `share_call_site` (`endpoint_id`,`project_key`,`file`,`line`);--> statement-breakpoint\nCREATE INDEX `idx_share_call_site_project` ON `share_call_site` (`project_key`,`endpoint_id`);--> statement-breakpoint\nALTER TABLE `egress_decision_override` ADD `host` text;--> statement-breakpoint\nPRAGMA foreign_keys=OFF;--> statement-breakpoint\nCREATE TABLE `__new_egress_decision_override` (\n `id` text PRIMARY KEY NOT NULL,\n `destination_id` text,\n `host` text,\n `decision` text NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL,\n FOREIGN KEY (`destination_id`) REFERENCES `share_destination`(`id`) ON UPDATE no action ON DELETE set null\n);\n--> statement-breakpoint\nINSERT INTO `__new_egress_decision_override`("id", "destination_id", "host", "decision", "created_at", "updated_at") SELECT "id", "destination_id", "host", "decision", "created_at", "updated_at" FROM `egress_decision_override`;--> statement-breakpoint\nDROP TABLE `egress_decision_override`;--> statement-breakpoint\nALTER TABLE `__new_egress_decision_override` RENAME TO `egress_decision_override`;--> statement-breakpoint\nPRAGMA foreign_keys=ON;--> statement-breakpoint\nCREATE UNIQUE INDEX `uq_egress_decision_override` ON `egress_decision_override` (`destination_id`);--> statement-breakpoint\nCREATE UNIQUE INDEX `uq_egress_decision_override_host` ON `egress_decision_override` (`host`) WHERE `host` IS NOT NULL;\n'
549
+ },
550
+ {
551
+ tag: "0012_handy_the_captain",
552
+ sql: "ALTER TABLE `inspection_findings` ADD `finding_key` text;--> statement-breakpoint\nALTER TABLE `inspection_findings` ADD `first_detected_at` integer;--> statement-breakpoint\nCREATE UNIQUE INDEX `uq_inspection_findings_key` ON `inspection_findings` (`finding_key`);"
553
+ },
554
+ {
555
+ tag: "0013_legacy_history_backfill_support",
556
+ sql: "-- Legacy-to-generalized backfill support: the schema the resumable\n-- events/findings -> audit_events/inspection_findings copy needs (the row\n-- copy itself runs as a batched post-migration installer, not here \u2014 see\n-- @akasecurity/persistence's migrations.ts), plus the audit_events read-path\n-- indexes replacing the ones the legacy events table carried (0009/0010).\n\n-- Tracks how far the batched, resumable copy has advanced through each legacy\n-- table, by rowid, so a copy interrupted mid-run resumes instead of\n-- restarting, and a completed copy is a cheap no-op on every later open.\nCREATE TABLE `legacy_copy_watermark` (\n `source` text PRIMARY KEY NOT NULL,\n `last_rowid` integer DEFAULT 0 NOT NULL\n);\n--> statement-breakpoint\n-- Serves the time-range read family that scans a single event_type across a\n-- start/end window (e.g. the Activity timeline) without a full-table scan.\nCREATE INDEX `idx_audit_type_t` ON `audit_events` (`event_type`,`started_at`);\n--> statement-breakpoint\n-- Partial expression index mirroring `idx_events_code_change_path` (0009) for\n-- the generalized audit_events/attributes pair: file-path reads filter\n-- `event_type = 'code_change' AND json_extract(attributes, '$.file_path') = :path`.\nCREATE INDEX `idx_audit_code_change_path` ON `audit_events` (json_extract(`attributes`, '$.file_path')) WHERE `event_type` = 'code_change';\n--> statement-breakpoint\n-- Synthesizes a stub session root (event_type = 'session', no attributes) for\n-- every legacy `events.metadata.sessionId` that has no audit_events row yet.\n-- audit_events.root_session_id is a self-FK, enforced with foreign-key\n-- checking on, and INSERT OR IGNORE does not suppress a foreign-key violation\n-- (only UNIQUE/PK/NOT NULL/CHECK) \u2014 so this must run before the events copy\n-- resolves root_session_id, or every session-scoped row's insert fails.\n-- started_at takes the earliest legacy occurred_at recorded under that\n-- session, so the stub root's own timeline position is never later than\n-- anything it will end up parenting.\nINSERT INTO audit_events (id, event_type, root_session_id, started_at)\nSELECT\n json_extract(metadata, '$.sessionId'),\n 'session',\n NULL,\n min(occurred_at)\nFROM events\nWHERE json_valid(metadata)\n AND json_extract(metadata, '$.sessionId') IS NOT NULL\n AND json_extract(metadata, '$.sessionId') NOT IN (SELECT id FROM audit_events)\nGROUP BY json_extract(metadata, '$.sessionId');\n"
557
+ },
558
+ {
559
+ tag: "0014_drop_legacy_events_findings",
560
+ sql: "-- Custom migration: drops the frozen legacy `events`/`findings` tables\n-- (superseded by audit_events/inspection_definitions/inspection_findings) and\n-- replaces them with read-only views of the same name.\n--\n-- persistence's migrations.ts applies this migration ONLY once the batched\n-- history backfill (see runLegacyHistoryBackfill) has fully drained both\n-- tables, and only after copying the live file aside \u2014 see\n-- backupBeforeLegacyDrop in packages/persistence/src/migrations.ts. A store\n-- still mid-copy keeps its real tables and this migration stays pending.\n--\n-- The views exist for skew: the `aka` CLI and the Claude Code plugin update\n-- independently against one shared store, so an older, already-installed\n-- binary can open a store a newer binary already dropped these tables on.\n-- Every already-shipped repository constructor prepares its SQL eagerly at\n-- open time, so a bare \"table not found\" would fail the WHOLE open, not just\n-- a findings-specific read \u2014 these views keep `prepare()` succeeding so an\n-- old binary's unrelated features keep working; its own reads stay truthful,\n-- and its rare (already fail-open) writes fail at run time instead.\n--\n-- The 0009/0010 expression indexes existed only over the legacy `events`\n-- table; DROP TABLE below would remove them implicitly, but they are\n-- dropped explicitly first so the intent reads clearly. IF EXISTS so a store\n-- that reached here with an index missing out of band (an adopted-tag store\n-- whose physical index was never built) does not throw a deterministic \"no\n-- such index\" out of the fail-open drop path.\nDROP INDEX IF EXISTS `idx_events_code_change_path`;\n--> statement-breakpoint\nDROP INDEX IF EXISTS `idx_events_session_id`;\n--> statement-breakpoint\n-- `findings.event_id` references `events.id` \u2014 drop the child first.\nDROP TABLE `findings`;\n--> statement-breakpoint\nDROP TABLE `events`;\n--> statement-breakpoint\n-- Legacy `events` shape, projected from audit_events: `kind`/`occurred_at`/\n-- `source_tool` become real columns again (source_tool round-trips through\n-- the attributes bag, the only place a capture-typed audit row keeps it);\n-- `metadata` is reconstructed as the old camelCase JSON object from the new\n-- snake_case attributes bag, with `root_session_id` folded back in as\n-- `sessionId` (the one legacy metadata key that became a column, never an\n-- attribute, on the new table). Constrained to the four capture kinds so\n-- structural rows (session/run/tool_call/llm_call/source_lookup/config_scan)\n-- never leak into a legacy reader's result set \u2014 the old `events` table\n-- never held them either.\nCREATE VIEW `events` AS\nSELECT\n id,\n json_extract(attributes, '$.source_tool') AS source_tool,\n event_type AS kind,\n started_at AS occurred_at,\n content_hash,\n content,\n -- Plugin-local bookkeeping column that `ensureSyncedAtColumn` adds to the\n -- real `events` table at open time. A pre-cutover binary runs that probe on\n -- EVERY open; without this projection its `columnNames('events')` check\n -- misses `synced_at` and issues `ALTER TABLE events ADD COLUMN` against this\n -- view, which SQLite rejects (\"Cannot add a column to a view\") \u2014 a hard,\n -- non-fail-open crash of the whole open, the exact skew failure these views\n -- exist to prevent. Projecting it (always NULL; no reader consumes it)\n -- short-circuits that ALTER.\n NULL AS synced_at,\n json_object(\n 'sessionId', root_session_id,\n 'repo', json_extract(attributes, '$.repo'),\n 'filePath', json_extract(attributes, '$.file_path'),\n 'toolName', json_extract(attributes, '$.tool_name'),\n 'gitignored', json_extract(attributes, '$.gitignored'),\n 'wholeFile', json_extract(attributes, '$.whole_file'),\n 'model', json_extract(attributes, '$.model'),\n 'turnIndex', json_extract(attributes, '$.turn_index'),\n 'correlationId', json_extract(attributes, '$.correlation_id'),\n 'traceId', json_extract(attributes, '$.trace_id'),\n 'exceptionIds', json_extract(attributes, '$.exception_ids')\n ) AS metadata\nFROM audit_events\nWHERE event_type IN ('prompt', 'response', 'code_change', 'tool_use');\n--> statement-breakpoint\n-- A plain single-row INSERT (the old writer's shape \u2014 no ON CONFLICT) is\n-- accepted by prepare() against a view once an INSTEAD OF INSERT trigger\n-- exists, so it fails at run time instead of at open \u2014 landing in the same\n-- fail-open path the caller already wraps its write in.\nCREATE TRIGGER `trg_events_ro`\nINSTEAD OF INSERT ON `events`\nBEGIN SELECT RAISE(ABORT, 'events is read-only; write to audit_events instead'); END;\n--> statement-breakpoint\n-- Legacy `findings` shape: rule_id/category/severity come from the joined\n-- inspection_definitions row (the legacy table inlined them per-row; the\n-- generalized schema normalizes them out into the shared definition). A view\n-- has no rowid of its own, so the underlying table's rowid is re-exposed\n-- explicitly under that name \u2014 a legacy reader ordering by `f.rowid` would\n-- otherwise fail to resolve the column at all. Joined to audit_events for the\n-- same four-capture-kind constraint as the events view above (a finding\n-- attached to a tool_call/config_scan row never existed in the legacy table\n-- either \u2014 see the persistence findings repository's identical predicate).\nCREATE VIEW `findings` AS\nSELECT\n f.id AS id,\n f.rowid AS rowid,\n f.audit_event_id AS event_id,\n d.rule_id AS rule_id,\n d.category AS category,\n d.severity AS severity,\n f.span_start AS span_start,\n f.span_end AS span_end,\n f.masked_match AS masked_match,\n f.action_taken AS action_taken,\n f.confidence AS confidence,\n f.finding_key AS finding_key,\n f.first_detected_at AS first_detected_at\nFROM inspection_findings f\nJOIN audit_events e ON e.id = f.audit_event_id\nJOIN inspection_definitions d ON d.id = f.inspection_definition_id\nWHERE e.event_type IN ('prompt', 'response', 'code_change', 'tool_use');\n--> statement-breakpoint\n-- Defense in depth only: SQLite refuses to plan ANY upsert against a view\n-- (\"cannot UPSERT a view\") no matter what trigger exists, so this can never\n-- rescue the real legacy writer, which always used\n-- `ON CONFLICT (finding_key) DO UPDATE` \u2014 that statement still fails at\n-- prepare() on an old binary, same as it would with no trigger at all. This\n-- only covers a plain-INSERT shape, should one ever exist.\nCREATE TRIGGER `trg_findings_ro`\nINSTEAD OF INSERT ON `findings`\nBEGIN SELECT RAISE(ABORT, 'findings is read-only; write to inspection_findings instead'); END;\n"
545
561
  }
546
562
  ];
547
563
 
@@ -15372,7 +15388,12 @@ var FindingFacets = external_exports.object({
15372
15388
  severity: external_exports.array(FindingFacetItem),
15373
15389
  subtype: external_exports.array(FindingFacetItem),
15374
15390
  provider: external_exports.array(FindingFacetItem),
15375
- action: external_exports.array(FindingFacetItem)
15391
+ action: external_exports.array(FindingFacetItem),
15392
+ // Counts by the group's derived status. The SQLite store derives a status
15393
+ // for every instance, so every group lands in a bucket; a status-less
15394
+ // group (possible only for callers whose rows carry no statuses) is
15395
+ // counted under no value.
15396
+ status: external_exports.array(FindingFacetItem)
15376
15397
  }).meta({ id: "FindingFacets" });
15377
15398
  var DEFAULT_GROUPED_FINDINGS_LIMIT = 50;
15378
15399
  var ListGroupedFindingsQuery = external_exports.object({
@@ -15382,6 +15403,10 @@ var ListGroupedFindingsQuery = external_exports.object({
15382
15403
  subtype: external_exports.array(external_exports.string()).optional(),
15383
15404
  provider: external_exports.array(FindingProvider).optional(),
15384
15405
  action: external_exports.array(FindingAction).optional(),
15406
+ // Matches a group's DERIVED status (see FindingGroup.status), not its
15407
+ // individual instances' — so a filtered group's Status column always reads
15408
+ // one of the requested values.
15409
+ status: external_exports.array(FindingStatus).optional(),
15385
15410
  q: external_exports.string().optional(),
15386
15411
  // Scope to findings whose event carries this session id (the Activity page's
15387
15412
  // session → findings drilldown). Findings without a session never match.
@@ -15569,6 +15594,33 @@ var ToolCallAttributes = external_exports.object({
15569
15594
  parent_uuid: external_exports.string().optional(),
15570
15595
  run_key: external_exports.string().optional()
15571
15596
  }).catchall(external_exports.unknown());
15597
+ var CaptureAttributes = external_exports.object({
15598
+ // The harness/tool that produced the capture (`claude-code`, `cli`, …). A
15599
+ // column on the legacy `events` table; here it rides the bag because a
15600
+ // capture-typed audit row has no equivalent column of its own.
15601
+ source_tool: external_exports.string().optional(),
15602
+ file_path: external_exports.string().optional(),
15603
+ repo: external_exports.string().optional(),
15604
+ // The host tool whose input/output was scanned (e.g. 'Bash', 'WebFetch') —
15605
+ // gives a non-file capture a display location ("via Bash") when file_path
15606
+ // is absent. The tool NAME only, never its arguments/output.
15607
+ tool_name: external_exports.string().optional(),
15608
+ // Presence-only provenance flag: set when the file is excluded by the
15609
+ // repo's .gitignore. Omitted (not false) for tracked files.
15610
+ gitignored: external_exports.boolean().optional(),
15611
+ // Set ONLY when the capture is a COMPLETE file snapshot (a worktree scan
15612
+ // reading from disk), never a partial fragment (a hook-captured edit).
15613
+ whole_file: external_exports.boolean().optional(),
15614
+ // Distributed-tracing correlation: `correlation_id` ties the capture back to
15615
+ // the request that produced it; `trace_id` is the originating span's W3C
15616
+ // trace id when telemetry is enabled.
15617
+ correlation_id: external_exports.uuid().optional(),
15618
+ trace_id: external_exports.string().regex(/^[0-9a-f]{32}$/).optional(),
15619
+ // Ids of the detection exceptions that downgraded findings in this capture
15620
+ // to 'allow' — the enforcement audit trail's link back to the grant that
15621
+ // authorized the bypass.
15622
+ exception_ids: external_exports.array(external_exports.guid()).optional()
15623
+ }).catchall(external_exports.unknown());
15572
15624
  var ToolCallInspection = external_exports.object({
15573
15625
  ruleId: external_exports.string().min(1),
15574
15626
  ruleName: external_exports.string(),
@@ -15655,7 +15707,18 @@ var InspectionFindingInput = external_exports.object({
15655
15707
  span: Span,
15656
15708
  maskedMatch: external_exports.string(),
15657
15709
  actionTaken: ActionTaken,
15658
- confidence: external_exports.number().min(0).max(1)
15710
+ confidence: external_exports.number().min(0).max(1),
15711
+ // Stable, content-addressed key correlating this finding across re-detections
15712
+ // — mirrors the legacy `findings.finding_key` (uq_inspection_findings_key is
15713
+ // its unique index). Optional: only an at-rest/re-scannable finding carries
15714
+ // one; an in-flight capture (prompt/response) has nothing to re-detect
15715
+ // against and leaves it unset, so every insert is a fresh row.
15716
+ findingKey: external_exports.string().optional(),
15717
+ // The ORIGINAL detection time, preserved across a later re-detection of the
15718
+ // same findingKey — mirrors the legacy `findings.first_detected_at`.
15719
+ // Optional: when omitted, the writer derives it from the referenced audit
15720
+ // event's startedAt on first insert (see SqliteInspectionFindingsRepository).
15721
+ firstDetectedAt: external_exports.iso.datetime().optional()
15659
15722
  });
15660
15723
  var InventoryContext = external_exports.object({
15661
15724
  host: InventoryInput.optional(),
@@ -15857,6 +15920,7 @@ var ActivityOverviewResponse = external_exports.object({
15857
15920
 
15858
15921
  // ../../packages/schema/src/zod/event.ts
15859
15922
  var EventKind = external_exports.enum(["prompt", "response", "code_change", "tool_use"]).meta({ id: "EventKind" });
15923
+ var CAPTURE_EVENT_TYPES_SQL = EventKind.options.map((k) => `'${k}'`).join(",");
15860
15924
  var SourceTool = external_exports.enum(["claude-code", "claude-desktop", "cursor", "chatgpt", "github-copilot", "cli", "unknown"]).meta({ id: "SourceTool" });
15861
15925
  var EventMetadata = external_exports.object({
15862
15926
  sessionId: external_exports.string().optional(),
@@ -16197,6 +16261,7 @@ var ExceptionBundleEntry = DetectionException.pick({
16197
16261
 
16198
16262
  // ../../packages/schema/src/zod/rule.ts
16199
16263
  var MatcherType = external_exports.enum(["keyword", "regex", "validator"]).meta({ id: "MatcherType" });
16264
+ var RuleProbeVerdict = external_exports.enum(["safe", "quarantined"]).meta({ id: "RuleProbeVerdict" });
16200
16265
  var KeywordMatcher = external_exports.object({
16201
16266
  type: external_exports.literal("keyword"),
16202
16267
  // An empty keyword matches at every position, yielding one zero-length span
@@ -16221,9 +16286,10 @@ function matchesEmptyString(pattern, flags) {
16221
16286
  return false;
16222
16287
  }
16223
16288
  }
16289
+ var MAX_PATTERN_LENGTH = 2e3;
16224
16290
  var RegexMatcher = external_exports.object({
16225
16291
  type: external_exports.literal("regex"),
16226
- pattern: external_exports.string(),
16292
+ pattern: external_exports.string().min(1).max(MAX_PATTERN_LENGTH),
16227
16293
  flags: external_exports.string().default("gi"),
16228
16294
  captureGroup: external_exports.number().int().nonnegative().optional()
16229
16295
  }).refine((v) => isValidRegex(v.pattern, v.flags), {
@@ -16344,6 +16410,12 @@ var PolicyBundle = external_exports.object({
16344
16410
  // on-disk caches — that omit the field still parse; consumers read
16345
16411
  // `bundle.exceptions ?? []`.
16346
16412
  exceptions: external_exports.array(ExceptionBundleEntry).optional(),
16413
+ // Installed pack version, keyed by ruleId, for rules in `rules` that came
16414
+ // from a versioned installed pack. Optional so older backends — and older
16415
+ // on-disk caches — that omit the field still parse; consumers fall back to
16416
+ // the rule's own spec version. NOT the bundle version above — see
16417
+ // installedRuleset's ruleVersions for the source of truth.
16418
+ ruleVersions: external_exports.record(external_exports.string(), external_exports.string()).optional(),
16347
16419
  customKeywords: external_exports.array(external_exports.string()),
16348
16420
  fetchedAt: external_exports.iso.datetime()
16349
16421
  }).meta({ id: "PolicyBundle" });
@@ -16790,6 +16862,212 @@ function buildDetectionsList(summaries, query) {
16790
16862
  return { counts, items: filtered.map(summaryToDetectionListItem) };
16791
16863
  }
16792
16864
 
16865
+ // ../../packages/schema/src/zod/shares.ts
16866
+ var DestinationKind = external_exports.enum(["provider", "internal", "external", "ip"]).meta({ id: "DestinationKind" });
16867
+ var Transport = external_exports.enum(["https", "http", "sftp", "grpc", "smtp", "ws", "wss"]).meta({ id: "Transport" });
16868
+ var DataClass = external_exports.enum(["secrets", "pii", "customer", "source", "telemetry", "logs", "metrics", "none"]).meta({ id: "DataClass" });
16869
+ var DATA_CLASS_ORDER = DataClass.options;
16870
+ var ShareTrustLevel = external_exports.enum(["recognized", "internal", "unverified", "ip"]).meta({ id: "ShareTrustLevel" });
16871
+ var EgressDecision = external_exports.enum(["allow", "block"]).meta({ id: "EgressDecision" });
16872
+ var EgressStatus = external_exports.enum(["allowed", "blocked", "review"]).meta({ id: "EgressStatus" });
16873
+ var ReviewReason = external_exports.enum(["raw_ip", "unverified_domain", "plaintext_transport"]).meta({ id: "ReviewReason" });
16874
+ var HttpMethod = external_exports.enum(["GET", "POST", "PUT", "DELETE", "SDK", "REF"]).meta({ id: "HttpMethod" });
16875
+ var ReviewInfo = external_exports.object({
16876
+ needsReview: external_exports.boolean(),
16877
+ reasons: external_exports.array(ReviewReason)
16878
+ }).meta({ id: "ReviewInfo" });
16879
+ var DestinationNetwork = external_exports.object({
16880
+ port: external_exports.number().int().nullable(),
16881
+ geo: external_exports.string().nullable(),
16882
+ ptr: external_exports.string().nullable()
16883
+ }).meta({ id: "DestinationNetwork" });
16884
+ var EndpointSummary = external_exports.object({
16885
+ id: external_exports.string(),
16886
+ method: HttpMethod,
16887
+ transport: Transport,
16888
+ url: external_exports.string(),
16889
+ template: external_exports.boolean(),
16890
+ dataClass: DataClass,
16891
+ lastSeen: external_exports.iso.datetime(),
16892
+ callSiteCount: external_exports.number().int().nonnegative()
16893
+ }).meta({ id: "EndpointSummary" });
16894
+ var CallSite = external_exports.object({
16895
+ id: external_exports.string(),
16896
+ project: external_exports.string(),
16897
+ file: external_exports.string(),
16898
+ line: external_exports.number().int().nonnegative(),
16899
+ snippet: external_exports.string(),
16900
+ dynamic: external_exports.boolean(),
16901
+ vendored: external_exports.boolean(),
16902
+ /** Deep-link to the Inventory project, when the repo is governed there. */
16903
+ projectId: external_exports.string().nullable()
16904
+ }).meta({ id: "CallSite" });
16905
+ var EndpointWithSites = EndpointSummary.extend({
16906
+ sites: external_exports.array(CallSite)
16907
+ }).meta({ id: "EndpointWithSites" });
16908
+ var ShareDestinationSummary = external_exports.object({
16909
+ id: external_exports.string(),
16910
+ kind: DestinationKind,
16911
+ name: external_exports.string(),
16912
+ host: external_exports.string(),
16913
+ category: external_exports.string(),
16914
+ trust: ShareTrustLevel,
16915
+ /** Effective state (decision applied over the trust default). */
16916
+ status: EgressStatus,
16917
+ /** True when an egress decision override differs from the trust default. */
16918
+ isCustom: external_exports.boolean(),
16919
+ lastSeen: external_exports.iso.datetime(),
16920
+ endpointCount: external_exports.number().int().nonnegative(),
16921
+ callSiteCount: external_exports.number().int().nonnegative(),
16922
+ transports: external_exports.array(Transport),
16923
+ /** Most-sensitive first. */
16924
+ dataClasses: external_exports.array(DataClass),
16925
+ review: ReviewInfo,
16926
+ /** Non-provider hosts only; null for providers. */
16927
+ network: DestinationNetwork.nullable(),
16928
+ /** Embedded for inline expansion — no call sites here. */
16929
+ endpoints: external_exports.array(EndpointSummary)
16930
+ }).meta({ id: "ShareDestinationSummary" });
16931
+ var ShareDestinationDetail = ShareDestinationSummary.omit({
16932
+ endpointCount: true,
16933
+ callSiteCount: true,
16934
+ endpoints: true
16935
+ }).extend({
16936
+ /** Ownership/geo rationale; null for providers. */
16937
+ note: external_exports.string().nullable(),
16938
+ endpoints: external_exports.array(EndpointWithSites)
16939
+ }).meta({ id: "ShareDestinationDetail" });
16940
+ var ReviewDestination = external_exports.object({
16941
+ id: external_exports.string(),
16942
+ kind: DestinationKind,
16943
+ name: external_exports.string(),
16944
+ /** Registrable host — lets the strip derive the provider lettermark, as the register does. */
16945
+ host: external_exports.string(),
16946
+ trust: ShareTrustLevel,
16947
+ status: EgressStatus,
16948
+ review: ReviewInfo,
16949
+ topDataClass: DataClass,
16950
+ callSiteCount: external_exports.number().int().nonnegative(),
16951
+ lastSeen: external_exports.iso.datetime()
16952
+ }).meta({ id: "ReviewDestination" });
16953
+ var ShareDestinationGroup = external_exports.object({
16954
+ kind: DestinationKind,
16955
+ total: external_exports.number().int().nonnegative(),
16956
+ items: external_exports.array(ShareDestinationSummary)
16957
+ }).meta({ id: "ShareDestinationGroup" });
16958
+ var ListShareDestinationsResponse = external_exports.object({ groups: external_exports.array(ShareDestinationGroup) }).meta({ id: "ListShareDestinationsResponse" });
16959
+ var NeedsReviewResponse = external_exports.object({ items: external_exports.array(ReviewDestination) }).meta({ id: "NeedsReviewResponse" });
16960
+ var SharesStats = external_exports.object({
16961
+ destinations: external_exports.number().int().nonnegative(),
16962
+ endpoints: external_exports.number().int().nonnegative(),
16963
+ callSites: external_exports.number().int().nonnegative(),
16964
+ needsReview: external_exports.number().int().nonnegative(),
16965
+ insecure: external_exports.number().int().nonnegative(),
16966
+ byKind: external_exports.object({
16967
+ provider: external_exports.number().int().nonnegative(),
16968
+ internal: external_exports.number().int().nonnegative(),
16969
+ external: external_exports.number().int().nonnegative(),
16970
+ ip: external_exports.number().int().nonnegative()
16971
+ }),
16972
+ byTrust: external_exports.object({
16973
+ recognized: external_exports.number().int().nonnegative(),
16974
+ internal: external_exports.number().int().nonnegative(),
16975
+ unverified: external_exports.number().int().nonnegative(),
16976
+ ip: external_exports.number().int().nonnegative()
16977
+ })
16978
+ }).meta({ id: "SharesStats" });
16979
+ var SetEgressDecisionBody = external_exports.object({
16980
+ /** `null` clears the override — reverts to the trust default, isCustom false. */
16981
+ decision: EgressDecision.nullable()
16982
+ }).meta({ id: "SetEgressDecisionBody" });
16983
+ var SetEgressDecisionResponse = external_exports.object({ destination: ShareDestinationSummary }).meta({ id: "SetEgressDecisionResponse" });
16984
+ var ListShareDestinationsQuery = external_exports.object({
16985
+ /** Case-insensitive match over destination name/category, endpoint url, call-site project/file. */
16986
+ q: external_exports.string().optional(),
16987
+ /** Repeatable. Restrict to these DestinationKind values; absent means all kinds. */
16988
+ kind: external_exports.array(DestinationKind).optional(),
16989
+ /** Reserved for future grouping modes; only 'destination' is supported today. */
16990
+ groupBy: external_exports.enum(["destination"]).default("destination"),
16991
+ /**
16992
+ * When true, return a flat severity-ordered `items[]` instead of `groups`.
16993
+ * Uses `z.stringbool()` (NOT `z.coerce.boolean()` — `Boolean(str)` is true for
16994
+ * any non-empty string, so `?review=false`/`?review=0` would wrongly coerce
16995
+ * to `true`). `z.stringbool()` parses true/1/yes vs false/0/no correctly.
16996
+ */
16997
+ review: external_exports.stringbool().default(false)
16998
+ });
16999
+ var ExportSharesQuery = external_exports.object({
17000
+ format: external_exports.enum(["csv", "json"]).default("csv"),
17001
+ q: external_exports.string().optional(),
17002
+ kind: external_exports.array(DestinationKind).optional()
17003
+ });
17004
+
17005
+ // ../../packages/schema/src/zod/egress-extraction.ts
17006
+ var EgressEcosystem = external_exports.enum(["npm", "pypi", "go", "maven", "rubygems", "cargo", "composer", "nuget"]).meta({ id: "EgressEcosystem" });
17007
+ var ProviderRegistryEntry = external_exports.object({
17008
+ id: external_exports.string(),
17009
+ name: external_exports.string(),
17010
+ category: external_exports.string(),
17011
+ /** Suffix-matched: 'stripe.com' matches api.stripe.com, never evilstripe.com. */
17012
+ hostSuffixes: external_exports.array(external_exports.string()).min(1),
17013
+ /** Canonical API base URL recorded for manifest-derived (method 'SDK') endpoints. */
17014
+ apiBase: external_exports.string(),
17015
+ /** Most-sensitive first; index 0 becomes the endpoint dataClass. */
17016
+ defaultDataClasses: external_exports.array(DataClass).min(1),
17017
+ /** SDK identifiers per ecosystem ('go' prefix-matched by path, 'maven' by group-id prefix). */
17018
+ sdks: external_exports.partialRecord(EgressEcosystem, external_exports.array(external_exports.string()))
17019
+ }).meta({ id: "ProviderRegistryEntry" });
17020
+ var EgressCallSiteHit = external_exports.object({
17021
+ file: external_exports.string(),
17022
+ line: external_exports.number().int().positive(),
17023
+ snippet: external_exports.string(),
17024
+ dynamic: external_exports.boolean(),
17025
+ vendored: external_exports.boolean()
17026
+ }).meta({ id: "EgressCallSiteHit" });
17027
+ var ResolvedEgressHit = external_exports.object({
17028
+ host: external_exports.string(),
17029
+ kind: DestinationKind,
17030
+ name: external_exports.string(),
17031
+ category: external_exports.string(),
17032
+ trust: ShareTrustLevel,
17033
+ network: DestinationNetwork.nullable(),
17034
+ method: HttpMethod,
17035
+ transport: Transport,
17036
+ url: external_exports.string(),
17037
+ template: external_exports.boolean(),
17038
+ dataClass: DataClass,
17039
+ site: EgressCallSiteHit
17040
+ }).meta({ id: "ResolvedEgressHit" });
17041
+ var EgressReconcile = external_exports.discriminatedUnion("mode", [
17042
+ external_exports.object({ mode: external_exports.literal("walk"), walkedPrefix: external_exports.string() }),
17043
+ external_exports.object({
17044
+ mode: external_exports.literal("ledger"),
17045
+ scannedFiles: external_exports.array(external_exports.string()),
17046
+ deletedFiles: external_exports.array(external_exports.string())
17047
+ })
17048
+ ]).meta({ id: "EgressReconcile" });
17049
+ var RecordProjectEgressInput = external_exports.object({
17050
+ /** Stable reconcile key: 'git:<repo identity>' or 'path:<abs root>' (non-git). */
17051
+ projectKey: external_exports.string().min(1),
17052
+ /** Display name only — never keys reconciliation. */
17053
+ project: external_exports.string(),
17054
+ projectId: external_exports.string().nullable(),
17055
+ reconcile: EgressReconcile,
17056
+ hits: external_exports.array(ResolvedEgressHit)
17057
+ }).meta({ id: "RecordProjectEgressInput" });
17058
+ var EgressWriteSummary = external_exports.object({
17059
+ destinations: external_exports.number().int().nonnegative(),
17060
+ endpoints: external_exports.number().int().nonnegative(),
17061
+ callSites: external_exports.number().int().nonnegative(),
17062
+ truncated: external_exports.boolean(),
17063
+ /**
17064
+ * Files the cap dropped whole. Their stored rows were left untouched, so a
17065
+ * ledger-keeping caller must withhold their ledger entries and read them
17066
+ * again next scan.
17067
+ */
17068
+ droppedFiles: external_exports.array(external_exports.string()).default([])
17069
+ }).meta({ id: "EgressWriteSummary" });
17070
+
16793
17071
  // ../../packages/schema/src/zod/findings-group-build.ts
16794
17072
  function toApiAction(dbVal) {
16795
17073
  const map2 = {
@@ -16937,6 +17215,15 @@ function groupActions(g) {
16937
17215
  actionsCache.set(g, actions);
16938
17216
  return actions;
16939
17217
  }
17218
+ function countInstancesByStatus(statusInputs, statuses) {
17219
+ const statusSet = new Set(statuses);
17220
+ let sum = 0;
17221
+ for (const input of statusInputs) {
17222
+ if (input.count === void 0) return null;
17223
+ if (statusSet.has(deriveFindingStatus(input))) sum += input.count;
17224
+ }
17225
+ return sum;
17226
+ }
16940
17227
  function applyFindingFilters(groups, opts) {
16941
17228
  let filtered = groups;
16942
17229
  if (opts.severity && opts.severity.length > 0) {
@@ -16955,6 +17242,10 @@ function applyFindingFilters(groups, opts) {
16955
17242
  const subtypeSet = new Set(opts.subtype);
16956
17243
  filtered = filtered.filter((g) => subtypeSet.has(g.subtype));
16957
17244
  }
17245
+ if (opts.statuses && opts.statuses.length > 0) {
17246
+ const statusSet = new Set(opts.statuses);
17247
+ filtered = filtered.filter((g) => g.status !== void 0 && statusSet.has(g.status));
17248
+ }
16958
17249
  if (opts.q) {
16959
17250
  const q = opts.q.toLowerCase();
16960
17251
  filtered = filtered.filter((g) => groupHaystack(g).includes(q));
@@ -16976,6 +17267,7 @@ function computeFindingFacets(allGroups, opts) {
16976
17267
  const forSeverity = applyFindingFilters(allGroups, {
16977
17268
  providers: opts.providers,
16978
17269
  actions: opts.actions,
17270
+ statuses: opts.statuses,
16979
17271
  q: opts.q,
16980
17272
  subtype: opts.subtype
16981
17273
  });
@@ -16985,6 +17277,7 @@ function computeFindingFacets(allGroups, opts) {
16985
17277
  }
16986
17278
  const forProvider = applyFindingFilters(allGroups, {
16987
17279
  actions: opts.actions,
17280
+ statuses: opts.statuses,
16988
17281
  q: opts.q,
16989
17282
  subtype: opts.subtype,
16990
17283
  severity: opts.severity
@@ -16995,6 +17288,7 @@ function computeFindingFacets(allGroups, opts) {
16995
17288
  }
16996
17289
  const forAction = applyFindingFilters(allGroups, {
16997
17290
  providers: opts.providers,
17291
+ statuses: opts.statuses,
16998
17292
  q: opts.q,
16999
17293
  subtype: opts.subtype,
17000
17294
  severity: opts.severity
@@ -17006,17 +17300,30 @@ function computeFindingFacets(allGroups, opts) {
17006
17300
  const forSubtype = applyFindingFilters(allGroups, {
17007
17301
  providers: opts.providers,
17008
17302
  actions: opts.actions,
17303
+ statuses: opts.statuses,
17009
17304
  q: opts.q,
17010
17305
  severity: opts.severity
17011
17306
  });
17012
17307
  const subtypeMap = /* @__PURE__ */ new Map();
17013
17308
  for (const g of forSubtype) subtypeMap.set(g.subtype, (subtypeMap.get(g.subtype) ?? 0) + 1);
17309
+ const forStatus = applyFindingFilters(allGroups, {
17310
+ providers: opts.providers,
17311
+ actions: opts.actions,
17312
+ q: opts.q,
17313
+ subtype: opts.subtype,
17314
+ severity: opts.severity
17315
+ });
17316
+ const statusMap = /* @__PURE__ */ new Map();
17317
+ for (const g of forStatus) {
17318
+ if (g.status !== void 0) statusMap.set(g.status, (statusMap.get(g.status) ?? 0) + 1);
17319
+ }
17014
17320
  const toItems = (m) => [...m.entries()].map(([value, count]) => ({ value, count }));
17015
17321
  return {
17016
17322
  severity: toItems(severityMap),
17017
17323
  provider: toItems(providerMap),
17018
17324
  action: toItems(actionMap),
17019
- subtype: toItems(subtypeMap)
17325
+ subtype: toItems(subtypeMap),
17326
+ status: toItems(statusMap)
17020
17327
  };
17021
17328
  }
17022
17329
 
@@ -17051,10 +17358,14 @@ var PatchInstalledPackRequest = external_exports.object({
17051
17358
  }).meta({ id: "PatchInstalledPackRequest" });
17052
17359
 
17053
17360
  // ../../packages/schema/src/zod/local.ts
17054
- var WORKSPACE_SETTINGS_SPEC_VERSION = 2;
17361
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 4;
17055
17362
  var RunMode = external_exports.enum(["standalone"]);
17056
17363
  var SimpleDetectionPolicy = external_exports.enum(["redact", "warn"]);
17057
17364
  var HistoricalAccess = external_exports.enum(["full", "session-only"]);
17365
+ var ModelJudgeConsent = external_exports.object({
17366
+ acknowledgedAt: external_exports.iso.datetime(),
17367
+ payloadVersion: external_exports.number().int().positive()
17368
+ });
17058
17369
  var WorkspaceSettings = external_exports.object({
17059
17370
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
17060
17371
  // Settings files written by earlier releases may carry the retired 'attached'
@@ -17066,38 +17377,20 @@ var WorkspaceSettings = external_exports.object({
17066
17377
  policy: SimpleDetectionPolicy.default("redact"),
17067
17378
  // Consent for scanning pre-install surfaces; opt-in (see HistoricalAccess).
17068
17379
  historicalAccess: HistoricalAccess.default("session-only"),
17380
+ // In-place egress extraction on the scan paths; disable to stop all Data
17381
+ // Shares writes.
17382
+ dataSharesInPlace: external_exports.boolean().default(true),
17069
17383
  // Absent until /aka:setup completes; its presence is what "onboarded" means.
17070
- onboardedAt: external_exports.iso.datetime().optional()
17384
+ onboardedAt: external_exports.iso.datetime().optional(),
17385
+ // Records that the user consented to sending findings to the model API for
17386
+ // the /aka:setup judge, along with the payload-shape version they agreed to.
17387
+ // Absent until granted; a stale payloadVersion means the consent no longer
17388
+ // covers the current payload and must be re-granted.
17389
+ modelJudgeConsent: ModelJudgeConsent.optional()
17071
17390
  });
17072
17391
  function defaultWorkspaceSettings() {
17073
17392
  return WorkspaceSettings.parse({});
17074
17393
  }
17075
- function toEventRow(event) {
17076
- return {
17077
- id: event.id,
17078
- sourceTool: event.sourceTool,
17079
- kind: event.kind,
17080
- occurredAt: isoToEpochMillis(event.occurredAt),
17081
- contentHash: event.contentHash,
17082
- content: event.content,
17083
- metadata: event.metadata ? JSON.stringify(event.metadata) : null
17084
- };
17085
- }
17086
- function toFindingRow(finding) {
17087
- return {
17088
- id: finding.id,
17089
- eventId: finding.eventId,
17090
- ruleId: finding.ruleId,
17091
- category: finding.category,
17092
- severity: finding.severity,
17093
- spanStart: finding.span.start,
17094
- spanEnd: finding.span.end,
17095
- maskedMatch: finding.maskedMatch,
17096
- actionTaken: finding.actionTaken,
17097
- confidence: finding.confidence,
17098
- findingKey: finding.findingKey ?? null
17099
- };
17100
- }
17101
17394
  function toInventoryRow(input, id, now) {
17102
17395
  return {
17103
17396
  id,
@@ -17167,7 +17460,42 @@ function toInspectionFindingRow(input) {
17167
17460
  spanEnd: input.span.end,
17168
17461
  maskedMatch: input.maskedMatch,
17169
17462
  actionTaken: input.actionTaken,
17170
- confidence: input.confidence
17463
+ confidence: input.confidence,
17464
+ findingKey: input.findingKey ?? null,
17465
+ firstDetectedAt: input.firstDetectedAt ? isoToEpochMillis(input.firstDetectedAt) : null
17466
+ };
17467
+ }
17468
+ function toCaptureAttributes(event) {
17469
+ const metadata = event.metadata;
17470
+ return {
17471
+ source_tool: event.sourceTool,
17472
+ ...metadata?.repo !== void 0 ? { repo: metadata.repo } : {},
17473
+ ...metadata?.filePath !== void 0 ? { file_path: metadata.filePath } : {},
17474
+ ...metadata?.toolName !== void 0 ? { tool_name: metadata.toolName } : {},
17475
+ ...metadata?.gitignored !== void 0 ? { gitignored: metadata.gitignored } : {},
17476
+ ...metadata?.wholeFile !== void 0 ? { whole_file: metadata.wholeFile } : {},
17477
+ ...metadata?.correlationId !== void 0 ? { correlation_id: metadata.correlationId } : {},
17478
+ ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
17479
+ ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
17480
+ // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
17481
+ // has ever populated either), but every legacy metadata key still rides
17482
+ // the bag rather than being silently dropped — CaptureAttributes'
17483
+ // `.catchall(z.unknown())` carries the long tail.
17484
+ ...metadata?.model !== void 0 ? { model: metadata.model } : {},
17485
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
17486
+ };
17487
+ }
17488
+ function captureDefinitionVersion(finding) {
17489
+ return `capture/${finding.category}/${finding.severity}`;
17490
+ }
17491
+ function toCaptureDefinitionInput(finding) {
17492
+ return {
17493
+ ruleId: finding.ruleId,
17494
+ version: captureDefinitionVersion(finding),
17495
+ name: finding.ruleId,
17496
+ category: finding.category,
17497
+ severity: finding.severity,
17498
+ definition: JSON.stringify({ ruleId: finding.ruleId })
17171
17499
  };
17172
17500
  }
17173
17501
 
@@ -17549,145 +17877,6 @@ var SetupHandoffOffer = external_exports.object({
17549
17877
  path: ["liveKeys"]
17550
17878
  });
17551
17879
 
17552
- // ../../packages/schema/src/zod/shares.ts
17553
- var DestinationKind = external_exports.enum(["provider", "internal", "ip"]).meta({ id: "DestinationKind" });
17554
- var Transport = external_exports.enum(["https", "http", "sftp", "grpc", "smtp"]).meta({ id: "Transport" });
17555
- var DataClass = external_exports.enum(["secrets", "pii", "customer", "source", "telemetry", "logs", "metrics", "none"]).meta({ id: "DataClass" });
17556
- var DATA_CLASS_ORDER = DataClass.options;
17557
- var ShareTrustLevel = external_exports.enum(["recognized", "internal", "unverified", "ip"]).meta({ id: "ShareTrustLevel" });
17558
- var EgressDecision = external_exports.enum(["allow", "block"]).meta({ id: "EgressDecision" });
17559
- var EgressStatus = external_exports.enum(["allowed", "blocked", "review"]).meta({ id: "EgressStatus" });
17560
- var ReviewReason = external_exports.enum(["raw_ip", "unverified_domain", "plaintext_transport"]).meta({ id: "ReviewReason" });
17561
- var HttpMethod = external_exports.enum(["GET", "POST", "PUT", "DELETE"]).meta({ id: "HttpMethod" });
17562
- var ReviewInfo = external_exports.object({
17563
- needsReview: external_exports.boolean(),
17564
- reasons: external_exports.array(ReviewReason)
17565
- }).meta({ id: "ReviewInfo" });
17566
- var DestinationNetwork = external_exports.object({
17567
- port: external_exports.number().int().nullable(),
17568
- geo: external_exports.string().nullable(),
17569
- ptr: external_exports.string().nullable()
17570
- }).meta({ id: "DestinationNetwork" });
17571
- var EndpointSummary = external_exports.object({
17572
- id: external_exports.string(),
17573
- method: HttpMethod,
17574
- transport: Transport,
17575
- url: external_exports.string(),
17576
- template: external_exports.boolean(),
17577
- dataClass: DataClass,
17578
- lastSeen: external_exports.iso.datetime(),
17579
- callSiteCount: external_exports.number().int().nonnegative()
17580
- }).meta({ id: "EndpointSummary" });
17581
- var CallSite = external_exports.object({
17582
- id: external_exports.string(),
17583
- project: external_exports.string(),
17584
- file: external_exports.string(),
17585
- line: external_exports.number().int().nonnegative(),
17586
- snippet: external_exports.string(),
17587
- dynamic: external_exports.boolean(),
17588
- vendored: external_exports.boolean(),
17589
- /** Deep-link to the Inventory project, when the repo is governed there. */
17590
- projectId: external_exports.string().nullable()
17591
- }).meta({ id: "CallSite" });
17592
- var EndpointWithSites = EndpointSummary.extend({
17593
- sites: external_exports.array(CallSite)
17594
- }).meta({ id: "EndpointWithSites" });
17595
- var ShareDestinationSummary = external_exports.object({
17596
- id: external_exports.string(),
17597
- kind: DestinationKind,
17598
- name: external_exports.string(),
17599
- host: external_exports.string(),
17600
- category: external_exports.string(),
17601
- trust: ShareTrustLevel,
17602
- /** Effective state (decision applied over the trust default). */
17603
- status: EgressStatus,
17604
- /** True when an egress decision override differs from the trust default. */
17605
- isCustom: external_exports.boolean(),
17606
- lastSeen: external_exports.iso.datetime(),
17607
- endpointCount: external_exports.number().int().nonnegative(),
17608
- callSiteCount: external_exports.number().int().nonnegative(),
17609
- transports: external_exports.array(Transport),
17610
- /** Most-sensitive first. */
17611
- dataClasses: external_exports.array(DataClass),
17612
- review: ReviewInfo,
17613
- /** Non-provider hosts only; null for providers. */
17614
- network: DestinationNetwork.nullable(),
17615
- /** Embedded for inline expansion — no call sites here. */
17616
- endpoints: external_exports.array(EndpointSummary)
17617
- }).meta({ id: "ShareDestinationSummary" });
17618
- var ShareDestinationDetail = ShareDestinationSummary.omit({
17619
- endpointCount: true,
17620
- callSiteCount: true,
17621
- endpoints: true
17622
- }).extend({
17623
- /** Ownership/geo rationale; null for providers. */
17624
- note: external_exports.string().nullable(),
17625
- endpoints: external_exports.array(EndpointWithSites)
17626
- }).meta({ id: "ShareDestinationDetail" });
17627
- var ReviewDestination = external_exports.object({
17628
- id: external_exports.string(),
17629
- kind: DestinationKind,
17630
- name: external_exports.string(),
17631
- /** Registrable host — lets the strip derive the provider lettermark, as the register does. */
17632
- host: external_exports.string(),
17633
- trust: ShareTrustLevel,
17634
- status: EgressStatus,
17635
- review: ReviewInfo,
17636
- topDataClass: DataClass,
17637
- callSiteCount: external_exports.number().int().nonnegative(),
17638
- lastSeen: external_exports.iso.datetime()
17639
- }).meta({ id: "ReviewDestination" });
17640
- var ShareDestinationGroup = external_exports.object({
17641
- kind: DestinationKind,
17642
- total: external_exports.number().int().nonnegative(),
17643
- items: external_exports.array(ShareDestinationSummary)
17644
- }).meta({ id: "ShareDestinationGroup" });
17645
- var ListShareDestinationsResponse = external_exports.object({ groups: external_exports.array(ShareDestinationGroup) }).meta({ id: "ListShareDestinationsResponse" });
17646
- var NeedsReviewResponse = external_exports.object({ items: external_exports.array(ReviewDestination) }).meta({ id: "NeedsReviewResponse" });
17647
- var SharesStats = external_exports.object({
17648
- destinations: external_exports.number().int().nonnegative(),
17649
- endpoints: external_exports.number().int().nonnegative(),
17650
- callSites: external_exports.number().int().nonnegative(),
17651
- needsReview: external_exports.number().int().nonnegative(),
17652
- insecure: external_exports.number().int().nonnegative(),
17653
- byKind: external_exports.object({
17654
- provider: external_exports.number().int().nonnegative(),
17655
- internal: external_exports.number().int().nonnegative(),
17656
- ip: external_exports.number().int().nonnegative()
17657
- }),
17658
- byTrust: external_exports.object({
17659
- recognized: external_exports.number().int().nonnegative(),
17660
- internal: external_exports.number().int().nonnegative(),
17661
- unverified: external_exports.number().int().nonnegative(),
17662
- ip: external_exports.number().int().nonnegative()
17663
- })
17664
- }).meta({ id: "SharesStats" });
17665
- var SetEgressDecisionBody = external_exports.object({
17666
- /** `null` clears the override — reverts to the trust default, isCustom false. */
17667
- decision: EgressDecision.nullable()
17668
- }).meta({ id: "SetEgressDecisionBody" });
17669
- var SetEgressDecisionResponse = external_exports.object({ destination: ShareDestinationSummary }).meta({ id: "SetEgressDecisionResponse" });
17670
- var ListShareDestinationsQuery = external_exports.object({
17671
- /** Case-insensitive match over destination name/category, endpoint url, call-site project/file. */
17672
- q: external_exports.string().optional(),
17673
- /** Repeatable. Restrict to these DestinationKind values; absent means all kinds. */
17674
- kind: external_exports.array(DestinationKind).optional(),
17675
- /** Reserved for future grouping modes; only 'destination' is supported today. */
17676
- groupBy: external_exports.enum(["destination"]).default("destination"),
17677
- /**
17678
- * When true, return a flat severity-ordered `items[]` instead of `groups`.
17679
- * Uses `z.stringbool()` (NOT `z.coerce.boolean()` — `Boolean(str)` is true for
17680
- * any non-empty string, so `?review=false`/`?review=0` would wrongly coerce
17681
- * to `true`). `z.stringbool()` parses true/1/yes vs false/0/no correctly.
17682
- */
17683
- review: external_exports.stringbool().default(false)
17684
- });
17685
- var ExportSharesQuery = external_exports.object({
17686
- format: external_exports.enum(["csv", "json"]).default("csv"),
17687
- q: external_exports.string().optional(),
17688
- kind: external_exports.array(DestinationKind).optional()
17689
- });
17690
-
17691
17880
  // ../../packages/schema/src/zod/shares-access.ts
17692
17881
  var ALLOWED_BY_DEFAULT_TRUST = /* @__PURE__ */ new Set(["recognized", "internal"]);
17693
17882
  function trustDefaultStatus(trust) {
@@ -17707,7 +17896,7 @@ function deriveReviewReasons(trust, transports) {
17707
17896
  const reasons = [];
17708
17897
  if (trust === "ip") reasons.push("raw_ip");
17709
17898
  if (trust === "unverified") reasons.push("unverified_domain");
17710
- if (transports.includes("http")) reasons.push("plaintext_transport");
17899
+ if (transports.includes("http") || transports.includes("ws")) reasons.push("plaintext_transport");
17711
17900
  return reasons;
17712
17901
  }
17713
17902
  function buildReviewInfo(trust, transports) {
@@ -17734,6 +17923,48 @@ function reviewSeverityRank(reasons) {
17734
17923
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
17735
17924
  }
17736
17925
 
17926
+ // ../../packages/persistence/src/ids.ts
17927
+ import { createHash } from "crypto";
17928
+ function sha256Hex(input) {
17929
+ return createHash("sha256").update(input).digest("hex");
17930
+ }
17931
+ function inventoryId(objectType, identityKey) {
17932
+ return sha256Hex(canonicalIdentity(["inventory", objectType, identityKey]));
17933
+ }
17934
+ function sourceProjectId(url2) {
17935
+ return sha256Hex(canonicalIdentity(["source_project", url2]));
17936
+ }
17937
+ function classifiedDataId(cls) {
17938
+ return sha256Hex(canonicalIdentity(["classified_data", cls]));
17939
+ }
17940
+ function inspectionDefinitionId(ruleId, version2) {
17941
+ return sha256Hex(canonicalIdentity(["inspection_definition", ruleId, version2]));
17942
+ }
17943
+ function llmCallId(sessionId, messageId) {
17944
+ return sha256Hex(canonicalIdentity(["audit_event_llm_call", sessionId, messageId]));
17945
+ }
17946
+ function toolCallId(sessionId, toolUseId) {
17947
+ return sha256Hex(canonicalIdentity(["audit_event_tool_call", sessionId, toolUseId]));
17948
+ }
17949
+ function inspectionFindingId(auditEventId, ruleId, spanStart, spanEnd) {
17950
+ return sha256Hex(
17951
+ canonicalIdentity([
17952
+ "inspection_finding",
17953
+ auditEventId,
17954
+ ruleId,
17955
+ String(spanStart),
17956
+ String(spanEnd)
17957
+ ])
17958
+ );
17959
+ }
17960
+ var NO_SESSION = "no_session";
17961
+ var NO_PATH = "no_path";
17962
+ function captureId(sessionId, contentHash, filePath = null) {
17963
+ return sha256Hex(
17964
+ canonicalIdentity(["capture", sessionId ?? NO_SESSION, contentHash, filePath ?? NO_PATH])
17965
+ );
17966
+ }
17967
+
17737
17968
  // ../../packages/persistence/src/internal/sql-text.ts
17738
17969
  function escapeLikePattern(s) {
17739
17970
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -17830,39 +18061,81 @@ function evidenceExists(db, object2) {
17830
18061
  return schemaObjectExists(db, "table", object2.name);
17831
18062
  }
17832
18063
 
17833
- // ../../packages/persistence/src/ids.ts
17834
- import { createHash } from "crypto";
17835
- function sha256Hex(input) {
17836
- return createHash("sha256").update(input).digest("hex");
18064
+ // ../../packages/persistence/src/internal/rows.ts
18065
+ function allRows(stmt, params) {
18066
+ if (params === void 0) return stmt.all();
18067
+ if (Array.isArray(params)) return stmt.all(...params);
18068
+ return stmt.all(params);
17837
18069
  }
17838
- function inventoryId(objectType, identityKey) {
17839
- return sha256Hex(canonicalIdentity(["inventory", objectType, identityKey]));
18070
+ function getRow(stmt, params) {
18071
+ if (params === void 0) return stmt.get();
18072
+ if (Array.isArray(params)) return stmt.get(...params);
18073
+ return stmt.get(params);
17840
18074
  }
17841
- function sourceProjectId(url2) {
17842
- return sha256Hex(canonicalIdentity(["source_project", url2]));
18075
+ function intToBool(raw) {
18076
+ return raw === 1 || raw === true;
17843
18077
  }
17844
- function classifiedDataId(cls) {
17845
- return sha256Hex(canonicalIdentity(["classified_data", cls]));
18078
+ function boolToInt(b) {
18079
+ return b ? 1 : 0;
17846
18080
  }
17847
- function inspectionDefinitionId(ruleId, version2) {
17848
- return sha256Hex(canonicalIdentity(["inspection_definition", ruleId, version2]));
18081
+ function bindParams(row) {
18082
+ const out = {};
18083
+ for (const [key, value] of Object.entries(row)) {
18084
+ out[key] = value === void 0 ? null : value;
18085
+ }
18086
+ return out;
17849
18087
  }
17850
- function llmCallId(sessionId, messageId) {
17851
- return sha256Hex(canonicalIdentity(["audit_event_llm_call", sessionId, messageId]));
18088
+ function countScalar(db, sql, params) {
18089
+ return getRow(db.prepare(sql), params)?.n ?? 0;
17852
18090
  }
17853
- function toolCallId(sessionId, toolUseId) {
17854
- return sha256Hex(canonicalIdentity(["audit_event_tool_call", sessionId, toolUseId]));
18091
+ function countBy(db, sql, params) {
18092
+ const map2 = /* @__PURE__ */ new Map();
18093
+ for (const row of allRows(db.prepare(sql), params)) {
18094
+ map2.set(row.k, row.n);
18095
+ }
18096
+ return map2;
17855
18097
  }
17856
- function inspectionFindingId(auditEventId, definitionId, spanStart, spanEnd) {
17857
- return sha256Hex(
17858
- canonicalIdentity([
17859
- "inspection_finding",
17860
- auditEventId,
17861
- definitionId,
17862
- String(spanStart),
17863
- String(spanEnd)
17864
- ])
17865
- );
18098
+ function mapRowsTolerant(rows, map2) {
18099
+ const out = [];
18100
+ for (const row of rows) {
18101
+ try {
18102
+ out.push(map2(row));
18103
+ } catch {
18104
+ }
18105
+ }
18106
+ return out;
18107
+ }
18108
+
18109
+ // ../../packages/persistence/src/paths.ts
18110
+ import { chmodSync, lstatSync, mkdirSync, renameSync, rmSync, writeFileSync } from "fs";
18111
+ var DATA_DIR_MODE = 448;
18112
+ var DATA_FILE_MODE = 384;
18113
+ var DB_FILENAME = "aka.db";
18114
+ function chmodBestEffort(path, mode) {
18115
+ try {
18116
+ chmodSync(path, mode);
18117
+ } catch {
18118
+ }
18119
+ }
18120
+ function tightenDir(dir) {
18121
+ chmodBestEffort(dir, DATA_DIR_MODE);
18122
+ }
18123
+ function ensureDataDirSync(dir) {
18124
+ mkdirSync(dir, { recursive: true, mode: DATA_DIR_MODE });
18125
+ tightenDir(dir);
18126
+ }
18127
+ function dbSidecars(file2) {
18128
+ return [`${file2}-wal`, `${file2}-shm`, `${file2}-journal`];
18129
+ }
18130
+ function tightenFile(file2) {
18131
+ try {
18132
+ if (lstatSync(file2).isSymbolicLink()) return;
18133
+ } catch {
18134
+ }
18135
+ chmodBestEffort(file2, DATA_FILE_MODE);
18136
+ }
18137
+ function tightenPerms(file2) {
18138
+ for (const path of [file2, ...dbSidecars(file2)]) chmodBestEffort(path, DATA_FILE_MODE);
17866
18139
  }
17867
18140
 
17868
18141
  // ../../packages/persistence/src/migrations.ts
@@ -17876,7 +18149,8 @@ function createdIndexName(statement) {
17876
18149
  const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
17877
18150
  return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
17878
18151
  }
17879
- function applyMigrations(db) {
18152
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
18153
+ function applyMigrations(db, file2) {
17880
18154
  const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
17881
18155
  db.exec(
17882
18156
  "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
@@ -17890,6 +18164,7 @@ function applyMigrations(db) {
17890
18164
  );
17891
18165
  for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
17892
18166
  if (applied.has(migration.tag)) continue;
18167
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
17893
18168
  const evidence = evidenceObjects(migration.sql);
17894
18169
  const present = evidence.filter((o) => evidenceExists(db, o));
17895
18170
  if (present.length > 0 && present.length < evidence.length) {
@@ -17934,13 +18209,54 @@ function applyMigrations(db) {
17934
18209
  if (legacyCount < SQLITE_MIGRATIONS.length) {
17935
18210
  db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
17936
18211
  }
17937
- ensureSyncedAtColumn(db, "events");
17938
18212
  ensureSyncedAtColumn(db, "audit_events");
17939
18213
  ensureScanLedgerTable(db);
17940
18214
  ensureBlockedDetectionsTable(db);
18215
+ ensureRuleProbeCacheTable(db);
17941
18216
  ensureWriteGateTrigger(db);
17942
18217
  ensureTokenUsageColumns(db);
17943
18218
  reconcileSourceProjectIds(db);
18219
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
18220
+ const drained = runLegacyHistoryBackfill(db);
18221
+ if (drained) applyLegacyDropMigration(db, file2);
18222
+ }
18223
+ }
18224
+ function applyLegacyDropMigration(db, file2) {
18225
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
18226
+ if (!migration) return;
18227
+ if (file2) {
18228
+ try {
18229
+ backupBeforeLegacyDrop(db, file2);
18230
+ } catch (error51) {
18231
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error51)}`);
18232
+ return;
18233
+ }
18234
+ }
18235
+ try {
18236
+ withTransaction(
18237
+ db,
18238
+ () => {
18239
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
18240
+ if (alreadyDropped) return;
18241
+ for (const statement of splitStatements(migration.sql)) {
18242
+ db.exec(statement);
18243
+ }
18244
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
18245
+ migration.tag,
18246
+ Date.now()
18247
+ );
18248
+ },
18249
+ "IMMEDIATE"
18250
+ );
18251
+ } catch (error51) {
18252
+ akaWarn(`legacy events/findings drop failed; deferring: ${String(error51)}`);
18253
+ }
18254
+ }
18255
+ function backupBeforeLegacyDrop(db, file2) {
18256
+ const backup = `${file2}.pre-drop.${String(Date.now())}.bak`;
18257
+ db.prepare("VACUUM INTO ?").run(backup);
18258
+ tightenFile(backup);
18259
+ return backup;
17944
18260
  }
17945
18261
  var TOKEN_USAGE_COLUMNS = [
17946
18262
  {
@@ -17969,6 +18285,7 @@ var TOKEN_USAGE_COLUMNS = [
17969
18285
  }
17970
18286
  ];
17971
18287
  function ensureTokenUsageColumns(db) {
18288
+ if (!schemaObjectExists(db, "table", "audit_events")) return;
17972
18289
  const existing = new Set(columnNames(db, "audit_events", { includeGenerated: true }));
17973
18290
  for (const column of TOKEN_USAGE_COLUMNS) {
17974
18291
  if (!existing.has(column.name)) {
@@ -18034,11 +18351,187 @@ function reconcileSourceProjectIds(db) {
18034
18351
  akaWarn(`source_project id reconcile failed: ${String(error51)}`);
18035
18352
  }
18036
18353
  }
18354
+ var LEGACY_BACKFILL_BATCH_SIZE = 200;
18355
+ var LEGACY_BACKFILL_MAX_ROWS_PER_CALL = 1e3;
18356
+ function getLegacyCopyWatermark(db, source) {
18357
+ const row = db.prepare("SELECT last_rowid AS lastRowid FROM legacy_copy_watermark WHERE source = ?").get(source);
18358
+ return row?.lastRowid ?? 0;
18359
+ }
18360
+ function setLegacyCopyWatermark(db, source, lastRowid) {
18361
+ db.prepare(
18362
+ `INSERT INTO legacy_copy_watermark (source, last_rowid) VALUES (?, ?)
18363
+ ON CONFLICT(source) DO UPDATE SET last_rowid = excluded.last_rowid`
18364
+ ).run(source, lastRowid);
18365
+ }
18366
+ function drainLegacyTable(db, source, selectStmt, handleRows) {
18367
+ let watermark = getLegacyCopyWatermark(db, source);
18368
+ let processed = 0;
18369
+ while (processed < LEGACY_BACKFILL_MAX_ROWS_PER_CALL) {
18370
+ const rows = selectStmt.all(watermark, LEGACY_BACKFILL_BATCH_SIZE);
18371
+ if (rows.length === 0) return true;
18372
+ withTransaction(
18373
+ db,
18374
+ () => {
18375
+ handleRows(rows);
18376
+ watermark = rows[rows.length - 1]?.rowid ?? watermark;
18377
+ setLegacyCopyWatermark(db, source, watermark);
18378
+ },
18379
+ "IMMEDIATE"
18380
+ );
18381
+ processed += rows.length;
18382
+ if (rows.length < LEGACY_BACKFILL_BATCH_SIZE) return true;
18383
+ }
18384
+ return false;
18385
+ }
18386
+ function parseLegacyEventMetadata(raw) {
18387
+ if (raw === null) return void 0;
18388
+ try {
18389
+ return JSON.parse(raw);
18390
+ } catch {
18391
+ return void 0;
18392
+ }
18393
+ }
18394
+ function toLegacyAuditAttributesJson(row) {
18395
+ return JSON.stringify(
18396
+ toCaptureAttributes({
18397
+ id: row.id,
18398
+ sourceTool: row.sourceTool,
18399
+ kind: row.kind,
18400
+ occurredAt: new Date(row.occurredAt).toISOString(),
18401
+ contentHash: row.contentHash,
18402
+ content: row.content,
18403
+ metadata: row.metadata
18404
+ })
18405
+ );
18406
+ }
18407
+ function copyLegacyEvents(db) {
18408
+ const selectStmt = db.prepare(
18409
+ `SELECT rowid AS rowid, id, source_tool AS sourceTool, kind, occurred_at AS occurredAt,
18410
+ content_hash AS contentHash, content, metadata
18411
+ FROM events WHERE rowid > ? ORDER BY rowid LIMIT ?`
18412
+ );
18413
+ const insertStmt = db.prepare(
18414
+ `INSERT OR IGNORE INTO audit_events
18415
+ (id, parent_id, root_session_id, event_type, started_at, content, content_hash, attributes)
18416
+ VALUES (:id, :parentId, :rootSessionId, :eventType, :startedAt, :content, :contentHash, :attributes)`
18417
+ );
18418
+ const stubRootStmt = db.prepare(
18419
+ `INSERT OR IGNORE INTO audit_events (id, event_type, started_at) VALUES (?, 'session', ?)`
18420
+ );
18421
+ return drainLegacyTable(
18422
+ db,
18423
+ "events",
18424
+ selectStmt,
18425
+ (rows) => {
18426
+ for (const row of rows) {
18427
+ const metadata = parseLegacyEventMetadata(row.metadata);
18428
+ const sessionId = metadata?.sessionId ?? null;
18429
+ if (sessionId !== null) stubRootStmt.run(sessionId, row.occurredAt);
18430
+ insertStmt.run(
18431
+ bindParams({
18432
+ id: row.id,
18433
+ parentId: sessionId,
18434
+ rootSessionId: sessionId,
18435
+ eventType: row.kind,
18436
+ startedAt: row.occurredAt,
18437
+ content: row.content,
18438
+ contentHash: row.contentHash,
18439
+ attributes: toLegacyAuditAttributesJson({ ...row, metadata })
18440
+ })
18441
+ );
18442
+ }
18443
+ }
18444
+ );
18445
+ }
18446
+ function copyLegacyFindings(db) {
18447
+ const selectStmt = db.prepare(
18448
+ `SELECT rowid AS rowid, id, event_id AS eventId, rule_id AS ruleId, category, severity,
18449
+ span_start AS spanStart, span_end AS spanEnd, masked_match AS maskedMatch,
18450
+ action_taken AS actionTaken, confidence, finding_key AS findingKey,
18451
+ first_detected_at AS firstDetectedAt
18452
+ FROM findings WHERE rowid > ? ORDER BY rowid LIMIT ?`
18453
+ );
18454
+ const definitionStmt = db.prepare(
18455
+ `INSERT OR IGNORE INTO inspection_definitions
18456
+ (id, rule_id, name, category, severity, definition, version)
18457
+ VALUES (:id, :ruleId, :name, :category, :severity, :definition, :version)`
18458
+ );
18459
+ const findingStmt = db.prepare(
18460
+ `INSERT INTO inspection_findings
18461
+ (id, audit_event_id, inspection_definition_id, classified_data_id,
18462
+ span_start, span_end, masked_match, action_taken, confidence,
18463
+ finding_key, first_detected_at)
18464
+ VALUES
18465
+ (:id, :auditEventId, :inspectionDefinitionId, NULL,
18466
+ :spanStart, :spanEnd, :maskedMatch, :actionTaken, :confidence,
18467
+ :findingKey, :firstDetectedAt)
18468
+ ON CONFLICT(id) DO NOTHING
18469
+ ON CONFLICT (finding_key) DO UPDATE SET
18470
+ first_detected_at = CASE
18471
+ WHEN first_detected_at IS NULL THEN excluded.first_detected_at
18472
+ WHEN excluded.first_detected_at IS NULL THEN first_detected_at
18473
+ ELSE min(first_detected_at, excluded.first_detected_at)
18474
+ END`
18475
+ );
18476
+ return drainLegacyTable(
18477
+ db,
18478
+ "findings",
18479
+ selectStmt,
18480
+ (rows) => {
18481
+ const definitionIds = /* @__PURE__ */ new Map();
18482
+ for (const row of rows) {
18483
+ const tupleKey = JSON.stringify([row.ruleId, row.category, row.severity]);
18484
+ let definitionId = definitionIds.get(tupleKey);
18485
+ if (definitionId === void 0) {
18486
+ const version2 = `unmigrated/${row.category}/${row.severity}`;
18487
+ definitionId = inspectionDefinitionId(row.ruleId, version2);
18488
+ definitionStmt.run(
18489
+ bindParams({
18490
+ id: definitionId,
18491
+ ruleId: row.ruleId,
18492
+ name: row.ruleId,
18493
+ category: row.category,
18494
+ severity: row.severity,
18495
+ definition: "",
18496
+ version: version2
18497
+ })
18498
+ );
18499
+ definitionIds.set(tupleKey, definitionId);
18500
+ }
18501
+ findingStmt.run(
18502
+ bindParams({
18503
+ id: row.id,
18504
+ auditEventId: row.eventId,
18505
+ inspectionDefinitionId: definitionId,
18506
+ spanStart: row.spanStart,
18507
+ spanEnd: row.spanEnd,
18508
+ maskedMatch: row.maskedMatch,
18509
+ actionTaken: row.actionTaken,
18510
+ confidence: row.confidence,
18511
+ findingKey: row.findingKey,
18512
+ firstDetectedAt: row.firstDetectedAt
18513
+ })
18514
+ );
18515
+ }
18516
+ }
18517
+ );
18518
+ }
18519
+ function runLegacyHistoryBackfill(db) {
18520
+ try {
18521
+ const eventsCaughtUp = copyLegacyEvents(db);
18522
+ if (!eventsCaughtUp) return false;
18523
+ return copyLegacyFindings(db);
18524
+ } catch (error51) {
18525
+ akaWarn(`legacy history backfill failed: ${String(error51)}`);
18526
+ return false;
18527
+ }
18528
+ }
18037
18529
  function isForeignSqliteLineage(db) {
18038
18530
  if (schemaObjectExists(db, "table", "tenants")) return true;
18039
18531
  return columnNames(db, "events").includes("tenant_id");
18040
18532
  }
18041
18533
  function ensureSyncedAtColumn(db, table2) {
18534
+ if (!schemaObjectExists(db, "table", table2)) return;
18042
18535
  if (!columnNames(db, table2).includes("synced_at")) {
18043
18536
  db.exec(`ALTER TABLE ${table2} ADD COLUMN synced_at integer`);
18044
18537
  }
@@ -18059,6 +18552,7 @@ function ensureWriteGateTrigger(db) {
18059
18552
  CONSTRAINT "ck_pack_write_gate_single_row" CHECK("_pack_write_gate"."id" = 1)
18060
18553
  )`);
18061
18554
  db.exec("INSERT OR IGNORE INTO _pack_write_gate (id, open) VALUES (1, 0)");
18555
+ if (!schemaObjectExists(db, "table", "installed_packs")) return;
18062
18556
  db.exec(`CREATE TRIGGER IF NOT EXISTS trg_installed_packs_write_gate
18063
18557
  BEFORE UPDATE OF version, name, rules_json ON installed_packs
18064
18558
  WHEN (SELECT open FROM _pack_write_gate WHERE id = 1) IS NOT 1
@@ -18077,29 +18571,13 @@ function ensureBlockedDetectionsTable(db) {
18077
18571
  blocked_at INTEGER NOT NULL
18078
18572
  )`);
18079
18573
  }
18080
-
18081
- // ../../packages/persistence/src/paths.ts
18082
- import { chmodSync, mkdirSync } from "fs";
18083
- var DATA_DIR_MODE = 448;
18084
- var DATA_FILE_MODE = 384;
18085
- var DB_FILENAME = "aka.db";
18086
- function ensureDataDirSync(dir) {
18087
- mkdirSync(dir, { recursive: true, mode: DATA_DIR_MODE });
18088
- try {
18089
- chmodSync(dir, DATA_DIR_MODE);
18090
- } catch {
18091
- }
18092
- }
18093
- function walSidecars(file2) {
18094
- return [`${file2}-wal`, `${file2}-shm`];
18095
- }
18096
- function tightenPerms(file2) {
18097
- for (const path of [file2, ...walSidecars(file2)]) {
18098
- try {
18099
- chmodSync(path, DATA_FILE_MODE);
18100
- } catch {
18101
- }
18102
- }
18574
+ function ensureRuleProbeCacheTable(db) {
18575
+ db.exec(`CREATE TABLE IF NOT EXISTS rule_probe_cache (
18576
+ rule_key TEXT PRIMARY KEY,
18577
+ verdict TEXT NOT NULL,
18578
+ worst_probe_ms REAL NOT NULL,
18579
+ checked_at INTEGER NOT NULL
18580
+ )`);
18103
18581
  }
18104
18582
 
18105
18583
  // ../../packages/persistence/src/internal/json.ts
@@ -18121,51 +18599,6 @@ function parseJsonObject(s) {
18121
18599
  return void 0;
18122
18600
  }
18123
18601
 
18124
- // ../../packages/persistence/src/internal/rows.ts
18125
- function allRows(stmt, params) {
18126
- if (params === void 0) return stmt.all();
18127
- if (Array.isArray(params)) return stmt.all(...params);
18128
- return stmt.all(params);
18129
- }
18130
- function getRow(stmt, params) {
18131
- if (params === void 0) return stmt.get();
18132
- if (Array.isArray(params)) return stmt.get(...params);
18133
- return stmt.get(params);
18134
- }
18135
- function intToBool(raw) {
18136
- return raw === 1 || raw === true;
18137
- }
18138
- function boolToInt(b) {
18139
- return b ? 1 : 0;
18140
- }
18141
- function bindParams(row) {
18142
- const out = {};
18143
- for (const [key, value] of Object.entries(row)) {
18144
- out[key] = value === void 0 ? null : value;
18145
- }
18146
- return out;
18147
- }
18148
- function countScalar(db, sql, params) {
18149
- return getRow(db.prepare(sql), params)?.n ?? 0;
18150
- }
18151
- function countBy(db, sql, params) {
18152
- const map2 = /* @__PURE__ */ new Map();
18153
- for (const row of allRows(db.prepare(sql), params)) {
18154
- map2.set(row.k, row.n);
18155
- }
18156
- return map2;
18157
- }
18158
- function mapRowsTolerant(rows, map2) {
18159
- const out = [];
18160
- for (const row of rows) {
18161
- try {
18162
- out.push(map2(row));
18163
- } catch {
18164
- }
18165
- }
18166
- return out;
18167
- }
18168
-
18169
18602
  // ../../packages/persistence/src/repositories/activity.ts
18170
18603
  var DAY_MS = 864e5;
18171
18604
  var LIVE_ACTIVITY_WINDOW_MS = 30 * 6e4;
@@ -18782,6 +19215,21 @@ var SqliteAuditEventsRepository = class {
18782
19215
  })
18783
19216
  );
18784
19217
  }
19218
+ // Idempotent stub of a session's structural root. Session-scoped leaves
19219
+ // (captures, llm_call, tool_call) FK parent_id/root_session_id onto this row;
19220
+ // INSERT OR IGNORE does NOT suppress a foreign-key violation (only
19221
+ // UNIQUE/PK/NOT NULL/CHECK), so a session-scoped insert with no root row
19222
+ // raises SQLITE_CONSTRAINT and rolls its whole transaction back — silently
19223
+ // dropping the write under failOpenTransaction. SessionStart's own root write
19224
+ // is itself fail-open and marks "attempted", not "succeeded", so a session
19225
+ // with no root row yet is a real, permanent condition, not a transient race.
19226
+ // The stub carries no dimensions/attributes; an authoritative root
19227
+ // (SessionStart / the reconciler's buildSessionRoot) wins by first-write-wins
19228
+ // on the id PK, so the stub never shadows real data. This is the single named
19229
+ // home for that FK invariant — call it before writing any session-scoped row.
19230
+ ensureSessionRoot(sessionId, startedAt) {
19231
+ this.insertAuditEvent({ id: sessionId, eventType: "session", startedAt });
19232
+ }
18785
19233
  // Insert one transcript-derived `llm_call` leaf. Unlike `insertAuditEvent`
18786
19234
  // (which takes a caller-supplied random id), the id here is MINTED internally
18787
19235
  // from the natural key — `llmCallId(sessionId, messageId)` — tenant-free like the
@@ -19243,8 +19691,14 @@ var SqliteDetectionsRepository = class {
19243
19691
  )
19244
19692
  );
19245
19693
  }
19246
- // Findings whose parent event occurred in the last 30 days and whose rule_id is
19247
- // in the given set. Mirrors the security repo's findings⋈events window join.
19694
+ // Findings whose parent audit event occurred in the last 30 days, is one of
19695
+ // the four capture kinds, and whose definition's rule_id is in the given set.
19696
+ // Mirrors the security repo's inspection_findings⋈audit_events window join.
19697
+ // rule_id lives on inspection_definitions, not the finding row, so the join
19698
+ // chains through it. audit_events also holds structural rows (session, run,
19699
+ // tool_call, llm_call, source_lookup, config_scan) that never had a legacy
19700
+ // events counterpart, so the event_type predicate keeps this count identical
19701
+ // to the old findings⋈events one.
19248
19702
  countFindingsLast30d(ruleIds) {
19249
19703
  if (ruleIds.length === 0) return 0;
19250
19704
  const since = this.now() - 30 * DAY_MS2;
@@ -19252,8 +19706,12 @@ var SqliteDetectionsRepository = class {
19252
19706
  return countScalar(
19253
19707
  this.db,
19254
19708
  `SELECT count(*) AS n
19255
- FROM findings f JOIN events e ON e.id = f.event_id
19256
- WHERE e.occurred_at >= ? AND f.rule_id IN (${inClause})`,
19709
+ FROM inspection_findings f
19710
+ JOIN audit_events e ON e.id = f.audit_event_id
19711
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
19712
+ WHERE e.started_at >= ?
19713
+ AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
19714
+ AND d.rule_id IN (${inClause})`,
19257
19715
  [since, ...ruleIds]
19258
19716
  );
19259
19717
  }
@@ -19263,35 +19721,24 @@ var SqliteDetectionsRepository = class {
19263
19721
  var SqliteEventsRepository = class {
19264
19722
  constructor(db) {
19265
19723
  this.db = db;
19266
- this.insertStmt = db.prepare(
19267
- `INSERT INTO events (id, source_tool, kind, occurred_at, content_hash, content, metadata)
19268
- VALUES (:id, :sourceTool, :kind, :occurredAt, :contentHash, :content, :metadata)`
19269
- );
19270
19724
  }
19271
19725
  db;
19272
- insertStmt;
19273
- insertEvent(event) {
19274
- const row = toEventRow(event);
19275
- this.insertStmt.run(
19276
- bindParams({
19277
- id: row.id,
19278
- sourceTool: row.sourceTool,
19279
- kind: row.kind,
19280
- occurredAt: row.occurredAt,
19281
- contentHash: row.contentHash,
19282
- content: row.content,
19283
- metadata: row.metadata
19284
- })
19285
- );
19286
- }
19287
- // Every recorded event's content hash — the historical backfill loads this once
19288
- // to skip transcript messages it has already stored, so re-running the scan
19289
- // never duplicates findings.
19726
+ // Every recorded capture's content hash — the historical backfill loads this
19727
+ // once to skip transcript messages it has already stored, so re-running the
19728
+ // scan never duplicates findings.
19290
19729
  // Async (Promise.resolve over synchronous node:sqlite) so it satisfies the
19291
19730
  // async EventsReadPort contract.
19731
+ //
19732
+ // audit_events also holds structural rows (session, run, tool_call, llm_call,
19733
+ // source_lookup, config_scan) with a NULL content_hash, so the capture-kind
19734
+ // predicate isn't load-bearing here — it documents intent and keeps the scan
19735
+ // index-friendly rather than walking rows that can never match.
19292
19736
  contentHashes() {
19293
19737
  const rows = allRows(
19294
- this.db.prepare("SELECT content_hash FROM events")
19738
+ this.db.prepare(
19739
+ `SELECT content_hash FROM audit_events
19740
+ WHERE event_type IN (${CAPTURE_EVENT_TYPES_SQL})`
19741
+ )
19295
19742
  );
19296
19743
  return Promise.resolve(new Set(rows.map((r) => r.content_hash)));
19297
19744
  }
@@ -19627,17 +20074,20 @@ function parseExceptionRow(row) {
19627
20074
  }
19628
20075
 
19629
20076
  // ../../packages/persistence/src/repositories/resolution-sql.ts
19630
- function latestResolutionStatusSql(findingsAlias) {
20077
+ function latestResolutionColumnSql(column, findingsAlias) {
19631
20078
  return `(
19632
- SELECT fr.status FROM finding_resolution fr
20079
+ SELECT fr.${column} FROM finding_resolution fr
19633
20080
  WHERE fr.finding_key = ${findingsAlias}.finding_key
19634
20081
  ORDER BY fr.created_at DESC, fr.rowid DESC
19635
20082
  LIMIT 1
19636
20083
  )`;
19637
20084
  }
20085
+ function latestResolutionStatusSql(findingsAlias) {
20086
+ return latestResolutionColumnSql("status", findingsAlias);
20087
+ }
19638
20088
  var LATEST_RESOLUTION_BY_KEY_SQL = `(
19639
- SELECT finding_key, status FROM (
19640
- SELECT fr.finding_key, fr.status,
20089
+ SELECT finding_key, status, method, resolved_at FROM (
20090
+ SELECT fr.finding_key, fr.status, fr.method, fr.resolved_at,
19641
20091
  ROW_NUMBER() OVER (
19642
20092
  PARTITION BY fr.finding_key
19643
20093
  ORDER BY fr.created_at DESC, fr.rowid DESC
@@ -19664,68 +20114,21 @@ var DAY_MS3 = 864e5;
19664
20114
  var SqliteFindingsRepository = class {
19665
20115
  constructor(db) {
19666
20116
  this.db = db;
19667
- this.insertStmt = db.prepare(
19668
- `INSERT INTO findings (id, event_id, rule_id, category, severity, span_start, span_end, masked_match, action_taken, confidence, finding_key, first_detected_at)
19669
- VALUES (:id, :eventId, :ruleId, :category, :severity, :spanStart, :spanEnd, :maskedMatch, :actionTaken, :confidence, :findingKey,
19670
- (SELECT occurred_at FROM events WHERE id = :eventId))
19671
- ON CONFLICT (finding_key) DO UPDATE SET
19672
- event_id = excluded.event_id,
19673
- category = excluded.category,
19674
- severity = excluded.severity,
19675
- span_start = excluded.span_start,
19676
- span_end = excluded.span_end,
19677
- masked_match = excluded.masked_match,
19678
- action_taken = excluded.action_taken,
19679
- confidence = excluded.confidence`
19680
- );
19681
- this.sessionDupStmt = db.prepare(
19682
- `SELECT 1 FROM findings f JOIN events e ON e.id = f.event_id
19683
- WHERE f.rule_id = :ruleId AND f.masked_match = :maskedMatch
19684
- AND json_extract(e.metadata, '$.sessionId') = :sessionId
19685
- LIMIT 1`
19686
- );
19687
20117
  }
19688
20118
  db;
19689
- insertStmt;
19690
- sessionDupStmt;
19691
- insertFindings(findings, scope = {}) {
19692
- for (const finding of findings) {
19693
- if (scope.sessionId && this.isSessionDuplicate(finding, scope.sessionId)) continue;
19694
- const row = toFindingRow(finding);
19695
- this.insertStmt.run({
19696
- id: row.id,
19697
- eventId: row.eventId,
19698
- ruleId: row.ruleId,
19699
- category: row.category,
19700
- severity: row.severity,
19701
- spanStart: row.spanStart,
19702
- spanEnd: row.spanEnd,
19703
- maskedMatch: row.maskedMatch,
19704
- actionTaken: row.actionTaken,
19705
- confidence: row.confidence,
19706
- findingKey: row.findingKey ?? null
19707
- });
19708
- }
19709
- }
19710
- // True when an earlier event in the same session already recorded a finding
19711
- // with the same rule and masked value. The current event is inserted before
19712
- // its findings, but carries no findings yet, so this never self-matches.
19713
- isSessionDuplicate(finding, sessionId) {
19714
- const hit = this.sessionDupStmt.get({
19715
- ruleId: finding.ruleId,
19716
- maskedMatch: finding.maskedMatch,
19717
- sessionId
19718
- });
19719
- return hit !== void 0;
19720
- }
19721
20119
  recentFindings(opts) {
19722
20120
  const limit = opts?.limit ?? 50;
19723
20121
  const rows = allRows(
19724
20122
  this.db.prepare(
19725
- `SELECT f.id, f.event_id, f.rule_id, f.category, f.severity, f.masked_match,
19726
- f.action_taken, f.confidence, e.occurred_at, e.source_tool, e.kind
19727
- FROM findings f JOIN events e ON e.id = f.event_id
19728
- ORDER BY e.occurred_at DESC, f.rowid DESC
20123
+ `SELECT f.id, f.audit_event_id AS event_id, d.rule_id, d.category, d.severity,
20124
+ f.masked_match, f.action_taken, f.confidence, e.started_at AS occurred_at,
20125
+ json_extract(e.attributes, '$.source_tool') AS source_tool,
20126
+ e.event_type AS kind
20127
+ FROM inspection_findings f
20128
+ JOIN audit_events e ON e.id = f.audit_event_id
20129
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
20130
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
20131
+ ORDER BY e.started_at DESC, f.rowid DESC
19729
20132
  LIMIT :limit`
19730
20133
  ),
19731
20134
  { limit }
@@ -19747,25 +20150,34 @@ var SqliteFindingsRepository = class {
19747
20150
  );
19748
20151
  }
19749
20152
  /** Live-enforced findings recorded for one session — a bare COUNT over the
19750
- * session-stamped events (served by idx_events_session_id), so the Activity
20153
+ * session-stamped audit_events (served by idx_audit_session), so the Activity
19751
20154
  * page can label its findings link without the grouped pipeline. */
19752
20155
  sessionFindingsCount(sessionId) {
19753
20156
  if (!sessionId) return Promise.resolve(0);
19754
20157
  return Promise.resolve(
19755
20158
  countScalar(
19756
20159
  this.db,
19757
- `SELECT count(*) AS n FROM findings f
19758
- JOIN events e ON e.id = f.event_id
19759
- WHERE json_extract(e.metadata, '$.sessionId') = :sessionId`,
20160
+ `SELECT count(*) AS n FROM inspection_findings f
20161
+ JOIN audit_events e ON e.id = f.audit_event_id
20162
+ WHERE e.root_session_id = :sessionId
20163
+ AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})`,
19760
20164
  { sessionId }
19761
20165
  )
19762
20166
  );
19763
20167
  }
19764
- /** Per-rule transcript firing tally for one session — reads the OTHER finding
19765
- * store (inspection_findings, keyed to audit_events): every detection the
19766
- * transcript pass recorded, counted per firing rather than per unique value.
19767
- * Rides on session-scoped grouped responses so the findings view can
19768
- * reconcile the Activity page's tally with the deduped groups it lists. */
20168
+ /** Per-rule transcript firing tally for one session — every detection the
20169
+ * transcript-reconciler pass recorded against the session's `tool_call` rows,
20170
+ * counted per firing rather than per unique value. Rides on session-scoped
20171
+ * grouped responses so the findings view can reconcile the Activity page's
20172
+ * tally with the deduped groups it lists.
20173
+ *
20174
+ * `inspection_findings`/`audit_events` are now the SAME physical tables the
20175
+ * rest of this class reads for the live-capture list above (they used to be
20176
+ * a separate store), so this excludes the four capture kinds those rows
20177
+ * already carry — without that exclusion, every live-capture finding in the
20178
+ * session would be tallied here too, double-counting against the grouped
20179
+ * list this response rides alongside. The reconciler attaches its findings
20180
+ * only to `tool_call` rows, which the exclusion leaves untouched. */
19769
20181
  sessionFirings(sessionId) {
19770
20182
  return Object.fromEntries(
19771
20183
  countBy(
@@ -19775,18 +20187,25 @@ var SqliteFindingsRepository = class {
19775
20187
  JOIN audit_events e ON e.id = f.audit_event_id
19776
20188
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
19777
20189
  WHERE e.root_session_id = :sessionId
20190
+ AND e.event_type NOT IN (${CAPTURE_EVENT_TYPES_SQL})
19778
20191
  GROUP BY d.rule_id`,
19779
20192
  { sessionId }
19780
20193
  )
19781
20194
  );
19782
20195
  }
19783
20196
  /**
19784
- * Grouped findings for the dashboard — joins findingsevents (repo/file/
19785
- * toolName from event metadata), groups by ruleId, computes per-filter-excluded facets,
19786
- * applies the requested filters, and sorts by severity then recency. Filtering
20197
+ * Grouped findings for the dashboard — joins inspection_findingsaudit_events
20198
+ * ⋈inspection_definitions (repo/file/toolName from the audit event's
20199
+ * attributes bag, rule_id/category/severity from the definition), scoped to
20200
+ * the four capture kinds (audit_events also holds structural/reconciler/scan
20201
+ * rows this list must never surface), groups by ruleId, computes
20202
+ * per-filter-excluded facets, applies the requested filters, and sorts by
20203
+ * severity then recency. Filtering
19787
20204
  * and faceting run in JS via the shared @akasecurity/schema helpers. `totals`
19788
20205
  * reflect the full filtered set; `items` is the requested
19789
- * page (default 50); no cursor (nextCursor is always null).
20206
+ * page (default 50); no cursor (nextCursor is always null). Under a `status`
20207
+ * filter, `totals.findings` counts only instances whose derived status was
20208
+ * requested, and each item's instance preview is narrowed the same way.
19790
20209
  *
19791
20210
  * Two reads, neither of which materializes a row per finding:
19792
20211
  * 1. one aggregate row per rule_id, folding EVERY instance into the numbers
@@ -19799,10 +20218,11 @@ var SqliteFindingsRepository = class {
19799
20218
  * rule is ever restated in SQL.
19800
20219
  */
19801
20220
  listGroupedFindings(query) {
19802
- const sessionPredicate = query.sessionId ? `WHERE json_extract(e.metadata, '$.sessionId') = :sessionId` : "";
20221
+ const sessionPredicate = query.sessionId ? ` AND e.root_session_id = :sessionId` : "";
20222
+ const predicate = `WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})${sessionPredicate}`;
19803
20223
  const sessionParams = query.sessionId ? { sessionId: query.sessionId } : {};
19804
20224
  const aggregates = this.groupAggregates(query.q !== void 0 && query.q !== "", {
19805
- predicate: sessionPredicate,
20225
+ predicate,
19806
20226
  params: sessionParams
19807
20227
  });
19808
20228
  const rows = allRows(
@@ -19810,24 +20230,26 @@ var SqliteFindingsRepository = class {
19810
20230
  `SELECT id, rule_id, category, severity, masked_match, action_taken, confidence,
19811
20231
  occurred_at, source_tool, repo, file, tool_name, kind, finding_key, latest_status
19812
20232
  FROM (
19813
- SELECT f.id AS id, f.rule_id AS rule_id, f.category AS category,
19814
- f.severity AS severity, f.masked_match AS masked_match,
20233
+ SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
20234
+ d.severity AS severity, f.masked_match AS masked_match,
19815
20235
  f.action_taken AS action_taken, f.confidence AS confidence,
19816
- e.occurred_at AS occurred_at, e.source_tool AS source_tool,
19817
- json_extract(e.metadata, '$.repo') AS repo,
19818
- json_extract(e.metadata, '$.filePath') AS file,
19819
- json_extract(e.metadata, '$.toolName') AS tool_name,
19820
- e.kind AS kind, f.finding_key AS finding_key,
20236
+ e.started_at AS occurred_at,
20237
+ json_extract(e.attributes, '$.source_tool') AS source_tool,
20238
+ json_extract(e.attributes, '$.repo') AS repo,
20239
+ json_extract(e.attributes, '$.file_path') AS file,
20240
+ json_extract(e.attributes, '$.tool_name') AS tool_name,
20241
+ e.event_type AS kind, f.finding_key AS finding_key,
19821
20242
  latest.status AS latest_status,
19822
20243
  ROW_NUMBER() OVER (
19823
- PARTITION BY f.rule_id
19824
- ORDER BY e.occurred_at DESC, f.id DESC
20244
+ PARTITION BY d.rule_id
20245
+ ORDER BY e.started_at DESC, f.id DESC
19825
20246
  ) AS rn
19826
- FROM findings f
19827
- JOIN events e ON e.id = f.event_id
20247
+ FROM inspection_findings f
20248
+ JOIN audit_events e ON e.id = f.audit_event_id
20249
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
19828
20250
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
19829
20251
  ON latest.finding_key = f.finding_key
19830
- ${sessionPredicate}
20252
+ ${predicate}
19831
20253
  )
19832
20254
  WHERE rn <= :cap
19833
20255
  ORDER BY occurred_at DESC, id DESC`
@@ -19854,17 +20276,29 @@ var SqliteFindingsRepository = class {
19854
20276
  severity: query.severity,
19855
20277
  providers: query.provider,
19856
20278
  actions: query.action,
20279
+ statuses: query.status,
19857
20280
  subtype: query.subtype,
19858
20281
  q: query.q
19859
20282
  };
19860
20283
  const facets = computeFindingFacets(allGroups, filterOpts);
19861
20284
  const sorted = sortFindingGroups(applyFindingFilters(allGroups, filterOpts));
20285
+ const statusFilter = query.status ?? [];
19862
20286
  const totals = {
19863
- findings: sorted.reduce((acc, g) => acc + g.instanceCount, 0),
20287
+ findings: sorted.reduce((acc, g) => {
20288
+ if (statusFilter.length === 0) return acc + g.instanceCount;
20289
+ const agg = aggregates.get(g.id);
20290
+ return acc + (agg ? countInstancesByStatus(agg.statusInputs, statusFilter) ?? g.instanceCount : g.instanceCount);
20291
+ }, 0),
19864
20292
  groups: sorted.length
19865
20293
  };
19866
20294
  const limit = query.limit ?? DEFAULT_GROUPED_FINDINGS_LIMIT;
19867
- const items = sorted.slice(0, limit);
20295
+ const statusSet = statusFilter.length > 0 ? new Set(statusFilter) : null;
20296
+ const items = sorted.slice(0, limit).map(
20297
+ (g) => statusSet ? {
20298
+ ...g,
20299
+ instances: g.instances.filter((i) => i.status !== void 0 && statusSet.has(i.status))
20300
+ } : g
20301
+ );
19868
20302
  return Promise.resolve({
19869
20303
  totals,
19870
20304
  facets,
@@ -19878,45 +20312,62 @@ var SqliteFindingsRepository = class {
19878
20312
  * buildFindingGroups cannot recover from a preview. Bounded by the number of
19879
20313
  * distinct rule_ids (the installed packs' rules), not by the store's size.
19880
20314
  *
19881
- * The per-instance sets ride back as group_concat lists of RAW DB values —
19882
- * source_tool, action_taken, and the (kind, has-key, latest-status) triples
19883
- * deriveFindingStatus consumes. Aggregating the status INPUTS rather than a
19884
- * status keeps the classifier itself in @akasecurity/schema, where
19885
- * severitySummary's SQL and this query can't drift apart on what 'resolved'
19886
- * means (see resolution-sql.ts). Each of those sets is bounded by an enum, so
20315
+ * A single scan, folded in two levels: the inner SELECT groups by
20316
+ * (rule_id, status tuple) so each (kind, has-key, latest-status) combination
20317
+ * carries its instance count countInstancesByStatus needs those counts for
20318
+ * status-scoped totals — and the outer SELECT folds the tuples back to one
20319
+ * row per rule. The per-instance sets ride back as group_concat lists of RAW
20320
+ * DB values source_tool, action_taken, and the tuples deriveFindingStatus
20321
+ * consumes. Aggregating the status INPUTS rather than a status keeps the
20322
+ * classifier itself in @akasecurity/schema, where severitySummary's SQL and
20323
+ * this query can't drift apart on what 'resolved' means (see
20324
+ * resolution-sql.ts). The concat-of-concats can repeat a value across
20325
+ * tuples; the schema mappers dedupe, and each set is bounded by an enum, so
19887
20326
  * a group's row stays small however many findings it holds.
19888
20327
  *
19889
20328
  * `withSearchText` is the exception, and the one column here that does NOT
19890
- * stay small: the group's distinct repos/filePaths, whose size tracks how many
19891
- * distinct paths a rule fired across — for a rule hitting mostly-unique paths
19892
- * that is a string proportional to the store (~8MB over 200k distinct paths,
19893
- * and buildHaystack lowercases a second copy). It buys `q` the ability to
19894
- * match an instance outside the preview, which searching the preview alone
19895
- * would silently lose, so it is fetched only when the request actually
19896
- * carries a `q`.
20329
+ * stay small: the group's per-tuple-distinct repos/filePaths, whose size
20330
+ * tracks how many distinct paths a rule fired across — for a rule hitting
20331
+ * mostly-unique paths that is a string proportional to the store (~8MB over
20332
+ * 200k distinct paths, and buildHaystack lowercases a second copy). It buys
20333
+ * `q` the ability to match an instance outside the preview, which searching
20334
+ * the preview alone would silently lose, so it is fetched only when the
20335
+ * request actually carries a `q`. (Substring matching is unaffected by a
20336
+ * path repeating across tuples.)
19897
20337
  */
19898
20338
  groupAggregates(withSearchText, scope) {
19899
- const searchTextColumns = withSearchText ? `, group_concat(DISTINCT json_extract(e.metadata, '$.repo')) AS repos,
19900
- group_concat(DISTINCT json_extract(e.metadata, '$.filePath')) AS files,
19901
- group_concat(DISTINCT 'via ' || json_extract(e.metadata, '$.toolName')) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
20339
+ const innerSearchColumns = withSearchText ? `, group_concat(DISTINCT json_extract(e.attributes, '$.repo')) AS repos,
20340
+ group_concat(DISTINCT json_extract(e.attributes, '$.file_path')) AS files,
20341
+ group_concat(DISTINCT 'via ' || json_extract(e.attributes, '$.tool_name')) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
19902
20342
  const rows = this.db.prepare(
19903
- `SELECT f.rule_id AS rule_id,
19904
- count(*) AS instance_count,
19905
- max(e.occurred_at) AS latest_at,
19906
- group_concat(DISTINCT e.source_tool) AS source_tools,
19907
- group_concat(DISTINCT f.action_taken) AS actions_taken,
19908
- group_concat(DISTINCT (
19909
- e.kind || '${TUPLE_SEP}' ||
19910
- (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
19911
- coalesce(latest.status, '')
19912
- )) AS status_inputs
19913
- ${searchTextColumns}
19914
- FROM findings f
19915
- JOIN events e ON e.id = f.event_id
19916
- LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
19917
- ON latest.finding_key = f.finding_key
19918
- ${scope.predicate}
19919
- GROUP BY f.rule_id`
20343
+ `SELECT rule_id,
20344
+ sum(tuple_count) AS instance_count,
20345
+ max(latest_at) AS latest_at,
20346
+ group_concat(source_tools) AS source_tools,
20347
+ group_concat(actions_taken) AS actions_taken,
20348
+ group_concat(status_tuple || '${TUPLE_SEP}' || tuple_count) AS status_inputs,
20349
+ group_concat(repos) AS repos,
20350
+ group_concat(files) AS files,
20351
+ group_concat(tool_names) AS tool_names
20352
+ FROM (
20353
+ SELECT d.rule_id AS rule_id,
20354
+ e.event_type || '${TUPLE_SEP}' ||
20355
+ (CASE WHEN f.finding_key IS NULL THEN '' ELSE 'k' END) || '${TUPLE_SEP}' ||
20356
+ coalesce(latest.status, '') AS status_tuple,
20357
+ count(*) AS tuple_count,
20358
+ max(e.started_at) AS latest_at,
20359
+ group_concat(DISTINCT json_extract(e.attributes, '$.source_tool')) AS source_tools,
20360
+ group_concat(DISTINCT f.action_taken) AS actions_taken
20361
+ ${innerSearchColumns}
20362
+ FROM inspection_findings f
20363
+ JOIN audit_events e ON e.id = f.audit_event_id
20364
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
20365
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
20366
+ ON latest.finding_key = f.finding_key
20367
+ ${scope.predicate}
20368
+ GROUP BY d.rule_id, status_tuple
20369
+ )
20370
+ GROUP BY rule_id`
19920
20371
  ).all(scope.params);
19921
20372
  return new Map(
19922
20373
  rows.map((r) => [
@@ -19926,13 +20377,14 @@ var SqliteFindingsRepository = class {
19926
20377
  sourceTools: splitConcat(r.source_tools),
19927
20378
  actionsTaken: splitConcat(r.actions_taken),
19928
20379
  statusInputs: splitConcat(r.status_inputs).map((tuple2) => {
19929
- const [kind = "", keyMarker = "", latestStatus = ""] = tuple2.split(TUPLE_SEP);
20380
+ const [kind = "", keyMarker = "", latestStatus = "", count = ""] = tuple2.split(TUPLE_SEP);
19930
20381
  return {
19931
20382
  // deriveFindingStatus only distinguishes null from non-null here,
19932
20383
  // so the marker stands in for the key itself (never rendered).
19933
20384
  kind,
19934
20385
  findingKey: keyMarker === "" ? null : keyMarker,
19935
- latestResolutionStatus: latestStatus === "" ? null : latestStatus
20386
+ latestResolutionStatus: latestStatus === "" ? null : latestStatus,
20387
+ count: Number(count)
19936
20388
  };
19937
20389
  }),
19938
20390
  latestDetectedAt: epochMillisToIso(r.latest_at),
@@ -19949,10 +20401,21 @@ var SqliteFindingsRepository = class {
19949
20401
  );
19950
20402
  }
19951
20403
  healthSummary() {
19952
- const total = countScalar(this.db, "SELECT count(*) AS n FROM findings");
20404
+ const total = countScalar(
20405
+ this.db,
20406
+ `SELECT count(*) AS n FROM inspection_findings f
20407
+ JOIN audit_events e ON e.id = f.audit_event_id
20408
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})`
20409
+ );
19953
20410
  const byAction = Object.fromEntries(ACTION_TAKEN_KEYS.map((a) => [a, 0]));
19954
20411
  const grouped = allRows(
19955
- this.db.prepare("SELECT action_taken, count(*) AS c FROM findings GROUP BY action_taken")
20412
+ this.db.prepare(
20413
+ `SELECT f.action_taken AS action_taken, count(*) AS c
20414
+ FROM inspection_findings f
20415
+ JOIN audit_events e ON e.id = f.audit_event_id
20416
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
20417
+ GROUP BY f.action_taken`
20418
+ )
19956
20419
  );
19957
20420
  for (const row of grouped) {
19958
20421
  if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
@@ -19960,12 +20423,15 @@ var SqliteFindingsRepository = class {
19960
20423
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
19961
20424
  const sevRows = allRows(
19962
20425
  this.db.prepare(
19963
- `SELECT f.severity AS severity, count(*) AS c
19964
- FROM findings f
20426
+ `SELECT d.severity AS severity, count(*) AS c
20427
+ FROM inspection_findings f
20428
+ JOIN audit_events e ON e.id = f.audit_event_id
20429
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
19965
20430
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
19966
20431
  ON latest.finding_key = f.finding_key
19967
- WHERE latest.status IS NULL OR latest.status != 'resolved'
19968
- GROUP BY f.severity`
20432
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
20433
+ AND (latest.status IS NULL OR latest.status != 'resolved')
20434
+ GROUP BY d.severity`
19969
20435
  )
19970
20436
  );
19971
20437
  for (const row of sevRows) {
@@ -19986,9 +20452,11 @@ var SqliteFindingsRepository = class {
19986
20452
  const since = startOfUtcDay(Date.now()) - (days - 1) * DAY_MS3;
19987
20453
  const rows = allRows(
19988
20454
  this.db.prepare(
19989
- `SELECT date(e.occurred_at / 1000, 'unixepoch') AS day, f.action_taken AS action, count(*) AS c
19990
- FROM findings f JOIN events e ON e.id = f.event_id
19991
- WHERE e.occurred_at >= :since
20455
+ `SELECT date(e.started_at / 1000, 'unixepoch') AS day, f.action_taken AS action, count(*) AS c
20456
+ FROM inspection_findings f
20457
+ JOIN audit_events e ON e.id = f.audit_event_id
20458
+ WHERE e.started_at >= :since
20459
+ AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
19992
20460
  GROUP BY day, f.action_taken`
19993
20461
  ),
19994
20462
  { since }
@@ -20053,15 +20521,59 @@ var SqliteInspectionFindingsRepository = class {
20053
20521
  this.insertStmt = db.prepare(
20054
20522
  `INSERT INTO inspection_findings
20055
20523
  (id, audit_event_id, inspection_definition_id, classified_data_id,
20056
- span_start, span_end, masked_match, action_taken, confidence)
20524
+ span_start, span_end, masked_match, action_taken, confidence,
20525
+ finding_key, first_detected_at)
20057
20526
  VALUES
20058
20527
  (:id, :auditEventId, :inspectionDefinitionId, :classifiedDataId,
20059
- :spanStart, :spanEnd, :maskedMatch, :actionTaken, :confidence)
20060
- ON CONFLICT(id) DO NOTHING`
20528
+ :spanStart, :spanEnd, :maskedMatch, :actionTaken, :confidence,
20529
+ :findingKey,
20530
+ COALESCE(:firstDetectedAt, (SELECT started_at FROM audit_events WHERE id = :auditEventId)))
20531
+ ON CONFLICT(id) DO UPDATE SET
20532
+ inspection_definition_id = excluded.inspection_definition_id
20533
+ ON CONFLICT (finding_key) DO UPDATE SET
20534
+ audit_event_id = excluded.audit_event_id,
20535
+ inspection_definition_id = excluded.inspection_definition_id,
20536
+ classified_data_id = excluded.classified_data_id,
20537
+ span_start = excluded.span_start,
20538
+ span_end = excluded.span_end,
20539
+ masked_match = excluded.masked_match,
20540
+ action_taken = excluded.action_taken,
20541
+ confidence = excluded.confidence`
20542
+ );
20543
+ this.sessionDupStmt = db.prepare(
20544
+ `SELECT 1 FROM inspection_findings f
20545
+ JOIN audit_events e ON e.id = f.audit_event_id
20546
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
20547
+ WHERE d.rule_id = :ruleId AND f.masked_match = :maskedMatch
20548
+ AND e.root_session_id = :sessionId
20549
+ AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
20550
+ LIMIT 1`
20551
+ );
20552
+ this.eventDupStmt = db.prepare(
20553
+ `SELECT 1 FROM inspection_findings f
20554
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
20555
+ WHERE f.audit_event_id = :auditEventId AND d.rule_id = :ruleId
20556
+ AND f.masked_match = :maskedMatch
20557
+ AND f.span_start = :spanStart AND f.span_end = :spanEnd
20558
+ LIMIT 1`
20061
20559
  );
20062
20560
  }
20063
20561
  db;
20064
20562
  insertStmt;
20563
+ sessionDupStmt;
20564
+ eventDupStmt;
20565
+ // True when an earlier event in the same session already recorded a finding
20566
+ // with the same rule and masked value. The current event's own findings are
20567
+ // inserted one at a time in caller order, so an earlier finding in the SAME
20568
+ // recordCapture call is visible to a later duplicate check within it too.
20569
+ isSessionDuplicate(ruleId, maskedMatch, sessionId) {
20570
+ return this.sessionDupStmt.get({ ruleId, maskedMatch, sessionId }) !== void 0;
20571
+ }
20572
+ // True when this exact detection (rule + masked value + span) is already
20573
+ // recorded against the given audit event.
20574
+ isEventDuplicate(auditEventId, ruleId, maskedMatch, spanStart, spanEnd) {
20575
+ return this.eventDupStmt.get({ auditEventId, ruleId, maskedMatch, spanStart, spanEnd }) !== void 0;
20576
+ }
20065
20577
  insertFinding(input) {
20066
20578
  const row = toInspectionFindingRow(input);
20067
20579
  this.insertStmt.run(
@@ -20074,7 +20586,9 @@ var SqliteInspectionFindingsRepository = class {
20074
20586
  spanEnd: row.spanEnd,
20075
20587
  maskedMatch: row.maskedMatch,
20076
20588
  actionTaken: row.actionTaken,
20077
- confidence: row.confidence
20589
+ confidence: row.confidence,
20590
+ findingKey: row.findingKey,
20591
+ firstDetectedAt: row.firstDetectedAt
20078
20592
  })
20079
20593
  );
20080
20594
  }
@@ -20346,7 +20860,7 @@ var SqliteInstalledPacksRepository = class {
20346
20860
  installedRuleset() {
20347
20861
  const rows = allRows(
20348
20862
  this.db.prepare(
20349
- `SELECT enabled, policy_id AS policyId, rules_json AS rulesJson FROM installed_packs`
20863
+ `SELECT enabled, policy_id AS policyId, rules_json AS rulesJson, version FROM installed_packs`
20350
20864
  )
20351
20865
  );
20352
20866
  const out = {
@@ -20354,7 +20868,8 @@ var SqliteInstalledPacksRepository = class {
20354
20868
  enabledPacks: 0,
20355
20869
  rules: [],
20356
20870
  invalidRules: 0,
20357
- ruleActions: /* @__PURE__ */ new Map()
20871
+ ruleActions: /* @__PURE__ */ new Map(),
20872
+ ruleVersions: /* @__PURE__ */ new Map()
20358
20873
  };
20359
20874
  for (const row of rows) {
20360
20875
  if (!intToBool(row.enabled)) continue;
@@ -20376,6 +20891,7 @@ var SqliteInstalledPacksRepository = class {
20376
20891
  if (parsed.success) {
20377
20892
  out.rules.push(parsed.data);
20378
20893
  out.ruleActions.set(parsed.data.id, action);
20894
+ out.ruleVersions.set(parsed.data.id, row.version);
20379
20895
  } else out.invalidRules += 1;
20380
20896
  }
20381
20897
  }
@@ -21550,19 +22066,19 @@ var SqliteResolutionsRepository = class {
21550
22066
  );
21551
22067
  this.openAtRestStmt = db.prepare(
21552
22068
  `SELECT DISTINCT f.finding_key AS finding_key
21553
- FROM findings f
21554
- JOIN events e ON e.id = f.event_id
21555
- WHERE e.kind = 'code_change'
21556
- AND json_extract(e.metadata, '$.filePath') = :path
22069
+ FROM inspection_findings f
22070
+ JOIN audit_events e ON e.id = f.audit_event_id
22071
+ WHERE e.event_type = 'code_change'
22072
+ AND json_extract(e.attributes, '$.file_path') = :path
21557
22073
  AND f.finding_key IS NOT NULL
21558
22074
  AND ${latestResolutionStatusSql("f")} IS NOT 'resolved'`
21559
22075
  );
21560
22076
  this.resolvedAtRestStmt = db.prepare(
21561
22077
  `SELECT DISTINCT f.finding_key AS finding_key
21562
- FROM findings f
21563
- JOIN events e ON e.id = f.event_id
21564
- WHERE e.kind = 'code_change'
21565
- AND json_extract(e.metadata, '$.filePath') = :path
22078
+ FROM inspection_findings f
22079
+ JOIN audit_events e ON e.id = f.audit_event_id
22080
+ WHERE e.event_type = 'code_change'
22081
+ AND json_extract(e.attributes, '$.file_path') = :path
21566
22082
  AND f.finding_key IS NOT NULL
21567
22083
  AND ${latestResolutionStatusSql("f")} = 'resolved'`
21568
22084
  );
@@ -21630,6 +22146,35 @@ var SqliteResolutionsRepository = class {
21630
22146
  }
21631
22147
  };
21632
22148
 
22149
+ // ../../packages/persistence/src/repositories/rule-probe-cache.ts
22150
+ var SqliteRuleProbeCacheRepository = class {
22151
+ constructor(db) {
22152
+ this.db = db;
22153
+ this.upsertStmt = db.prepare(
22154
+ `INSERT INTO rule_probe_cache (rule_key, verdict, worst_probe_ms, checked_at)
22155
+ VALUES (:ruleKey, :verdict, :worstProbeMs, :checkedAt)
22156
+ ON CONFLICT (rule_key) DO UPDATE SET
22157
+ verdict = excluded.verdict,
22158
+ worst_probe_ms = excluded.worst_probe_ms,
22159
+ checked_at = excluded.checked_at`
22160
+ );
22161
+ this.readStmt = db.prepare(
22162
+ `SELECT verdict, worst_probe_ms AS worstProbeMs FROM rule_probe_cache WHERE rule_key = :ruleKey`
22163
+ );
22164
+ }
22165
+ db;
22166
+ upsertStmt;
22167
+ readStmt;
22168
+ getVerdict(ruleKey) {
22169
+ return getRow(this.readStmt, { ruleKey });
22170
+ }
22171
+ setVerdict(ruleKey, verdict, worstProbeMs) {
22172
+ failOpenTransaction(this.db, () => {
22173
+ this.upsertStmt.run({ ruleKey, verdict, worstProbeMs, checkedAt: Date.now() });
22174
+ });
22175
+ }
22176
+ };
22177
+
21633
22178
  // ../../packages/persistence/src/repositories/scan-ledger.ts
21634
22179
  var SqliteScanLedgerRepository = class {
21635
22180
  constructor(db) {
@@ -21756,25 +22301,27 @@ var SqliteSecurityRepository = class {
21756
22301
  severitySummary() {
21757
22302
  const rows = allRows(
21758
22303
  this.db.prepare(
21759
- `SELECT f.severity AS severity,
22304
+ `SELECT d.severity AS severity,
21760
22305
  COUNT(*) AS count,
21761
22306
  SUM(CASE
21762
- WHEN e.kind != 'code_change' THEN 1
22307
+ WHEN e.event_type != 'code_change' THEN 1
21763
22308
  WHEN f.finding_key IS NULL THEN 0
21764
22309
  WHEN latest.status = 'resolved' THEN 1
21765
22310
  ELSE 0
21766
22311
  END) AS caught,
21767
22312
  SUM(CASE
21768
- WHEN e.kind = 'code_change'
22313
+ WHEN e.event_type = 'code_change'
21769
22314
  AND f.finding_key IS NOT NULL
21770
22315
  AND (latest.status IS NULL OR latest.status != 'resolved') THEN 1
21771
22316
  ELSE 0
21772
22317
  END) AS open_at_rest
21773
- FROM findings f
21774
- JOIN events e ON e.id = f.event_id
22318
+ FROM inspection_findings f
22319
+ JOIN audit_events e ON e.id = f.audit_event_id
22320
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
21775
22321
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
21776
22322
  ON latest.finding_key = f.finding_key
21777
- GROUP BY f.severity`
22323
+ WHERE e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
22324
+ GROUP BY d.severity`
21778
22325
  )
21779
22326
  );
21780
22327
  const byRow = new Map(rows.map((r) => [r.severity, r]));
@@ -21840,7 +22387,7 @@ var SqliteSecurityRepository = class {
21840
22387
  // Mean time-to-remediate per bucket, split by severity — a sibling of
21841
22388
  // findingsTimeseries that reuses the same window/bucket/UTC math, but buckets
21842
22389
  // on a different timestamp: findingsTimeseries buckets by first-detection
21843
- // (events.occurred_at), this buckets by resolution time (the latest
22390
+ // (audit_events.started_at), this buckets by resolution time (the latest
21844
22391
  // finding_resolution row's resolved_at) — it's a "resolved in this bucket"
21845
22392
  // trend, not a "detected in this bucket" one. Only findings whose LATEST
21846
22393
  // resolution row (latest-resolution-wins, same correlated subquery as
@@ -21865,30 +22412,20 @@ var SqliteSecurityRepository = class {
21865
22412
  // first_detected_at is the PRESERVED first-detection time (set once on a
21866
22413
  // finding's INSERT, never overwritten on the re-detection upsert), so MTTR
21867
22414
  // measures from first sighting — not the latest re-scan's event, whose
21868
- // occurred_at the upsert overwrites onto findings.event_id. COALESCE onto
21869
- // the parent event's occurred_at defends against any legacy/edge row the
21870
- // backfill left null.
21871
- `SELECT COALESCE(f.first_detected_at, e.occurred_at) AS first_detected_at, f.severity AS severity,
21872
- (
21873
- SELECT fr.status FROM finding_resolution fr
21874
- WHERE fr.finding_key = f.finding_key
21875
- ORDER BY fr.created_at DESC, fr.rowid DESC
21876
- LIMIT 1
21877
- ) AS latest_status,
21878
- (
21879
- SELECT fr.method FROM finding_resolution fr
21880
- WHERE fr.finding_key = f.finding_key
21881
- ORDER BY fr.created_at DESC, fr.rowid DESC
21882
- LIMIT 1
21883
- ) AS latest_method,
21884
- (
21885
- SELECT fr.resolved_at FROM finding_resolution fr
21886
- WHERE fr.finding_key = f.finding_key
21887
- ORDER BY fr.created_at DESC, fr.rowid DESC
21888
- LIMIT 1
21889
- ) AS latest_resolved_at
21890
- FROM findings f JOIN events e ON e.id = f.event_id
22415
+ // started_at the upsert overwrites onto inspection_findings.audit_event_id.
22416
+ // COALESCE onto the parent event's started_at defends against any
22417
+ // legacy/edge row the backfill left null.
22418
+ `SELECT COALESCE(f.first_detected_at, e.started_at) AS first_detected_at, d.severity AS severity,
22419
+ latest.status AS latest_status,
22420
+ latest.method AS latest_method,
22421
+ latest.resolved_at AS latest_resolved_at
22422
+ FROM inspection_findings f
22423
+ JOIN audit_events e ON e.id = f.audit_event_id
22424
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
22425
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
22426
+ ON latest.finding_key = f.finding_key
21891
22427
  WHERE f.finding_key IS NOT NULL
22428
+ AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
21892
22429
  AND EXISTS (
21893
22430
  SELECT 1 FROM finding_resolution fr
21894
22431
  WHERE fr.finding_key = f.finding_key
@@ -21935,11 +22472,13 @@ var SqliteSecurityRepository = class {
21935
22472
  const from = now - RANGE_DAYS[range] * DAY_MS4;
21936
22473
  const rows = allRows(
21937
22474
  this.db.prepare(
21938
- `SELECT json_extract(e.metadata, '$.repo') AS repo, count(*) AS c
21939
- FROM findings f JOIN events e ON e.id = f.event_id
21940
- WHERE e.occurred_at >= :from AND e.occurred_at < :to
21941
- AND json_extract(e.metadata, '$.repo') IS NOT NULL
21942
- AND json_extract(e.metadata, '$.repo') != ''
22475
+ `SELECT json_extract(e.attributes, '$.repo') AS repo, count(*) AS c
22476
+ FROM inspection_findings f
22477
+ JOIN audit_events e ON e.id = f.audit_event_id
22478
+ WHERE e.started_at >= :from AND e.started_at < :to
22479
+ AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
22480
+ AND json_extract(e.attributes, '$.repo') IS NOT NULL
22481
+ AND json_extract(e.attributes, '$.repo') != ''
21943
22482
  GROUP BY repo
21944
22483
  ORDER BY c DESC, repo
21945
22484
  LIMIT :limit`
@@ -21963,44 +22502,28 @@ var SqliteSecurityRepository = class {
21963
22502
  // secret came back) is excluded — it is not currently resolved. Legacy
21964
22503
  // at-rest findings with finding_key IS NULL are excluded outright (the
21965
22504
  // resolution lifecycle can never attach to them). Path comes from the
21966
- // finding's parent event (kind 'code_change', metadata.filePath) — mirrors
21967
- // resolutions.ts's openAtRestStmt accessor. Ordered by resolved_at DESC,
21968
- // capped at `limit`.
22505
+ // finding's parent event (event_type 'code_change', attributes.file_path) —
22506
+ // mirrors resolutions.ts's openAtRestStmt accessor. Ordered by resolved_at
22507
+ // DESC, capped at `limit`.
21969
22508
  recentlyResolved(limit = 20) {
21970
22509
  const rows = allRows(
21971
22510
  this.db.prepare(
21972
22511
  `SELECT f.finding_key AS finding_key,
21973
- f.rule_id AS rule_id,
21974
- f.severity AS severity,
21975
- json_extract(e.metadata, '$.filePath') AS path,
21976
- COALESCE(f.first_detected_at, e.occurred_at) AS first_detected_at,
21977
- (
21978
- SELECT fr.resolved_at FROM finding_resolution fr
21979
- WHERE fr.finding_key = f.finding_key
21980
- ORDER BY fr.created_at DESC, fr.rowid DESC
21981
- LIMIT 1
21982
- ) AS latest_resolved_at
21983
- FROM findings f JOIN events e ON e.id = f.event_id
21984
- WHERE e.kind = 'code_change'
22512
+ d.rule_id AS rule_id,
22513
+ d.severity AS severity,
22514
+ json_extract(e.attributes, '$.file_path') AS path,
22515
+ COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
22516
+ latest.resolved_at AS latest_resolved_at
22517
+ FROM inspection_findings f
22518
+ JOIN audit_events e ON e.id = f.audit_event_id
22519
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
22520
+ LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
22521
+ ON latest.finding_key = f.finding_key
22522
+ WHERE e.event_type = 'code_change'
21985
22523
  AND f.finding_key IS NOT NULL
21986
- AND (
21987
- SELECT fr.status FROM finding_resolution fr
21988
- WHERE fr.finding_key = f.finding_key
21989
- ORDER BY fr.created_at DESC, fr.rowid DESC
21990
- LIMIT 1
21991
- ) = 'resolved'
21992
- AND (
21993
- SELECT fr.method FROM finding_resolution fr
21994
- WHERE fr.finding_key = f.finding_key
21995
- ORDER BY fr.created_at DESC, fr.rowid DESC
21996
- LIMIT 1
21997
- ) = 'fixed-at-source'
21998
- AND (
21999
- SELECT fr.resolved_at FROM finding_resolution fr
22000
- WHERE fr.finding_key = f.finding_key
22001
- ORDER BY fr.created_at DESC, fr.rowid DESC
22002
- LIMIT 1
22003
- ) IS NOT NULL
22524
+ AND latest.status = 'resolved'
22525
+ AND latest.method = 'fixed-at-source'
22526
+ AND latest.resolved_at IS NOT NULL
22004
22527
  ORDER BY latest_resolved_at DESC
22005
22528
  LIMIT :limit`
22006
22529
  ),
@@ -22019,15 +22542,18 @@ var SqliteSecurityRepository = class {
22019
22542
  return Promise.resolve({ items });
22020
22543
  }
22021
22544
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
22022
- // epoch-millis timestamp. occurred_at is an INTEGER column, so the bounds stay
22545
+ // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
22023
22546
  // numeric and the JS aggregations bucket/split on ms directly.
22024
22547
  findingsInRange(fromMs, toMs) {
22025
22548
  const rows = allRows(
22026
22549
  this.db.prepare(
22027
- `SELECT e.occurred_at AS occurred_at, f.severity AS severity, f.action_taken AS action_taken
22028
- FROM findings f JOIN events e ON e.id = f.event_id
22029
- WHERE e.occurred_at >= :from AND e.occurred_at < :to
22030
- ORDER BY e.occurred_at`
22550
+ `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken
22551
+ FROM inspection_findings f
22552
+ JOIN audit_events e ON e.id = f.audit_event_id
22553
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
22554
+ WHERE e.started_at >= :from AND e.started_at < :to
22555
+ AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
22556
+ ORDER BY e.started_at`
22031
22557
  ),
22032
22558
  { from: fromMs, to: toMs }
22033
22559
  );
@@ -22041,11 +22567,50 @@ var SqliteSecurityRepository = class {
22041
22567
 
22042
22568
  // ../../packages/persistence/src/repositories/shares.ts
22043
22569
  import { randomUUID as randomUUID7 } from "crypto";
22044
- var KIND_ORDER = ["provider", "internal", "ip"];
22570
+ var MAX_EGRESS_CALL_SITES_PER_PROJECT = 5e3;
22571
+ var IN_CHUNK = 500;
22572
+ var KIND_ORDER = ["provider", "internal", "external", "ip"];
22573
+ var PLAINTEXT_TRANSPORT_SQL = "('http', 'ws')";
22574
+ var OVERRIDE_JOIN = `LEFT JOIN egress_decision_override oh ON oh.host = d.host
22575
+ LEFT JOIN egress_decision_override ol ON ol.destination_id = d.id AND ol.host IS NULL`;
22045
22576
  var CALL_SITE_EMBED_CAP = 200;
22046
22577
  function parseNetwork(networkJson) {
22047
22578
  return safeJson(networkJson, null);
22048
22579
  }
22580
+ function capHits(all, mode) {
22581
+ if (all.length <= MAX_EGRESS_CALL_SITES_PER_PROJECT) {
22582
+ return { hits: [...all], droppedFiles: [], truncated: false };
22583
+ }
22584
+ if (mode === "walk") {
22585
+ return {
22586
+ hits: all.slice(0, MAX_EGRESS_CALL_SITES_PER_PROJECT),
22587
+ droppedFiles: [],
22588
+ truncated: true
22589
+ };
22590
+ }
22591
+ const byFile = /* @__PURE__ */ new Map();
22592
+ for (const hit of all) {
22593
+ const bucket = byFile.get(hit.site.file);
22594
+ if (bucket === void 0) byFile.set(hit.site.file, [hit]);
22595
+ else bucket.push(hit);
22596
+ }
22597
+ const hits = [];
22598
+ const droppedFiles = [];
22599
+ for (const [file2, bucket] of byFile) {
22600
+ if (hits.length + bucket.length > MAX_EGRESS_CALL_SITES_PER_PROJECT) droppedFiles.push(file2);
22601
+ else hits.push(...bucket);
22602
+ }
22603
+ return { hits, droppedFiles, truncated: true };
22604
+ }
22605
+ function withoutDroppedFiles(reconcile, droppedFiles) {
22606
+ if (reconcile.mode === "walk" || droppedFiles.length === 0) return reconcile;
22607
+ const dropped = new Set(droppedFiles);
22608
+ return {
22609
+ mode: "ledger",
22610
+ scannedFiles: reconcile.scannedFiles.filter((file2) => !dropped.has(file2)),
22611
+ deletedFiles: reconcile.deletedFiles.filter((file2) => !dropped.has(file2))
22612
+ };
22613
+ }
22049
22614
  function toEndpointSummary(row) {
22050
22615
  return {
22051
22616
  id: row.id,
@@ -22136,13 +22701,15 @@ var SqliteSharesRepository = class {
22136
22701
  const callSites = countScalar(this.db, "SELECT count(*) AS n FROM share_call_site");
22137
22702
  const insecure = countScalar(
22138
22703
  this.db,
22139
- "SELECT count(DISTINCT destination_id) AS n FROM share_endpoint WHERE transport = 'http'"
22704
+ `SELECT count(DISTINCT destination_id) AS n FROM share_endpoint
22705
+ WHERE transport IN ${PLAINTEXT_TRANSPORT_SQL}`
22140
22706
  );
22141
22707
  const needsReview = countScalar(
22142
22708
  this.db,
22143
22709
  `SELECT count(DISTINCT d.id) AS n
22144
22710
  FROM share_destination d
22145
- LEFT JOIN share_endpoint e ON e.destination_id = d.id AND e.transport = 'http'
22711
+ LEFT JOIN share_endpoint e ON e.destination_id = d.id
22712
+ AND e.transport IN ${PLAINTEXT_TRANSPORT_SQL}
22146
22713
  WHERE d.trust IN ('unverified', 'ip') OR e.id IS NOT NULL`
22147
22714
  );
22148
22715
  const kindCounts = countBy(
@@ -22152,6 +22719,7 @@ var SqliteSharesRepository = class {
22152
22719
  const byKind = {
22153
22720
  provider: kindCounts.get("provider") ?? 0,
22154
22721
  internal: kindCounts.get("internal") ?? 0,
22722
+ external: kindCounts.get("external") ?? 0,
22155
22723
  ip: kindCounts.get("ip") ?? 0
22156
22724
  };
22157
22725
  const trustCounts = countBy(
@@ -22227,23 +22795,316 @@ var SqliteSharesRepository = class {
22227
22795
  // real edit from a no-such-destination.
22228
22796
  /**
22229
22797
  * Set (decision) or clear (null) the egress decision override for a destination.
22230
- * `null` deletes the override row → reverts to the trust default.
22798
+ * `null` deletes the override rows → reverts to the trust default.
22799
+ *
22800
+ * The written row carries both the destination id and its host, so the
22801
+ * decision re-attaches by host after the destination is pruned and
22802
+ * re-detected under a fresh id. Rows written before the host column existed
22803
+ * (host NULL, matched by destination id) are replaced rather than left to
22804
+ * shadow the new one. Runs IMMEDIATE: the host lookup is read-then-write and
22805
+ * would otherwise race a concurrent prune.
22231
22806
  */
22232
22807
  setEgressDecision(destinationId, decision) {
22233
- const exists = this.db.prepare("SELECT 1 FROM share_destination WHERE id = ?").get(destinationId);
22234
- if (exists === void 0) return false;
22235
- if (decision === null) {
22236
- this.db.prepare("DELETE FROM egress_decision_override WHERE destination_id = ?").run(destinationId);
22237
- return true;
22808
+ let existed = false;
22809
+ withTransaction(
22810
+ this.db,
22811
+ () => {
22812
+ const dest = this.db.prepare("SELECT host FROM share_destination WHERE id = ?").get(destinationId);
22813
+ if (dest === void 0) return;
22814
+ existed = true;
22815
+ this.db.prepare(
22816
+ `DELETE FROM egress_decision_override
22817
+ WHERE host = :host OR (destination_id = :destinationId AND host IS NULL)`
22818
+ ).run({ host: dest.host, destinationId });
22819
+ if (decision === null) return;
22820
+ this.db.prepare(
22821
+ `INSERT INTO egress_decision_override
22822
+ (id, destination_id, host, decision, created_at, updated_at)
22823
+ VALUES (:id, :destinationId, :host, :decision, :now, :now)`
22824
+ ).run({
22825
+ id: randomUUID7(),
22826
+ destinationId,
22827
+ host: dest.host,
22828
+ decision,
22829
+ now: Date.now()
22830
+ });
22831
+ },
22832
+ "IMMEDIATE"
22833
+ );
22834
+ return existed;
22835
+ }
22836
+ /**
22837
+ * Record one project's statically-extracted egress: reconcile the previously
22838
+ * stored call sites against this scan, upsert destination → endpoint → call
22839
+ * site for every hit, confirm `last_seen` on everything the project still
22840
+ * references, and drop what no longer has evidence.
22841
+ *
22842
+ * Reconciliation keys on `projectKey` alone; `project` and `projectId` are
22843
+ * display payload and never scope a delete. The whole write is one
22844
+ * transaction: a failure leaves the project's previous inventory exactly as
22845
+ * it was, and THROWS rather than reporting a partial write — callers decide
22846
+ * their own fail-open behavior, and the scanner additionally withholds its
22847
+ * ledger commit so the next scan retries.
22848
+ *
22849
+ * Over-cap input is truncated at a FILE boundary, and the files that lost
22850
+ * their hits are both excluded from the reconcile delete and named in
22851
+ * `droppedFiles`. That pairing is what keeps truncation non-destructive on
22852
+ * the ledger path: a dropped file keeps whatever rows it already had, and its
22853
+ * caller withholds the ledger entry so the next scan reads it again.
22854
+ */
22855
+ recordProjectEgress(input) {
22856
+ const { hits, droppedFiles, truncated } = capHits(input.hits, input.reconcile.mode);
22857
+ const reconcile = withoutDroppedFiles(input.reconcile, droppedFiles);
22858
+ const now = Date.now();
22859
+ let summary = {
22860
+ destinations: 0,
22861
+ endpoints: 0,
22862
+ callSites: 0,
22863
+ truncated,
22864
+ droppedFiles
22865
+ };
22866
+ withTransaction(
22867
+ this.db,
22868
+ () => {
22869
+ const projectId = input.projectId ?? this.knownProjectId(input.projectKey);
22870
+ this.reconcileCallSites(input.projectKey, reconcile);
22871
+ this.upsertHits(input, hits, projectId, now);
22872
+ this.confirmLastSeen(input.projectKey, now);
22873
+ this.pruneOrphans();
22874
+ summary = { ...this.projectTotals(input.projectKey), truncated, droppedFiles };
22875
+ },
22876
+ "IMMEDIATE"
22877
+ );
22878
+ return summary;
22879
+ }
22880
+ // ─── Egress write internals ──────────────────────────────────────────────────
22881
+ /**
22882
+ * Clear the stored call sites this scan is responsible for re-creating.
22883
+ *
22884
+ * Each pipeline may only delete rows its own walker could have produced. The
22885
+ * fs walk behind 'walk' mode never descends into dot-directories, so its
22886
+ * delete excludes dot-path files — those rows are the plugin scanner's to
22887
+ * reconcile, and deleting them here would make the two pipelines erase each
22888
+ * other's rows on every alternating scan. 'ledger' mode names its files
22889
+ * outright and never mass-deletes, so rows the fs walk contributed for files
22890
+ * the scanner skips (vendored, oversize) survive it.
22891
+ */
22892
+ reconcileCallSites(projectKey, reconcile) {
22893
+ if (reconcile.mode === "walk") {
22894
+ const prefix = reconcile.walkedPrefix.replace(/\/+$/, "");
22895
+ this.db.prepare(
22896
+ `DELETE FROM share_call_site
22897
+ WHERE project_key = :key
22898
+ AND (:prefix = '' OR file = :prefix OR file LIKE :subtree ESCAPE '\\')
22899
+ AND file NOT LIKE '.%'
22900
+ AND file NOT LIKE '%/.%'`
22901
+ ).run({ key: projectKey, prefix, subtree: `${escapeLikePattern(prefix)}/%` });
22902
+ return;
22903
+ }
22904
+ const files = [.../* @__PURE__ */ new Set([...reconcile.scannedFiles, ...reconcile.deletedFiles])];
22905
+ for (let i = 0; i < files.length; i += IN_CHUNK) {
22906
+ const chunk = files.slice(i, i + IN_CHUNK);
22907
+ this.db.prepare(
22908
+ `DELETE FROM share_call_site
22909
+ WHERE project_key = ? AND file IN (${placeholders(chunk.length)})`
22910
+ ).run(projectKey, ...chunk);
22911
+ }
22912
+ }
22913
+ /**
22914
+ * Upsert every hit as destination → endpoint → call site. Destinations key on
22915
+ * `host` and endpoints on `(destination_id, method, url)`, both shared across
22916
+ * projects; only the call site carries `project_key`. A destination's `note`
22917
+ * is user-owned and never overwritten. The id caches keep one upsert per
22918
+ * distinct host and endpoint, so the first hit for a host supplies its
22919
+ * classification for this batch.
22920
+ */
22921
+ upsertHits(input, hits, projectId, now) {
22922
+ if (hits.length === 0) return;
22923
+ const destStmt = this.db.prepare(
22924
+ `INSERT INTO share_destination
22925
+ (id, kind, name, host, category, trust, network_json, last_seen, provenance,
22926
+ created_at, updated_at)
22927
+ VALUES (:id, :kind, :name, :host, :category, :trust, :networkJson, :now, 'scan', :now, :now)
22928
+ ON CONFLICT (host) DO UPDATE SET
22929
+ kind = excluded.kind,
22930
+ name = excluded.name,
22931
+ category = excluded.category,
22932
+ trust = excluded.trust,
22933
+ network_json = excluded.network_json,
22934
+ last_seen = excluded.last_seen,
22935
+ updated_at = excluded.updated_at`
22936
+ );
22937
+ const destIdStmt = this.db.prepare("SELECT id FROM share_destination WHERE host = ?");
22938
+ const endpointStmt = this.db.prepare(
22939
+ `INSERT INTO share_endpoint
22940
+ (id, destination_id, method, transport, url, template, data_class, last_seen,
22941
+ created_at, updated_at)
22942
+ VALUES (:id, :destinationId, :method, :transport, :url, :template, :dataClass, :now,
22943
+ :now, :now)
22944
+ ON CONFLICT (destination_id, method, url) DO UPDATE SET
22945
+ transport = excluded.transport,
22946
+ template = excluded.template,
22947
+ data_class = excluded.data_class,
22948
+ last_seen = excluded.last_seen,
22949
+ updated_at = excluded.updated_at`
22950
+ );
22951
+ const endpointIdStmt = this.db.prepare(
22952
+ "SELECT id FROM share_endpoint WHERE destination_id = ? AND method = ? AND url = ?"
22953
+ );
22954
+ const siteStmt = this.db.prepare(
22955
+ `INSERT INTO share_call_site
22956
+ (id, endpoint_id, project, project_key, file, line, snippet, dynamic, vendored,
22957
+ project_id, created_at, updated_at)
22958
+ VALUES (:id, :endpointId, :project, :projectKey, :file, :line, :snippet, :dynamic,
22959
+ :vendored, :projectId, :now, :now)
22960
+ ON CONFLICT (endpoint_id, project_key, file, line) DO UPDATE SET
22961
+ snippet = excluded.snippet,
22962
+ dynamic = excluded.dynamic,
22963
+ vendored = excluded.vendored,
22964
+ project = excluded.project,
22965
+ project_id = COALESCE(excluded.project_id, share_call_site.project_id),
22966
+ updated_at = excluded.updated_at`
22967
+ );
22968
+ const destIds = /* @__PURE__ */ new Map();
22969
+ const endpointIds = /* @__PURE__ */ new Map();
22970
+ for (const hit of hits) {
22971
+ let destinationId = destIds.get(hit.host);
22972
+ if (destinationId === void 0) {
22973
+ destStmt.run({
22974
+ id: randomUUID7(),
22975
+ kind: hit.kind,
22976
+ name: hit.name,
22977
+ host: hit.host,
22978
+ category: hit.category,
22979
+ trust: hit.trust,
22980
+ networkJson: hit.network === null ? null : JSON.stringify(hit.network),
22981
+ now
22982
+ });
22983
+ destinationId = getRow(destIdStmt, [hit.host])?.id ?? "";
22984
+ destIds.set(hit.host, destinationId);
22985
+ }
22986
+ const endpointKey = `${destinationId}\0${hit.method}\0${hit.url}`;
22987
+ let endpointId = endpointIds.get(endpointKey);
22988
+ if (endpointId === void 0) {
22989
+ endpointStmt.run({
22990
+ id: randomUUID7(),
22991
+ destinationId,
22992
+ method: hit.method,
22993
+ transport: hit.transport,
22994
+ url: hit.url,
22995
+ template: boolToInt(hit.template),
22996
+ dataClass: hit.dataClass,
22997
+ now
22998
+ });
22999
+ endpointId = getRow(endpointIdStmt, [destinationId, hit.method, hit.url])?.id ?? "";
23000
+ endpointIds.set(endpointKey, endpointId);
23001
+ }
23002
+ siteStmt.run({
23003
+ id: randomUUID7(),
23004
+ endpointId,
23005
+ project: input.project,
23006
+ projectKey: input.projectKey,
23007
+ file: hit.site.file,
23008
+ line: hit.site.line,
23009
+ snippet: hit.site.snippet,
23010
+ dynamic: boolToInt(hit.site.dynamic),
23011
+ vendored: boolToInt(hit.site.vendored),
23012
+ projectId,
23013
+ now
23014
+ });
22238
23015
  }
23016
+ }
23017
+ /**
23018
+ * The source-project id this project's stored call sites already carry, if
23019
+ * any. Only the pipeline that resolves a source project supplies one; the
23020
+ * other passes null and inherits this, so the link stops flapping between a
23021
+ * real id and NULL depending on which pipeline ran last. The value is a
23022
+ * per-project attribute stored redundantly on each row, so any row's is
23023
+ * representative.
23024
+ */
23025
+ knownProjectId(projectKey) {
23026
+ return getRow(
23027
+ this.db.prepare(
23028
+ `SELECT project_id AS projectId FROM share_call_site
23029
+ WHERE project_key = ? AND project_id IS NOT NULL LIMIT 1`
23030
+ ),
23031
+ [projectKey]
23032
+ )?.projectId ?? null;
23033
+ }
23034
+ /**
23035
+ * Stamp `last_seen` on every endpoint and destination this project still
23036
+ * references — including rows the scan preserved rather than re-wrote, so a
23037
+ * ledger-skipped file's references don't decay into "stale" on the page.
23038
+ */
23039
+ confirmLastSeen(projectKey, now) {
22239
23040
  this.db.prepare(
22240
- `INSERT INTO egress_decision_override (id, destination_id, decision, created_at, updated_at)
22241
- VALUES (:id, :destinationId, :decision, :now, :now)
22242
- ON CONFLICT (destination_id) DO UPDATE SET
22243
- decision = excluded.decision,
22244
- updated_at = excluded.updated_at`
22245
- ).run({ id: randomUUID7(), destinationId, decision, now: Date.now() });
22246
- return true;
23041
+ `UPDATE share_endpoint SET last_seen = :now, updated_at = :now
23042
+ WHERE id IN (SELECT DISTINCT endpoint_id FROM share_call_site WHERE project_key = :key)`
23043
+ ).run({ now, key: projectKey });
23044
+ this.db.prepare(
23045
+ `UPDATE share_destination SET last_seen = :now, updated_at = :now
23046
+ WHERE id IN (SELECT DISTINCT e.destination_id
23047
+ FROM share_endpoint e
23048
+ JOIN share_call_site c ON c.endpoint_id = e.id
23049
+ WHERE c.project_key = :key)`
23050
+ ).run({ now, key: projectKey });
23051
+ }
23052
+ /**
23053
+ * Drop rows left without evidence: endpoints with no call site, then
23054
+ * destinations with no endpoint. Call sites are the only evidence either one
23055
+ * has, so a row that lost its last one belongs to no project any more.
23056
+ *
23057
+ * Overrides are deleted between the two steps, and only the ones written
23058
+ * before the host column existed. Those match a destination by id alone;
23059
+ * because the id link is released on delete rather than cascading, leaving
23060
+ * them would accumulate rows that match neither join arm and that nothing can
23061
+ * reach again. Host-bearing rows deliberately survive — the host is what
23062
+ * re-attaches a user's decision when the destination comes back.
23063
+ */
23064
+ pruneOrphans() {
23065
+ this.db.exec(
23066
+ `DELETE FROM share_endpoint
23067
+ WHERE NOT EXISTS (SELECT 1 FROM share_call_site c WHERE c.endpoint_id = share_endpoint.id)`
23068
+ );
23069
+ this.db.exec(
23070
+ `DELETE FROM egress_decision_override
23071
+ WHERE host IS NULL
23072
+ AND destination_id IN (
23073
+ SELECT d.id FROM share_destination d
23074
+ WHERE NOT EXISTS (SELECT 1 FROM share_endpoint e WHERE e.destination_id = d.id))`
23075
+ );
23076
+ this.db.exec(
23077
+ `DELETE FROM share_destination
23078
+ WHERE NOT EXISTS (
23079
+ SELECT 1 FROM share_endpoint e WHERE e.destination_id = share_destination.id)`
23080
+ );
23081
+ }
23082
+ /**
23083
+ * Live totals for one project. Destinations and endpoints are shared across
23084
+ * projects and carry no project column, so both are counted through the call
23085
+ * sites that reference them.
23086
+ */
23087
+ projectTotals(projectKey) {
23088
+ return {
23089
+ destinations: countScalar(
23090
+ this.db,
23091
+ `SELECT count(DISTINCT e.destination_id) AS n
23092
+ FROM share_endpoint e
23093
+ JOIN share_call_site c ON c.endpoint_id = e.id
23094
+ WHERE c.project_key = ?`,
23095
+ [projectKey]
23096
+ ),
23097
+ endpoints: countScalar(
23098
+ this.db,
23099
+ "SELECT count(DISTINCT endpoint_id) AS n FROM share_call_site WHERE project_key = ?",
23100
+ [projectKey]
23101
+ ),
23102
+ callSites: countScalar(
23103
+ this.db,
23104
+ "SELECT count(*) AS n FROM share_call_site WHERE project_key = ?",
23105
+ [projectKey]
23106
+ )
23107
+ };
22247
23108
  }
22248
23109
  // ─── Raw fetchers ────────────────────────────────────────────────────────────
22249
23110
  mapDestRow(r) {
@@ -22263,7 +23124,8 @@ var SqliteSharesRepository = class {
22263
23124
  fetchDestinations(q, kinds, reviewOnly = false) {
22264
23125
  const cols = `d.id, d.kind, d.name, d.host, d.category, d.trust, d.note,
22265
23126
  d.network_json AS networkJson, d.last_seen AS lastSeenMs,
22266
- d.created_at AS createdAt, o.decision AS overrideDecision`;
23127
+ d.created_at AS createdAt,
23128
+ COALESCE(oh.decision, ol.decision) AS overrideDecision`;
22267
23129
  const conditions = [];
22268
23130
  const params = [];
22269
23131
  if (kinds && kinds.length > 0) {
@@ -22274,7 +23136,8 @@ var SqliteSharesRepository = class {
22274
23136
  conditions.push(
22275
23137
  `(d.trust IN ('unverified', 'ip')
22276
23138
  OR EXISTS (SELECT 1 FROM share_endpoint re
22277
- WHERE re.destination_id = d.id AND re.transport = 'http'))`
23139
+ WHERE re.destination_id = d.id
23140
+ AND re.transport IN ${PLAINTEXT_TRANSPORT_SQL}))`
22278
23141
  );
22279
23142
  }
22280
23143
  let sql;
@@ -22287,7 +23150,7 @@ var SqliteSharesRepository = class {
22287
23150
  params.push(pattern, pattern, pattern, pattern, pattern);
22288
23151
  sql = `SELECT DISTINCT ${cols}
22289
23152
  FROM share_destination d
22290
- LEFT JOIN egress_decision_override o ON o.destination_id = d.id
23153
+ ${OVERRIDE_JOIN}
22291
23154
  LEFT JOIN share_endpoint e ON e.destination_id = d.id
22292
23155
  LEFT JOIN share_call_site c ON c.endpoint_id = e.id
22293
23156
  ${conditions.length ? `WHERE ${conditions.join(" AND ")}` : ""}
@@ -22295,7 +23158,7 @@ var SqliteSharesRepository = class {
22295
23158
  } else {
22296
23159
  sql = `SELECT ${cols}
22297
23160
  FROM share_destination d
22298
- LEFT JOIN egress_decision_override o ON o.destination_id = d.id
23161
+ ${OVERRIDE_JOIN}
22299
23162
  ${conditions.length ? `WHERE ${conditions.join(" AND ")}` : ""}
22300
23163
  ORDER BY d.created_at ASC, d.id ASC`;
22301
23164
  }
@@ -22310,9 +23173,9 @@ var SqliteSharesRepository = class {
22310
23173
  this.db.prepare(
22311
23174
  `SELECT d.id, d.kind, d.name, d.host, d.category, d.trust, d.note,
22312
23175
  d.network_json AS networkJson, d.last_seen AS lastSeenMs,
22313
- o.decision AS overrideDecision
23176
+ COALESCE(oh.decision, ol.decision) AS overrideDecision
22314
23177
  FROM share_destination d
22315
- LEFT JOIN egress_decision_override o ON o.destination_id = d.id
23178
+ ${OVERRIDE_JOIN}
22316
23179
  WHERE d.id = ?`
22317
23180
  ),
22318
23181
  [destinationId]
@@ -22514,9 +23377,10 @@ function openWithPragmas(file2) {
22514
23377
  }
22515
23378
  function backupLegacyStore(file2) {
22516
23379
  const backup = `${file2}.legacy.${String(Date.now())}.bak`;
22517
- renameSync(file2, backup);
22518
- for (const sidecar of walSidecars(file2)) {
22519
- if (existsSync(sidecar)) rmSync(sidecar);
23380
+ renameSync2(file2, backup);
23381
+ tightenFile(backup);
23382
+ for (const sidecar of dbSidecars(file2)) {
23383
+ if (existsSync(sidecar)) rmSync2(sidecar);
22520
23384
  }
22521
23385
  return backup;
22522
23386
  }
@@ -22532,7 +23396,7 @@ function openLocalDatabase(dir) {
22532
23396
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
22533
23397
  );
22534
23398
  }
22535
- applyMigrations(db);
23399
+ applyMigrations(db, file2);
22536
23400
  tightenPerms(file2);
22537
23401
  const events = new SqliteEventsRepository(db);
22538
23402
  const findings = new SqliteFindingsRepository(db);
@@ -22541,6 +23405,7 @@ function openLocalDatabase(dir) {
22541
23405
  const scanLedger = new SqliteScanLedgerRepository(db);
22542
23406
  const exceptions = new SqliteExceptionsRepository(db);
22543
23407
  const resolutions = new SqliteResolutionsRepository(db);
23408
+ const ruleProbeCache = new SqliteRuleProbeCacheRepository(db);
22544
23409
  const security = new SqliteSecurityRepository(db);
22545
23410
  const detections = new SqliteDetectionsRepository(db);
22546
23411
  const shares = new SqliteSharesRepository(db);
@@ -22558,9 +23423,56 @@ function openLocalDatabase(dir) {
22558
23423
  policies.seedDefaults();
22559
23424
  function recordCapture(event, detected) {
22560
23425
  failOpenTransaction(db, () => {
22561
- events.insertEvent(event);
22562
23426
  const sessionId = event.metadata?.sessionId;
22563
- findings.insertFindings(detected, sessionId ? { sessionId } : {});
23427
+ if (sessionId) {
23428
+ auditEvents.ensureSessionRoot(sessionId, event.occurredAt);
23429
+ }
23430
+ const auditEventId = captureId(
23431
+ sessionId ?? null,
23432
+ event.contentHash,
23433
+ event.metadata?.filePath ?? null
23434
+ );
23435
+ auditEvents.insertAuditEvent({
23436
+ id: auditEventId,
23437
+ eventType: event.kind,
23438
+ startedAt: event.occurredAt,
23439
+ parentId: sessionId,
23440
+ rootSessionId: sessionId,
23441
+ content: event.content,
23442
+ contentHash: event.contentHash,
23443
+ attributes: toCaptureAttributes(event)
23444
+ });
23445
+ const definitionIds = /* @__PURE__ */ new Map();
23446
+ for (const finding of detected) {
23447
+ if (sessionId && inspectionFindings.isSessionDuplicate(finding.ruleId, finding.maskedMatch, sessionId)) {
23448
+ continue;
23449
+ }
23450
+ if (inspectionFindings.isEventDuplicate(
23451
+ auditEventId,
23452
+ finding.ruleId,
23453
+ finding.maskedMatch,
23454
+ finding.span.start,
23455
+ finding.span.end
23456
+ )) {
23457
+ continue;
23458
+ }
23459
+ const key = `${finding.ruleId}@${captureDefinitionVersion(finding)}`;
23460
+ let definitionId = definitionIds.get(key);
23461
+ if (!definitionId) {
23462
+ definitionId = inspectionDefinitions.upsert(toCaptureDefinitionInput(finding));
23463
+ definitionIds.set(key, definitionId);
23464
+ }
23465
+ inspectionFindings.insertFinding({
23466
+ id: finding.id,
23467
+ auditEventId,
23468
+ inspectionDefinitionId: definitionId,
23469
+ span: finding.span,
23470
+ maskedMatch: finding.maskedMatch,
23471
+ actionTaken: finding.actionTaken,
23472
+ confidence: finding.confidence,
23473
+ findingKey: finding.findingKey ?? void 0
23474
+ });
23475
+ }
22564
23476
  });
22565
23477
  }
22566
23478
  function ensureInventory(ctx) {
@@ -22678,6 +23590,7 @@ function openLocalDatabase(dir) {
22678
23590
  scanLedger,
22679
23591
  exceptions,
22680
23592
  resolutions,
23593
+ ruleProbeCache,
22681
23594
  security,
22682
23595
  detections,
22683
23596
  shares,
@@ -22707,9 +23620,12 @@ function openLocalDatabase(dir) {
22707
23620
  };
22708
23621
  }
22709
23622
 
23623
+ // ../../packages/persistence/src/finding-key.ts
23624
+ import { createHash as createHash3 } from "crypto";
23625
+
22710
23626
  // ../../packages/persistence/src/fingerprint.ts
22711
23627
  import { createHmac, randomBytes } from "crypto";
22712
- import { chmodSync as chmodSync2, readFileSync, renameSync as renameSync2, writeFileSync } from "fs";
23628
+ import { readFileSync } from "fs";
22713
23629
  import { join as join2 } from "path";
22714
23630
  var KEY_FILENAME = "exception.key";
22715
23631
  var KEY_MATERIAL_BYTES = 32;
@@ -22746,8 +23662,8 @@ function readFingerprintKey(dataDir2) {
22746
23662
  }
22747
23663
 
22748
23664
  // ../../packages/persistence/src/local-layout.ts
22749
- import { chmodSync as chmodSync3, mkdirSync as mkdirSync2, renameSync as renameSync3 } from "fs";
22750
- import { chmod, mkdir } from "fs/promises";
23665
+ import { renameSync as renameSync3 } from "fs";
23666
+ import { mkdir } from "fs/promises";
22751
23667
  import { homedir } from "os";
22752
23668
  import { join as join3 } from "path";
22753
23669
  function defaultDataDir() {
@@ -22762,6 +23678,9 @@ function dataDir(base = defaultDataDir()) {
22762
23678
  function dbPath(base = defaultDataDir()) {
22763
23679
  return join3(dataDir(base), "aka.db");
22764
23680
  }
23681
+ function ensureLayoutDirSync(dir = defaultDataDir()) {
23682
+ ensureDataDirSync(dir);
23683
+ }
22765
23684
  function migrateLegacyLayout(base = defaultDataDir()) {
22766
23685
  const moves = [
22767
23686
  { name: "config.json", dest: settingsDir(base) },
@@ -22769,19 +23688,17 @@ function migrateLegacyLayout(base = defaultDataDir()) {
22769
23688
  ];
22770
23689
  for (const { name, dest } of moves) {
22771
23690
  try {
22772
- mkdirSync2(dest, { recursive: true, mode: DATA_DIR_MODE });
22773
- try {
22774
- chmodSync3(dest, DATA_DIR_MODE);
22775
- } catch {
22776
- }
22777
- renameSync3(join3(base, name), join3(dest, name));
23691
+ ensureDataDirSync(dest);
23692
+ const moved = join3(dest, name);
23693
+ renameSync3(join3(base, name), moved);
23694
+ tightenFile(moved);
22778
23695
  } catch {
22779
23696
  }
22780
23697
  }
22781
23698
  }
22782
23699
 
22783
23700
  // ../../packages/persistence/src/settings.ts
22784
- import { readFileSync as readFileSync2, renameSync as renameSync4, writeFileSync as writeFileSync2 } from "fs";
23701
+ import { readFileSync as readFileSync2 } from "fs";
22785
23702
  import { join as join4 } from "path";
22786
23703
  function readWorkspaceSettings(base = defaultDataDir()) {
22787
23704
  const record2 = readJson(join4(settingsDir(base), "settings.json"));
@@ -22803,7 +23720,7 @@ function readJson(file2) {
22803
23720
  }
22804
23721
 
22805
23722
  // ../../packages/persistence/src/warn-era-cap.ts
22806
- import { existsSync as existsSync2, writeFileSync as writeFileSync3 } from "fs";
23723
+ import { existsSync as existsSync2, writeFileSync as writeFileSync2 } from "fs";
22807
23724
  import { join as join5 } from "path";
22808
23725
  var MARKER = "warn-era-capped";
22809
23726
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
@@ -22811,11 +23728,15 @@ function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
22811
23728
  const marker = join5(dataDir2, MARKER);
22812
23729
  if (existsSync2(marker)) return { capped: 0, skipped: "already-run" };
22813
23730
  const capped = db.policies.capCategoryActions();
22814
- writeFileSync3(marker, `${new Date(Date.now()).toISOString()}
23731
+ writeFileSync2(marker, `${new Date(Date.now()).toISOString()}
22815
23732
  `, { mode: DATA_FILE_MODE });
22816
23733
  return { capped };
22817
23734
  }
22818
23735
 
23736
+ // ../../packages/plugin-sdk/src/config.ts
23737
+ import { existsSync as existsSync3 } from "fs";
23738
+ import { join as join6 } from "path";
23739
+
22819
23740
  // ../../packages/plugin-sdk/src/provider-env.ts
22820
23741
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
22821
23742
  var booleanish = external_exports.string().optional().transform((v) => {
@@ -22866,6 +23787,12 @@ function resolveProvider() {
22866
23787
 
22867
23788
  // ../../packages/plugin-sdk/src/config.ts
22868
23789
  function loadConfig(base = defaultDataDir()) {
23790
+ try {
23791
+ ensureLayoutDirSync(base);
23792
+ const settingsFile = join6(settingsDir(base), "settings.json");
23793
+ if (existsSync3(settingsFile)) tightenFile(settingsFile);
23794
+ } catch {
23795
+ }
22869
23796
  migrateLegacyLayout(base);
22870
23797
  const settings = readWorkspaceSettings(base);
22871
23798
  return {
@@ -22888,15 +23815,583 @@ function resolveProviderSafe() {
22888
23815
  // ../../packages/plugin-sdk/src/config-inventory.ts
22889
23816
  import { readdirSync, readFileSync as readFileSync4, realpathSync, statSync as statSync2 } from "fs";
22890
23817
  import { homedir as homedir2 } from "os";
22891
- import { basename as basename2, join as join7 } from "path";
23818
+ import { basename as basename2, join as join8 } from "path";
23819
+
23820
+ // ../../packages/detections/src/egress/registry.ts
23821
+ var EXTRACTOR_VERSION = "1";
23822
+ var PROVIDER_REGISTRY = [
23823
+ {
23824
+ id: "stripe",
23825
+ name: "Stripe",
23826
+ category: "Payments",
23827
+ hostSuffixes: ["stripe.com"],
23828
+ apiBase: "https://api.stripe.com",
23829
+ defaultDataClasses: ["pii", "customer"],
23830
+ sdks: {
23831
+ npm: ["stripe"],
23832
+ pypi: ["stripe"],
23833
+ go: ["github.com/stripe/stripe-go"],
23834
+ maven: ["com.stripe"],
23835
+ rubygems: ["stripe"],
23836
+ composer: ["stripe/stripe-php"],
23837
+ nuget: ["Stripe.net"]
23838
+ }
23839
+ },
23840
+ {
23841
+ id: "datadog",
23842
+ name: "Datadog",
23843
+ category: "Observability",
23844
+ hostSuffixes: ["datadoghq.com", "datadoghq.eu"],
23845
+ apiBase: "https://api.datadoghq.com",
23846
+ defaultDataClasses: ["telemetry", "logs", "metrics"],
23847
+ sdks: {
23848
+ npm: ["dd-trace", "@datadog/browser-logs"],
23849
+ pypi: ["datadog", "ddtrace"],
23850
+ go: ["github.com/DataDog/dd-trace-go"],
23851
+ maven: ["com.datadoghq"],
23852
+ rubygems: ["ddtrace", "dogapi"],
23853
+ nuget: ["Datadog.Trace"]
23854
+ }
23855
+ },
23856
+ {
23857
+ id: "newrelic",
23858
+ name: "New Relic",
23859
+ category: "Observability",
23860
+ hostSuffixes: ["newrelic.com", "nr-data.net"],
23861
+ apiBase: "https://api.newrelic.com",
23862
+ defaultDataClasses: ["telemetry", "logs", "metrics"],
23863
+ sdks: {
23864
+ npm: ["newrelic"],
23865
+ pypi: ["newrelic"],
23866
+ go: ["github.com/newrelic/go-agent"],
23867
+ maven: ["com.newrelic.agent.java"],
23868
+ rubygems: ["newrelic_rpm"],
23869
+ nuget: ["NewRelic.Agent"]
23870
+ }
23871
+ },
23872
+ {
23873
+ id: "sentry",
23874
+ name: "Sentry",
23875
+ category: "Error tracking",
23876
+ hostSuffixes: ["sentry.io"],
23877
+ apiBase: "https://sentry.io",
23878
+ defaultDataClasses: ["source", "telemetry"],
23879
+ sdks: {
23880
+ npm: ["@sentry/node", "@sentry/react", "@sentry/nextjs"],
23881
+ pypi: ["sentry-sdk"],
23882
+ go: ["github.com/getsentry/sentry-go"],
23883
+ maven: ["io.sentry"],
23884
+ rubygems: ["sentry-ruby"],
23885
+ cargo: ["sentry"],
23886
+ composer: ["sentry/sentry"],
23887
+ nuget: ["Sentry"]
23888
+ }
23889
+ },
23890
+ {
23891
+ id: "openai",
23892
+ name: "OpenAI",
23893
+ category: "LLM provider",
23894
+ hostSuffixes: ["openai.com"],
23895
+ apiBase: "https://api.openai.com",
23896
+ defaultDataClasses: ["pii", "source"],
23897
+ sdks: {
23898
+ npm: ["openai"],
23899
+ pypi: ["openai"],
23900
+ go: ["github.com/sashabaranov/go-openai"],
23901
+ maven: ["com.openai"],
23902
+ rubygems: ["ruby-openai"],
23903
+ cargo: ["async-openai"],
23904
+ composer: ["openai-php/client"],
23905
+ nuget: ["OpenAI"]
23906
+ }
23907
+ },
23908
+ {
23909
+ id: "anthropic",
23910
+ name: "Anthropic",
23911
+ category: "LLM provider",
23912
+ hostSuffixes: ["anthropic.com"],
23913
+ apiBase: "https://api.anthropic.com",
23914
+ defaultDataClasses: ["pii", "source"],
23915
+ sdks: {
23916
+ npm: ["@anthropic-ai/sdk"],
23917
+ pypi: ["anthropic"],
23918
+ go: ["github.com/anthropics/anthropic-sdk-go"],
23919
+ nuget: ["Anthropic.SDK"]
23920
+ }
23921
+ },
23922
+ {
23923
+ id: "aws",
23924
+ name: "Amazon Web Services",
23925
+ category: "Cloud platform",
23926
+ hostSuffixes: ["amazonaws.com"],
23927
+ apiBase: "https://s3.amazonaws.com",
23928
+ defaultDataClasses: ["secrets", "customer"],
23929
+ sdks: {
23930
+ npm: ["@aws-sdk/client-s3", "aws-sdk"],
23931
+ pypi: ["boto3"],
23932
+ go: ["github.com/aws/aws-sdk-go", "github.com/aws/aws-sdk-go-v2"],
23933
+ maven: ["com.amazonaws", "software.amazon.awssdk"],
23934
+ rubygems: ["aws-sdk-s3"],
23935
+ cargo: ["aws-sdk-s3"],
23936
+ nuget: ["AWSSDK.S3"]
23937
+ }
23938
+ },
23939
+ {
23940
+ id: "gcp",
23941
+ name: "Google Cloud",
23942
+ category: "Cloud platform",
23943
+ hostSuffixes: ["googleapis.com"],
23944
+ apiBase: "https://storage.googleapis.com",
23945
+ defaultDataClasses: ["customer", "logs"],
23946
+ sdks: {
23947
+ npm: ["@google-cloud/storage"],
23948
+ pypi: ["google-cloud-storage"],
23949
+ go: ["cloud.google.com/go"],
23950
+ maven: ["com.google.cloud"],
23951
+ rubygems: ["google-cloud-storage"],
23952
+ nuget: ["Google.Cloud.Storage.V1"]
23953
+ }
23954
+ },
23955
+ {
23956
+ id: "azure",
23957
+ name: "Microsoft Azure",
23958
+ category: "Cloud platform",
23959
+ hostSuffixes: ["azure.com", "windows.net"],
23960
+ apiBase: "https://management.azure.com",
23961
+ defaultDataClasses: ["customer", "logs"],
23962
+ sdks: {
23963
+ npm: ["@azure/storage-blob"],
23964
+ pypi: ["azure-storage-blob"],
23965
+ go: ["github.com/Azure/azure-sdk-for-go"],
23966
+ maven: ["com.azure"],
23967
+ rubygems: ["azure-storage-blob"],
23968
+ nuget: ["Azure.Storage.Blobs"]
23969
+ }
23970
+ },
23971
+ {
23972
+ id: "slack",
23973
+ name: "Slack",
23974
+ category: "Notifications",
23975
+ hostSuffixes: ["slack.com"],
23976
+ apiBase: "https://slack.com/api",
23977
+ defaultDataClasses: ["logs"],
23978
+ sdks: {
23979
+ npm: ["@slack/web-api"],
23980
+ pypi: ["slack-sdk"],
23981
+ go: ["github.com/slack-go/slack"],
23982
+ maven: ["com.slack.api"],
23983
+ rubygems: ["slack-ruby-client"],
23984
+ composer: ["slack-php/slack-api"],
23985
+ nuget: ["SlackNet"]
23986
+ }
23987
+ },
23988
+ {
23989
+ id: "segment",
23990
+ name: "Segment",
23991
+ category: "Analytics",
23992
+ hostSuffixes: ["segment.io", "segment.com"],
23993
+ apiBase: "https://api.segment.io",
23994
+ defaultDataClasses: ["customer"],
23995
+ sdks: {
23996
+ npm: ["@segment/analytics-node", "analytics-node"],
23997
+ pypi: ["segment-analytics-python"],
23998
+ go: ["github.com/segmentio/analytics-go"],
23999
+ maven: ["com.segment.analytics.java"],
24000
+ rubygems: ["analytics-ruby"],
24001
+ nuget: ["Analytics"]
24002
+ }
24003
+ },
24004
+ {
24005
+ id: "twilio",
24006
+ name: "Twilio",
24007
+ category: "Communications",
24008
+ hostSuffixes: ["twilio.com"],
24009
+ apiBase: "https://api.twilio.com",
24010
+ defaultDataClasses: ["pii", "customer"],
24011
+ sdks: {
24012
+ npm: ["twilio"],
24013
+ pypi: ["twilio"],
24014
+ go: ["github.com/twilio/twilio-go"],
24015
+ maven: ["com.twilio.sdk"],
24016
+ rubygems: ["twilio-ruby"],
24017
+ composer: ["twilio/sdk"],
24018
+ nuget: ["Twilio"]
24019
+ }
24020
+ },
24021
+ {
24022
+ id: "sendgrid",
24023
+ name: "SendGrid",
24024
+ category: "Email",
24025
+ hostSuffixes: ["sendgrid.com"],
24026
+ apiBase: "https://api.sendgrid.com",
24027
+ defaultDataClasses: ["pii"],
24028
+ sdks: {
24029
+ npm: ["@sendgrid/mail"],
24030
+ pypi: ["sendgrid"],
24031
+ go: ["github.com/sendgrid/sendgrid-go"],
24032
+ maven: ["com.sendgrid"],
24033
+ rubygems: ["sendgrid-ruby"],
24034
+ composer: ["sendgrid/sendgrid"],
24035
+ nuget: ["SendGrid"]
24036
+ }
24037
+ },
24038
+ {
24039
+ id: "mailgun",
24040
+ name: "Mailgun",
24041
+ category: "Email",
24042
+ hostSuffixes: ["mailgun.net"],
24043
+ apiBase: "https://api.mailgun.net",
24044
+ defaultDataClasses: ["pii"],
24045
+ sdks: {
24046
+ npm: ["mailgun.js"],
24047
+ pypi: ["mailgun"],
24048
+ rubygems: ["mailgun-ruby"],
24049
+ composer: ["mailgun/mailgun-php"],
24050
+ nuget: ["Mailgun"]
24051
+ }
24052
+ },
24053
+ {
24054
+ id: "mixpanel",
24055
+ name: "Mixpanel",
24056
+ category: "Analytics",
24057
+ hostSuffixes: ["mixpanel.com"],
24058
+ apiBase: "https://api.mixpanel.com",
24059
+ defaultDataClasses: ["customer", "telemetry"],
24060
+ sdks: {
24061
+ npm: ["mixpanel"],
24062
+ pypi: ["mixpanel"],
24063
+ rubygems: ["mixpanel-ruby"],
24064
+ nuget: ["Mixpanel"]
24065
+ }
24066
+ },
24067
+ {
24068
+ id: "amplitude",
24069
+ name: "Amplitude",
24070
+ category: "Analytics",
24071
+ hostSuffixes: ["amplitude.com"],
24072
+ apiBase: "https://api2.amplitude.com",
24073
+ defaultDataClasses: ["customer", "telemetry"],
24074
+ sdks: {
24075
+ npm: ["@amplitude/analytics-node"],
24076
+ pypi: ["amplitude-analytics"],
24077
+ nuget: ["Amplitude"]
24078
+ }
24079
+ },
24080
+ {
24081
+ id: "posthog",
24082
+ name: "PostHog",
24083
+ category: "Analytics",
24084
+ hostSuffixes: ["posthog.com"],
24085
+ apiBase: "https://us.i.posthog.com",
24086
+ defaultDataClasses: ["customer", "telemetry"],
24087
+ sdks: {
24088
+ npm: ["posthog-node", "posthog-js"],
24089
+ pypi: ["posthog"],
24090
+ go: ["github.com/posthog/posthog-go"],
24091
+ rubygems: ["posthog-ruby"],
24092
+ composer: ["posthog/posthog-php"],
24093
+ nuget: ["PostHog"]
24094
+ }
24095
+ },
24096
+ {
24097
+ id: "honeycomb",
24098
+ name: "Honeycomb",
24099
+ category: "Observability",
24100
+ hostSuffixes: ["honeycomb.io"],
24101
+ apiBase: "https://api.honeycomb.io",
24102
+ defaultDataClasses: ["telemetry", "metrics"],
24103
+ sdks: {
24104
+ npm: ["libhoney"],
24105
+ pypi: ["libhoney"],
24106
+ go: ["github.com/honeycombio/libhoney-go"],
24107
+ rubygems: ["libhoney"]
24108
+ }
24109
+ },
24110
+ {
24111
+ id: "grafana",
24112
+ name: "Grafana Cloud",
24113
+ category: "Observability",
24114
+ hostSuffixes: ["grafana.net"],
24115
+ apiBase: "https://grafana.net",
24116
+ defaultDataClasses: ["logs", "metrics"],
24117
+ sdks: {
24118
+ npm: ["@grafana/faro-web-sdk"]
24119
+ }
24120
+ },
24121
+ {
24122
+ id: "splunk",
24123
+ name: "Splunk",
24124
+ category: "Observability",
24125
+ hostSuffixes: ["splunkcloud.com", "splunk.com"],
24126
+ apiBase: "https://http-inputs.splunkcloud.com",
24127
+ defaultDataClasses: ["logs"],
24128
+ sdks: {
24129
+ npm: ["splunk-logging"],
24130
+ pypi: ["splunk-sdk"],
24131
+ maven: ["com.splunk"],
24132
+ nuget: ["Splunk.Logging.Common"]
24133
+ }
24134
+ },
24135
+ {
24136
+ id: "pagerduty",
24137
+ name: "PagerDuty",
24138
+ category: "Incident response",
24139
+ hostSuffixes: ["pagerduty.com"],
24140
+ apiBase: "https://api.pagerduty.com",
24141
+ defaultDataClasses: ["logs"],
24142
+ sdks: {
24143
+ npm: ["@pagerduty/pdjs"],
24144
+ pypi: ["pdpyras"],
24145
+ go: ["github.com/PagerDuty/go-pagerduty"],
24146
+ rubygems: ["pagerduty"]
24147
+ }
24148
+ },
24149
+ {
24150
+ id: "github",
24151
+ name: "GitHub",
24152
+ category: "Developer platform",
24153
+ hostSuffixes: ["github.com", "githubusercontent.com"],
24154
+ apiBase: "https://api.github.com",
24155
+ defaultDataClasses: ["source"],
24156
+ sdks: {
24157
+ npm: ["@octokit/rest", "octokit"],
24158
+ pypi: ["pygithub"],
24159
+ go: ["github.com/google/go-github"],
24160
+ maven: ["org.kohsuke.github-api"],
24161
+ rubygems: ["octokit"],
24162
+ cargo: ["octocrab"],
24163
+ composer: ["knplabs/github-api"],
24164
+ nuget: ["Octokit"]
24165
+ }
24166
+ },
24167
+ {
24168
+ id: "gitlab",
24169
+ name: "GitLab",
24170
+ category: "Developer platform",
24171
+ hostSuffixes: ["gitlab.com"],
24172
+ apiBase: "https://gitlab.com/api",
24173
+ defaultDataClasses: ["source"],
24174
+ sdks: {
24175
+ npm: ["@gitbeaker/rest"],
24176
+ pypi: ["python-gitlab"],
24177
+ go: ["gitlab.com/gitlab-org/api/client-go"],
24178
+ rubygems: ["gitlab"],
24179
+ nuget: ["GitLabApiClient"]
24180
+ }
24181
+ },
24182
+ {
24183
+ id: "auth0",
24184
+ name: "Auth0",
24185
+ category: "Identity",
24186
+ hostSuffixes: ["auth0.com"],
24187
+ apiBase: "https://login.auth0.com",
24188
+ defaultDataClasses: ["pii"],
24189
+ sdks: {
24190
+ npm: ["auth0"],
24191
+ pypi: ["auth0-python"],
24192
+ go: ["github.com/auth0/go-auth0"],
24193
+ maven: ["com.auth0"],
24194
+ rubygems: ["auth0"],
24195
+ composer: ["auth0/auth0-php"],
24196
+ nuget: ["Auth0.ManagementApi"]
24197
+ }
24198
+ },
24199
+ {
24200
+ id: "okta",
24201
+ name: "Okta",
24202
+ category: "Identity",
24203
+ hostSuffixes: ["okta.com", "oktapreview.com"],
24204
+ apiBase: "https://login.okta.com",
24205
+ defaultDataClasses: ["pii"],
24206
+ sdks: {
24207
+ npm: ["@okta/okta-sdk-nodejs"],
24208
+ pypi: ["okta"],
24209
+ go: ["github.com/okta/okta-sdk-golang"],
24210
+ maven: ["com.okta.sdk"],
24211
+ nuget: ["Okta.Sdk"]
24212
+ }
24213
+ },
24214
+ {
24215
+ id: "clerk",
24216
+ name: "Clerk",
24217
+ category: "Identity",
24218
+ hostSuffixes: ["clerk.com", "clerk.dev"],
24219
+ apiBase: "https://api.clerk.com",
24220
+ defaultDataClasses: ["pii"],
24221
+ sdks: {
24222
+ npm: ["@clerk/backend", "@clerk/nextjs"],
24223
+ pypi: ["clerk-backend-api"],
24224
+ go: ["github.com/clerk/clerk-sdk-go"]
24225
+ }
24226
+ },
24227
+ {
24228
+ id: "supabase",
24229
+ name: "Supabase",
24230
+ category: "Backend platform",
24231
+ hostSuffixes: ["supabase.co", "supabase.com"],
24232
+ apiBase: "https://api.supabase.com",
24233
+ defaultDataClasses: ["pii", "customer"],
24234
+ sdks: {
24235
+ npm: ["@supabase/supabase-js"],
24236
+ pypi: ["supabase"],
24237
+ cargo: ["postgrest"]
24238
+ }
24239
+ },
24240
+ {
24241
+ id: "firebase",
24242
+ name: "Firebase",
24243
+ category: "Backend platform",
24244
+ hostSuffixes: ["firebaseio.com", "firebase.google.com"],
24245
+ apiBase: "https://firebaseio.com",
24246
+ defaultDataClasses: ["customer"],
24247
+ sdks: {
24248
+ npm: ["firebase", "firebase-admin"],
24249
+ pypi: ["firebase-admin"],
24250
+ go: ["firebase.google.com/go"],
24251
+ maven: ["com.google.firebase"]
24252
+ }
24253
+ },
24254
+ {
24255
+ id: "mongodb-atlas",
24256
+ name: "MongoDB Atlas",
24257
+ category: "Database SaaS",
24258
+ hostSuffixes: ["mongodb.net", "mongodb.com"],
24259
+ apiBase: "https://cloud.mongodb.com",
24260
+ defaultDataClasses: ["customer"],
24261
+ sdks: {
24262
+ npm: ["mongodb"],
24263
+ pypi: ["pymongo"],
24264
+ go: ["go.mongodb.org/mongo-driver"],
24265
+ maven: ["org.mongodb"],
24266
+ rubygems: ["mongo"],
24267
+ cargo: ["mongodb"],
24268
+ nuget: ["MongoDB.Driver"]
24269
+ }
24270
+ },
24271
+ {
24272
+ id: "planetscale",
24273
+ name: "PlanetScale",
24274
+ category: "Database SaaS",
24275
+ hostSuffixes: ["psdb.cloud", "planetscale.com"],
24276
+ apiBase: "https://api.planetscale.com",
24277
+ defaultDataClasses: ["customer"],
24278
+ sdks: {
24279
+ npm: ["@planetscale/database"],
24280
+ go: ["github.com/planetscale/planetscale-go"]
24281
+ }
24282
+ },
24283
+ {
24284
+ id: "algolia",
24285
+ name: "Algolia",
24286
+ category: "Search SaaS",
24287
+ hostSuffixes: ["algolia.net", "algolianet.com"],
24288
+ apiBase: "https://algolia.net",
24289
+ defaultDataClasses: ["customer"],
24290
+ sdks: {
24291
+ npm: ["algoliasearch"],
24292
+ pypi: ["algoliasearch"],
24293
+ go: ["github.com/algolia/algoliasearch-client-go"],
24294
+ maven: ["com.algolia"],
24295
+ rubygems: ["algolia"],
24296
+ composer: ["algolia/algoliasearch-client-php"],
24297
+ nuget: ["Algolia.Search"]
24298
+ }
24299
+ },
24300
+ {
24301
+ id: "cloudflare",
24302
+ name: "Cloudflare",
24303
+ category: "CDN / edge",
24304
+ hostSuffixes: ["cloudflare.com", "workers.dev"],
24305
+ apiBase: "https://api.cloudflare.com",
24306
+ defaultDataClasses: ["logs"],
24307
+ sdks: {
24308
+ npm: ["cloudflare"],
24309
+ pypi: ["cloudflare"],
24310
+ go: ["github.com/cloudflare/cloudflare-go"],
24311
+ nuget: ["CloudFlare.Client"]
24312
+ }
24313
+ },
24314
+ {
24315
+ id: "huggingface",
24316
+ name: "Hugging Face",
24317
+ category: "LLM provider",
24318
+ hostSuffixes: ["huggingface.co"],
24319
+ apiBase: "https://api-inference.huggingface.co",
24320
+ defaultDataClasses: ["source"],
24321
+ sdks: {
24322
+ npm: ["@huggingface/inference"],
24323
+ pypi: ["huggingface-hub", "transformers"],
24324
+ rubygems: ["hugging-face"]
24325
+ }
24326
+ },
24327
+ {
24328
+ id: "cohere",
24329
+ name: "Cohere",
24330
+ category: "LLM provider",
24331
+ hostSuffixes: ["cohere.com", "cohere.ai"],
24332
+ apiBase: "https://api.cohere.com",
24333
+ defaultDataClasses: ["pii", "source"],
24334
+ sdks: {
24335
+ npm: ["cohere-ai"],
24336
+ pypi: ["cohere"],
24337
+ go: ["github.com/cohere-ai/cohere-go"]
24338
+ }
24339
+ },
24340
+ {
24341
+ id: "mistral",
24342
+ name: "Mistral AI",
24343
+ category: "LLM provider",
24344
+ hostSuffixes: ["mistral.ai"],
24345
+ apiBase: "https://api.mistral.ai",
24346
+ defaultDataClasses: ["pii", "source"],
24347
+ sdks: {
24348
+ npm: ["@mistralai/mistralai"],
24349
+ pypi: ["mistralai"],
24350
+ go: ["github.com/gage-technologies/mistral-go"]
24351
+ }
24352
+ }
24353
+ ];
24354
+ var EGRESS_VERSION_MATERIAL = `${EXTRACTOR_VERSION}
24355
+ ${JSON.stringify(PROVIDER_REGISTRY)}`;
24356
+
24357
+ // ../../packages/detections/src/egress/extract.ts
24358
+ var SECRET_KEY_NAMES = "api[_-]?key|apikey|private[_-]?key|access[_-]?key|access[_-]?token|token|secret|credentials?|password|passwd|pwd|authorization|sig|signature|sas|assertion";
24359
+ var AUTH_SCHEMES = "Bearer|Basic|Token|Digest|ApiKey|SSWS|AWS4-HMAC-SHA256";
24360
+ var SECRET_VALUE = new RegExp(
24361
+ `((?:${SECRET_KEY_NAMES})['"\`]?\\s*[:=]\\s*['"\`]?)(?!(?:${AUTH_SCHEMES})[\\s'"\`])[^\\s'"\`&]+`,
24362
+ "gi"
24363
+ );
24364
+ var AUTH_SCHEME_VALUE = new RegExp(
24365
+ `((?:${SECRET_KEY_NAMES})['"\`]?\\s*[:=]\\s*['"\`]?)(${AUTH_SCHEMES})\\s+[^\\s'"\`]+`,
24366
+ "gi"
24367
+ );
24368
+ var WEBHOOK_SECRET_PATHS = [
24369
+ { hosts: ["hooks.slack.com"], prefix: "/services/" },
24370
+ {
24371
+ hosts: ["discord.com", "discordapp.com", "ptb.discord.com", "canary.discord.com"],
24372
+ prefix: "/api/webhooks/"
24373
+ },
24374
+ { hosts: ["hooks.zapier.com"], prefix: "/hooks/" },
24375
+ { hosts: ["outlook.office.com", "outlook.office365.com"], prefix: "/webhook/" }
24376
+ ];
24377
+ function escapeRegExp(literal2) {
24378
+ return literal2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
24379
+ }
24380
+ var WEBHOOK_URL = new RegExp(
24381
+ `(https?://(?:${WEBHOOK_SECRET_PATHS.flatMap(
24382
+ (entry) => entry.hosts.map((host) => `${escapeRegExp(host)}${escapeRegExp(entry.prefix)}`)
24383
+ ).join("|")}))[^\\s'"\`<>()[\\]{},;]+`,
24384
+ "gi"
24385
+ );
22892
24386
 
22893
24387
  // ../../packages/detections/src/escape-regexp.ts
22894
- function escapeRegExp(value) {
24388
+ function escapeRegExp2(value) {
22895
24389
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
22896
24390
  }
22897
24391
 
22898
24392
  // ../../packages/detections/src/matchers/limits.ts
22899
24393
  var MAX_MATCHES_PER_RULE = 1e4;
24394
+ var MAX_REGEX_INPUT_LENGTH = 2e5;
22900
24395
 
22901
24396
  // ../../packages/detections/src/matchers/keyword.ts
22902
24397
  var KeywordMatcher2 = class {
@@ -22907,7 +24402,7 @@ var KeywordMatcher2 = class {
22907
24402
  for (const kw of keywords) {
22908
24403
  if (kw.length === 0) continue;
22909
24404
  if (spans.length >= MAX_MATCHES_PER_RULE) break;
22910
- const re = new RegExp(escapeRegExp(kw), caseSensitive ? "gu" : "giu");
24405
+ const re = new RegExp(escapeRegExp2(kw), caseSensitive ? "gu" : "giu");
22911
24406
  let m;
22912
24407
  while ((m = re.exec(text)) !== null) {
22913
24408
  spans.push({ start: m.index, end: m.index + m[0].length });
@@ -22924,9 +24419,13 @@ var RegexMatcher2 = class {
22924
24419
  if (rule.matcher.type !== "regex") return [];
22925
24420
  const { pattern, flags, captureGroup } = rule.matcher;
22926
24421
  const re = new RegExp(pattern, flags.includes("d") ? flags : `${flags}d`);
24422
+ const scanText2 = text.length > MAX_REGEX_INPUT_LENGTH ? text.slice(0, MAX_REGEX_INPUT_LENGTH) : text;
22927
24423
  const spans = [];
22928
24424
  let m;
22929
- while ((m = re.exec(text)) !== null) {
24425
+ const maxIterations = scanText2.length + 1;
24426
+ let iterations = 0;
24427
+ while ((m = re.exec(scanText2)) !== null) {
24428
+ if (++iterations > maxIterations) break;
22930
24429
  const group = captureGroup != null ? m[captureGroup] : m[0];
22931
24430
  if (m[0].length === 0) re.lastIndex++;
22932
24431
  if (group && spans.length < MAX_MATCHES_PER_RULE) {
@@ -23001,6 +24500,31 @@ var CONFIG_POSTURE_RULES = [
23001
24500
  }
23002
24501
  ];
23003
24502
 
24503
+ // ../../packages/detections/src/security/redos-probe.ts
24504
+ var EXPONENTIAL_UNITS = [
24505
+ "a",
24506
+ "0",
24507
+ " ",
24508
+ "x",
24509
+ "ab",
24510
+ "a.",
24511
+ "a-",
24512
+ "a_",
24513
+ "a@",
24514
+ "a/",
24515
+ "a:",
24516
+ "a=",
24517
+ "a;",
24518
+ "aA0",
24519
+ " "
24520
+ ];
24521
+ var EXPONENTIAL_PROBES = EXPONENTIAL_UNITS.flatMap(
24522
+ (unit) => [23, 25].map((len) => unit.repeat(Math.ceil(len / unit.length)).slice(0, len) + "!")
24523
+ );
24524
+ var POLYNOMIAL_PROBES = ["abc-", "a.", "a ", "a=", "x", "0", "a@", "a/", "ab"].map(
24525
+ (unit) => unit.repeat(1e4).slice(0, 4e4) + "!"
24526
+ );
24527
+
23004
24528
  // ../../rules/code-flaws/auth-jwt-no-verify.json
23005
24529
  var auth_jwt_no_verify_default = {
23006
24530
  specVersion: 1,
@@ -25027,26 +26551,27 @@ function bundledDetections() {
25027
26551
  }
25028
26552
 
25029
26553
  // ../../packages/plugin-sdk/src/repo.ts
25030
- import { existsSync as existsSync3, readFileSync as readFileSync3, statSync } from "fs";
25031
- import { basename, dirname, isAbsolute, join as join6, sep as sep2 } from "path";
26554
+ import { existsSync as existsSync4, readFileSync as readFileSync3, statSync } from "fs";
26555
+ import { basename, dirname, isAbsolute, join as join7, sep as sep2 } from "path";
25032
26556
 
25033
26557
  // ../../packages/plugin-sdk/src/events.ts
25034
- import { createHash as createHash3, randomUUID as randomUUID9 } from "crypto";
25035
-
25036
- // ../../packages/plugin-sdk/src/finding-key.ts
25037
- import { createHash as createHash4 } from "crypto";
26558
+ import { createHash as createHash4, randomUUID as randomUUID9 } from "crypto";
25038
26559
 
25039
26560
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
25040
26561
  import { arch, hostname as hostname3, platform, release } from "os";
25041
26562
 
25042
26563
  // ../../packages/plugin-sdk/src/nudge.ts
25043
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "fs";
25044
- import { join as join8 } from "path";
26564
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
26565
+ import { join as join9 } from "path";
26566
+
26567
+ // ../../packages/plugin-sdk/src/paths.ts
26568
+ import { readdirSync as readdirSync2, realpathSync as realpathSync2 } from "fs";
26569
+ import { basename as basename3, dirname as dirname2, sep as sep3 } from "path";
25045
26570
 
25046
26571
  // ../../packages/plugin-sdk/src/project-files.ts
25047
26572
  var import_ignore = __toESM(require_ignore(), 1);
25048
- import { existsSync as existsSync4, readdirSync as readdirSync2, readFileSync as readFileSync6 } from "fs";
25049
- import { basename as basename3, join as join9, relative, sep as sep3 } from "path";
26573
+ import { existsSync as existsSync5, readdirSync as readdirSync3, readFileSync as readFileSync6 } from "fs";
26574
+ import { basename as basename4, join as join10, relative, sep as sep4 } from "path";
25050
26575
 
25051
26576
  // ../../packages/plugin-sdk/src/runtime.ts
25052
26577
  import { randomUUID as randomUUID10 } from "crypto";
@@ -25055,8 +26580,8 @@ import { randomUUID as randomUUID10 } from "crypto";
25055
26580
  var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
25056
26581
 
25057
26582
  // ../../packages/plugin-sdk/src/throttle.ts
25058
- import { mkdirSync as mkdirSync4, statSync as statSync3, writeFileSync as writeFileSync5 } from "fs";
25059
- import { join as join10 } from "path";
26583
+ import { mkdirSync as mkdirSync3, statSync as statSync3, writeFileSync as writeFileSync4 } from "fs";
26584
+ import { join as join11 } from "path";
25060
26585
 
25061
26586
  // ../../packages/plugin-runtime/src/standalone-gateway.ts
25062
26587
  import { randomUUID as randomUUID11 } from "crypto";
@@ -25087,7 +26612,8 @@ var StandaloneDataGateway = class {
25087
26612
  }
25088
26613
  // The id is minted inside the repository from the natural key — the plugin can't
25089
26614
  // import @akasecurity/persistence to compute it, so the gateway is the boundary that
25090
- // hands the natural key across. INSERT OR IGNORE → idempotent re-reads.
26615
+ // hands the natural key across. UPSERT-take-MAX → idempotent re-reads that also
26616
+ // converge a streaming partial/final split (see insertLlmCall).
25091
26617
  recordLlmCall(input) {
25092
26618
  this.db.auditEvents.insertLlmCall(input);
25093
26619
  return Promise.resolve();
@@ -25129,7 +26655,9 @@ var StandaloneDataGateway = class {
25129
26655
  // caller's transaction (Layer 2b). The audit-event id the findings FK into is the
25130
26656
  // SAME content-addressed `toolCallId` the leaf insert mints, so both re-read
25131
26657
  // idempotently. Definitions/classified-data are idempotent upserts; findings are
25132
- // content-addressed INSERT OR IGNORE.
26658
+ // content-addressed upserts (ON CONFLICT(id) DO UPDATE SET inspection_definition_id),
26659
+ // so a re-detection under a bumped rule version repoints the definition FK rather
26660
+ // than no-opping.
25133
26661
  writeToolCall(input) {
25134
26662
  this.db.auditEvents.insertToolCall(input);
25135
26663
  if (input.inspections.length === 0) return;
@@ -25149,7 +26677,7 @@ var StandaloneDataGateway = class {
25149
26677
  });
25150
26678
  const classifiedDataId2 = this.db.classifiedData.upsert({ class: insp.category });
25151
26679
  this.db.inspectionFindings.insertFinding({
25152
- id: inspectionFindingId(auditEventId, definitionId, insp.span.start, insp.span.end),
26680
+ id: inspectionFindingId(auditEventId, insp.ruleId, insp.span.start, insp.span.end),
25153
26681
  auditEventId,
25154
26682
  inspectionDefinitionId: definitionId,
25155
26683
  classifiedDataId: classifiedDataId2,
@@ -25198,10 +26726,17 @@ var StandaloneDataGateway = class {
25198
26726
  try {
25199
26727
  const snapshot = this.db.installedPacks.installedRuleset();
25200
26728
  if (snapshot.installedPacks === 0) return void 0;
25201
- if (snapshot.enabledPacks === 0) return { rules: [], ruleActions: /* @__PURE__ */ new Map(), complete: true };
26729
+ if (snapshot.enabledPacks === 0) {
26730
+ return { rules: [], ruleActions: /* @__PURE__ */ new Map(), ruleVersions: /* @__PURE__ */ new Map(), complete: true };
26731
+ }
25202
26732
  if (snapshot.invalidRules > 0) return void 0;
25203
26733
  if (snapshot.rules.length === 0) return void 0;
25204
- return { rules: snapshot.rules, ruleActions: snapshot.ruleActions, complete: true };
26734
+ return {
26735
+ rules: snapshot.rules,
26736
+ ruleActions: snapshot.ruleActions,
26737
+ ruleVersions: snapshot.ruleVersions,
26738
+ complete: true
26739
+ };
25205
26740
  } catch {
25206
26741
  return void 0;
25207
26742
  }
@@ -25229,6 +26764,7 @@ var StandaloneDataGateway = class {
25229
26764
  policies: [...policies, ...rulePolicies],
25230
26765
  rules: installed ? installed.rules : [],
25231
26766
  ...installed ? { rulesComplete: true } : {},
26767
+ ...installed ? { ruleVersions: Object.fromEntries(installed.ruleVersions) } : {},
25232
26768
  ...exceptions !== void 0 ? { exceptions } : {},
25233
26769
  customKeywords,
25234
26770
  fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -25327,6 +26863,13 @@ var StandaloneDataGateway = class {
25327
26863
  this.db.scanLedger.upsertEntries(entries);
25328
26864
  return Promise.resolve();
25329
26865
  }
26866
+ getRuleProbeVerdict(ruleKey) {
26867
+ return Promise.resolve(this.db.ruleProbeCache.getVerdict(ruleKey));
26868
+ }
26869
+ setRuleProbeVerdict(ruleKey, verdict, worstProbeMs) {
26870
+ this.db.ruleProbeCache.setVerdict(ruleKey, verdict, worstProbeMs);
26871
+ return Promise.resolve();
26872
+ }
25330
26873
  openAtRestKeysForPath(path) {
25331
26874
  return Promise.resolve(this.db.resolutions.openAtRestKeysForPath(path));
25332
26875
  }
@@ -25337,6 +26880,12 @@ var StandaloneDataGateway = class {
25337
26880
  this.db.resolutions.insertResolution(input);
25338
26881
  return Promise.resolve();
25339
26882
  }
26883
+ // Bare forward — no toggle read here. The plugin-path kill-switch is
26884
+ // enforced by the caller, which already holds the parsed workspace
26885
+ // settings; this class only ever sees `dataDir`, not the settings base.
26886
+ recordProjectEgress(input) {
26887
+ return Promise.resolve(this.db.shares.recordProjectEgress(input));
26888
+ }
25340
26889
  close() {
25341
26890
  this.db.close();
25342
26891
  return Promise.resolve();
@@ -25354,12 +26903,12 @@ import { randomUUID as randomUUID12 } from "crypto";
25354
26903
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
25355
26904
 
25356
26905
  // src/command-registry.ts
25357
- import { readdirSync as readdirSync3 } from "fs";
26906
+ import { readdirSync as readdirSync4 } from "fs";
25358
26907
  import { fileURLToPath } from "url";
25359
26908
  var COMMAND_NAMESPACE = "aka";
25360
26909
  var COMMANDS_DIR = fileURLToPath(new URL("../commands", import.meta.url));
25361
26910
  function readRegisteredCommands() {
25362
- return readdirSync3(COMMANDS_DIR).filter((f) => f.endsWith(".md")).map((f) => `/${COMMAND_NAMESPACE}:${f.replace(/\.md$/, "")}`);
26911
+ return readdirSync4(COMMANDS_DIR).filter((f) => f.endsWith(".md")).map((f) => `/${COMMAND_NAMESPACE}:${f.replace(/\.md$/, "")}`);
25363
26912
  }
25364
26913
  function selectRegisteredCommands(curated, registry2) {
25365
26914
  const registered = new Set(registry2);
@@ -25440,8 +26989,8 @@ function table(headers, rows, opts = {}) {
25440
26989
  const widths = headers.map(
25441
26990
  (h, i) => Math.max(visibleLength(h), ...rows.map((r) => visibleLength(r[i] ?? "")))
25442
26991
  );
25443
- const sep4 = " ".repeat(gap);
25444
- const fmt = (cells) => cells.map((cell, i) => padEnd(cell, widths[i] ?? 0)).join(sep4);
26992
+ const sep5 = " ".repeat(gap);
26993
+ const fmt = (cells) => cells.map((cell, i) => padEnd(cell, widths[i] ?? 0)).join(sep5);
25445
26994
  const headerLine = fmt(headers.map((h) => h.toUpperCase()));
25446
26995
  if (opts.rowSep === true) {
25447
26996
  const fullWidth = widths.reduce((n, w) => n + w, 0) + gap * Math.max(0, widths.length - 1);
@@ -25453,7 +27002,7 @@ function table(headers, rows, opts = {}) {
25453
27002
  });
25454
27003
  return [headerLine, rule, ...body].join("\n");
25455
27004
  }
25456
- const ruleLine = widths.map((w) => "\u2500".repeat(w)).join(sep4);
27005
+ const ruleLine = widths.map((w) => "\u2500".repeat(w)).join(sep5);
25457
27006
  return [headerLine, ruleLine, ...rows.map(fmt)].join("\n");
25458
27007
  }
25459
27008
  function fenced(body) {