@akasecurity/ai-tc-claude-code 0.9.11 → 0.9.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH2 = "/";
53
+ var SLASH3 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH2).filter(Boolean);
425
+ const slices = path.split(SLASH3).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH2) + SLASH2,
429
+ slices.join(SLASH3) + SLASH3,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH2).filter(Boolean);
445
+ slices = path.split(SLASH3).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH2) + SLASH2,
452
+ slices.join(SLASH3) + SLASH3,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -502,6 +502,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
502
502
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
503
503
  import { join as join2 } from "path";
504
504
 
505
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
506
+ var DEFERRED_MIGRATION_TAGS = [
507
+ "0031_audit_capture_by_time_index",
508
+ "0032_audit_capture_by_id_index",
509
+ "0033_audit_capture_location_index",
510
+ "0034_findings_read_indexes"
511
+ ];
512
+
505
513
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
506
514
  var SQLITE_MIGRATIONS = [
507
515
  {
@@ -619,6 +627,30 @@ var SQLITE_MIGRATIONS = [
619
627
  {
620
628
  tag: "0028_activity_session_probe_indexes",
621
629
  sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"
630
+ },
631
+ {
632
+ tag: "0029_audit_capture_rollup_index",
633
+ sql: "CREATE INDEX `idx_audit_capture_rollup` ON `audit_events` (`event_type`,`started_at`,`repo`,`id`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
634
+ },
635
+ {
636
+ tag: "0030_audit_content_expiry",
637
+ sql: "ALTER TABLE `audit_events` ADD `content_expired_at` integer;--> statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"
638
+ },
639
+ {
640
+ tag: "0031_audit_capture_by_time_index",
641
+ sql: "CREATE INDEX `idx_audit_capture_by_time` ON `audit_events` (`started_at`,`id`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
642
+ },
643
+ {
644
+ tag: "0032_audit_capture_by_id_index",
645
+ sql: "CREATE INDEX `idx_audit_capture_by_id` ON `audit_events` (`id`,`started_at`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
646
+ },
647
+ {
648
+ tag: "0033_audit_capture_location_index",
649
+ sql: "CREATE INDEX `idx_audit_capture_location` ON `audit_events` (`repo`,`file_path`,`started_at`,`id`,`event_type`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
650
+ },
651
+ {
652
+ tag: "0034_findings_read_indexes",
653
+ sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
622
654
  }
623
655
  ];
624
656
 
@@ -20427,9 +20459,8 @@ var SEVERITY_WEIGHT = {
20427
20459
  medium: 2,
20428
20460
  low: 1
20429
20461
  };
20430
- var SEVERITY_WEIGHT_BY_STRING = SEVERITY_WEIGHT;
20431
20462
  function severityWeight(severity) {
20432
- return SEVERITY_WEIGHT_BY_STRING[severity] ?? 0;
20463
+ return Object.hasOwn(SEVERITY_WEIGHT, severity) ? SEVERITY_WEIGHT[severity] : 0;
20433
20464
  }
20434
20465
  var ADVICE = {
20435
20466
  secret: "Rotate the exposed credentials and move them out of prompts (secrets manager / env vars).",
@@ -20754,6 +20785,15 @@ var FindingCategory = external_exports.enum([
20754
20785
  ]).meta({ id: "FindingCategory" });
20755
20786
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20756
20787
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20788
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20789
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20790
+ var FindingDelivery = external_exports.object({
20791
+ state: FindingDeliveryState,
20792
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20793
+ at: external_exports.iso.datetime().optional(),
20794
+ // Only on `not_sent`, and only when a known reason was recorded.
20795
+ reason: SyncFailureReason.optional()
20796
+ }).meta({ id: "FindingDelivery" });
20757
20797
  var ResolutionMethod = external_exports.enum([
20758
20798
  "enforced-in-flight",
20759
20799
  "fixed-at-source",
@@ -20810,7 +20850,10 @@ var FindingInstance = external_exports.object({
20810
20850
  // The session that event belongs to, when it has one — the seam a
20811
20851
  // per-instance "view session" link needs. Absent for events captured
20812
20852
  // outside a session.
20813
- sessionId: external_exports.string().optional()
20853
+ sessionId: external_exports.string().optional(),
20854
+ // The delivery state of the event above (see FindingDelivery). Optional so
20855
+ // readers that do not project it stay valid.
20856
+ delivery: FindingDelivery.optional()
20814
20857
  }).meta({ id: "FindingInstance" });
20815
20858
  var FindingGroup = external_exports.object({
20816
20859
  id: external_exports.string(),
@@ -20862,7 +20905,10 @@ var FindingFacets = external_exports.object({
20862
20905
  // Host tool (attributes.tool_name). Present only on the instance-level
20863
20906
  // reads, which can filter by it; the type-level read omits the dimension
20864
20907
  // because a group spans tools.
20865
- tool: external_exports.array(FindingFacetItem).optional()
20908
+ tool: external_exports.array(FindingFacetItem).optional(),
20909
+ // Delivery states (FindingDeliveryState). Present only on the
20910
+ // instance-level reads, like `tool`.
20911
+ deployment: external_exports.array(FindingFacetItem).optional()
20866
20912
  }).meta({ id: "FindingFacets" });
20867
20913
  var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20868
20914
  id: "FindingTypeSummary"
@@ -20973,6 +21019,8 @@ var ListFindingInstancesQuery = external_exports.object({
20973
21019
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20974
21020
  // where the free-text `q` can only match the rendered "via Bash" label.
20975
21021
  tool: external_exports.array(external_exports.string()).optional(),
21022
+ // The delivery state of each finding's event (see FindingDelivery).
21023
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20976
21024
  // Exact repository / file-path matches, for the drill-down out of the
20977
21025
  // locations view. A row whose event carries no repo/file matches neither.
20978
21026
  repo: external_exports.string().optional(),
@@ -20993,6 +21041,10 @@ var ListFindingInstancesResponse = external_exports.object({
20993
21041
  items: external_exports.array(FindingInstanceDetail),
20994
21042
  nextCursor: external_exports.string().nullable()
20995
21043
  }).meta({ id: "ListFindingInstancesResponse" });
21044
+ var ListFindingInstancesPage = external_exports.object({
21045
+ items: external_exports.array(FindingInstanceDetail),
21046
+ nextCursor: external_exports.string().nullable()
21047
+ }).meta({ id: "ListFindingInstancesPage" });
20996
21048
  var FindingLocationSummary = external_exports.object({
20997
21049
  // Opaque, stable, minted from the pair by encodeLocationId. It exists
20998
21050
  // because a location's identity is two values and a URL param carries one:
@@ -21035,6 +21087,8 @@ var ListFindingLocationsQuery = external_exports.object({
21035
21087
  // instances that match, and folds its status from those.
21036
21088
  status: external_exports.array(FindingStatus).optional(),
21037
21089
  tool: external_exports.array(external_exports.string()).optional(),
21090
+ // The delivery state of each finding's event (see FindingDelivery).
21091
+ deployment: external_exports.array(FindingDeliveryState).optional(),
21038
21092
  q: external_exports.string().optional(),
21039
21093
  sessionId: external_exports.string().optional(),
21040
21094
  from: external_exports.iso.datetime().optional(),
@@ -21237,6 +21291,10 @@ var CaptureAttributes = external_exports.object({
21237
21291
  // to 'allow' — the enforcement audit trail's link back to the grant that
21238
21292
  // authorized the bypass.
21239
21293
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21294
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21295
+ // join back to the `llm_call` leaf for the same assistant turn.
21296
+ message_id: external_exports.string().optional(),
21297
+ conversation_id: external_exports.string().optional(),
21240
21298
  // Whole milliseconds this capture's inspection blocked its caller — the
21241
21299
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21242
21300
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21245,7 +21303,19 @@ var CaptureAttributes = external_exports.object({
21245
21303
  // inline json_extract and is not itself an optimization.
21246
21304
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21247
21305
  // before the measurement shipped — never present as a placeholder 0.
21248
- inspection_ms: external_exports.number().int().nonnegative().optional()
21306
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21307
+ // What a `redact` this capture could not carry out became instead (see
21308
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21309
+ // degrade actually happened, so absence is the ordinary case rather than a
21310
+ // reader having to distinguish it from a zero.
21311
+ //
21312
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21313
+ // so on a multi-finding row this does not say which finding degraded, and
21314
+ // its presence does not mean the fallback decided the capture's action. A
21315
+ // capture denied by another finding's own Block policy carries `block`
21316
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21317
+ // repeated rather than referenced because a store reader opens this file.
21318
+ redact_degraded_to: ActionTaken.optional()
21249
21319
  }).catchall(external_exports.unknown());
21250
21320
  var ToolCallInspection = external_exports.object({
21251
21321
  ruleId: external_exports.string().min(1),
@@ -21444,7 +21514,17 @@ var AuditEvent = external_exports.object({
21444
21514
  /** `share` to a first-party/internal destination. */
21445
21515
  internal: external_exports.boolean(),
21446
21516
  /** Event needs review (e.g. unverified egress). */
21447
- flagged: external_exports.boolean()
21517
+ flagged: external_exports.boolean(),
21518
+ /**
21519
+ * The body this event's `title` is drawn from was cleared by local body
21520
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21521
+ *
21522
+ * A separate flag rather than a sentinel written into `title`: the title is
21523
+ * rendered text, and a store-layer module that invented display copy for it
21524
+ * would be choosing words the view is supposed to choose. Additive and
21525
+ * defaulted, so an older producer still validates.
21526
+ */
21527
+ bodyExpired: external_exports.boolean().default(false)
21448
21528
  }).meta({ id: "ActivityAuditEvent" });
21449
21529
  var ActivitySessionSummary = external_exports.object({
21450
21530
  id: external_exports.string(),
@@ -22785,6 +22865,12 @@ var EventMetadata = external_exports.object({
22785
22865
  // to 'allow' — the enforcement audit trail's link back to the grant that
22786
22866
  // authorized the bypass. Absent on captures where no exception applied.
22787
22867
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22868
+ // The assistant message this capture belongs to, and the conversation it sits
22869
+ // in — set by the browser extension's network capture so a stored `response`
22870
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22871
+ // on every other capture path, which has no such id.
22872
+ messageId: external_exports.string().optional(),
22873
+ conversationId: external_exports.string().optional(),
22788
22874
  // How long THIS capture's inspection blocked its caller, in whole
22789
22875
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22790
22876
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22797,7 +22883,37 @@ var EventMetadata = external_exports.object({
22797
22883
  // Absent is also what every pre-measurement client writes, and what a
22798
22884
  // clock failure degrades to — a reader must treat absence as "not measured"
22799
22885
  // and never as a zero, which would read as "inspection is free".
22800
- inspectionMs: external_exports.number().int().nonnegative().optional()
22886
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22887
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22888
+ // workspace's `redactFallback`, applied because the field could not be
22889
+ // masked in place (a shell command, a URL, or any argument on a host whose
22890
+ // hook contract offers no rewrite channel).
22891
+ //
22892
+ // It exists because the action alone cannot say why. A finding recorded as
22893
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22894
+ // assigned Redact on a field that could not take one — and those are
22895
+ // different facts about the same row: the first is a policy the user chose,
22896
+ // the second is a masking the host could not perform. Absent means no
22897
+ // degrade happened, which is every ordinary capture.
22898
+ //
22899
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22900
+ // is the CAPTURE while `actionTaken` is per FINDING:
22901
+ //
22902
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22903
+ // `redact` alongside a finding ASSIGNED the same action stores both
22904
+ // identically and one reason for the pair; attributing it to both
22905
+ // describes the assigned one wrongly, and to neither loses the degrade.
22906
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22907
+ // became, not the reason the capture ended as it did — a capture denied
22908
+ // by some other finding's own Block policy still carries `block` here,
22909
+ // and clearing the workspace's fallback would not have let it through.
22910
+ // Gate on the value against what a fallback can produce; never read the
22911
+ // field's presence as "this was the fallback's doing".
22912
+ //
22913
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22914
+ // Closing either means moving the reason onto the finding row, which
22915
+ // already carries its own action.
22916
+ redactDegradedTo: ActionTaken.optional()
22801
22917
  }).meta({ id: "EventMetadata" });
22802
22918
  var Event = external_exports.object({
22803
22919
  id: external_exports.guid(),
@@ -22907,7 +23023,32 @@ var RotateKeyInput = external_exports.object({
22907
23023
  confirmation: external_exports.string()
22908
23024
  });
22909
23025
 
23026
+ // ../../packages/schema/src/zod/finding-delivery.ts
23027
+ var KNOWN_REASONS = SyncFailureReason.options;
23028
+ function knownReason(value) {
23029
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
23030
+ }
23031
+ function deriveFindingDelivery(row) {
23032
+ if (row.kind === "code_change") return { state: "local_scan" };
23033
+ if (row.syncedAt !== null && row.syncedAt > 0) {
23034
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
23035
+ }
23036
+ if (row.syncedAt !== null) {
23037
+ const reason = knownReason(row.syncFailure);
23038
+ return {
23039
+ state: "not_sent",
23040
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
23041
+ ...reason === void 0 ? {} : { reason }
23042
+ };
23043
+ }
23044
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
23045
+ return { state: "never_offered" };
23046
+ }
23047
+
22910
23048
  // ../../packages/schema/src/zod/findings-group-build.ts
23049
+ function lookupOwn(map2, key) {
23050
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
23051
+ }
22911
23052
  function toApiAction(dbVal) {
22912
23053
  const map2 = {
22913
23054
  log: "monitored",
@@ -22916,7 +23057,7 @@ function toApiAction(dbVal) {
22916
23057
  warn: "warned",
22917
23058
  allow: "allowed"
22918
23059
  };
22919
- return map2[dbVal] ?? "allowed";
23060
+ return lookupOwn(map2, dbVal) ?? "allowed";
22920
23061
  }
22921
23062
  function toApiCategory(dbVal) {
22922
23063
  if (dbVal === "code_context") return "source_code";
@@ -22924,13 +23065,18 @@ function toApiCategory(dbVal) {
22924
23065
  return parsed2.success ? parsed2.data : "custom";
22925
23066
  }
22926
23067
  function toApiProvider(sourceTool) {
22927
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
23068
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22928
23069
  }
22929
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
23070
+ var FINDING_STATUS_PRECEDENCE = [
23071
+ "open",
23072
+ "handled",
23073
+ "dismissed",
23074
+ "resolved"
23075
+ ];
22930
23076
  function foldGroupStatus(instanceStatuses) {
22931
23077
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22932
23078
  if (statuses.size === 0) return void 0;
22933
- for (const candidate of STATUS_PRECEDENCE) {
23079
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22934
23080
  if (statuses.has(candidate)) return candidate;
22935
23081
  }
22936
23082
  return void 0;
@@ -23037,11 +23183,16 @@ function applyFindingFilters(types, opts) {
23037
23183
  }
23038
23184
  return filtered;
23039
23185
  }
23040
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
23041
- var SEVERITY_RANK = SEVERITY_ORDER;
23186
+ function rankByOrder(members2) {
23187
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23188
+ }
23189
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23190
+ function severityRank(severity) {
23191
+ return lookupOwn(SEVERITY_RANK, severity);
23192
+ }
23042
23193
  function compareFindingGroupOrder(a, b) {
23043
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
23044
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23194
+ const rankA = severityRank(a.severity) ?? -1;
23195
+ const rankB = severityRank(b.severity) ?? -1;
23045
23196
  const severityDiff = rankA - rankB;
23046
23197
  if (severityDiff !== 0) return severityDiff;
23047
23198
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
@@ -23116,6 +23267,20 @@ function computeFindingFacets(allTypes, opts) {
23116
23267
  }
23117
23268
 
23118
23269
  // ../../packages/schema/src/zod/findings-flat-build.ts
23270
+ function compareCodePoints(a, b) {
23271
+ const aIter = a[Symbol.iterator]();
23272
+ const bIter = b[Symbol.iterator]();
23273
+ for (; ; ) {
23274
+ const aNext = aIter.next();
23275
+ const bNext = bIter.next();
23276
+ if (aNext.done && bNext.done) return 0;
23277
+ if (aNext.done) return -1;
23278
+ if (bNext.done) return 1;
23279
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23280
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23281
+ if (aPoint !== bPoint) return aPoint - bPoint;
23282
+ }
23283
+ }
23119
23284
  function rowHaystack(row) {
23120
23285
  return [
23121
23286
  row.ruleId,
@@ -23140,6 +23305,8 @@ function matchesDimension(row, opts, dimension) {
23140
23305
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23141
23306
  case "statuses":
23142
23307
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23308
+ case "deliveries":
23309
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23143
23310
  case "tools":
23144
23311
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23145
23312
  // An EMPTY value is a real filter here, not an absent one. The location
@@ -23166,6 +23333,7 @@ var DIMENSIONS = [
23166
23333
  "providers",
23167
23334
  "actions",
23168
23335
  "statuses",
23336
+ "deliveries",
23169
23337
  "tools",
23170
23338
  "repo",
23171
23339
  "file",
@@ -23179,10 +23347,19 @@ function matchesInstanceFilters(row, opts, except) {
23179
23347
  return true;
23180
23348
  }
23181
23349
  function toItems(counts) {
23182
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23350
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23351
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23352
+ // NFD spelling of the same text) as equal, so a count tie between
23353
+ // them would otherwise be ordered by whichever the Map iteration
23354
+ // produced. compareCodePoints breaks that tie deterministically, which
23355
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23356
+ // which it need not: foldFacetTuples runs this same sort over grouped
23357
+ // tuples, so both paths order facets identically by construction.
23358
+ compareCodePoints(a.value, b.value)
23359
+ );
23183
23360
  }
23184
- function bump(counts, value) {
23185
- counts.set(value, (counts.get(value) ?? 0) + 1);
23361
+ function bump(counts, value, by = 1) {
23362
+ counts.set(value, (counts.get(value) ?? 0) + by);
23186
23363
  }
23187
23364
  function createInstanceFacetAccumulator(opts) {
23188
23365
  const severity = /* @__PURE__ */ new Map();
@@ -23191,6 +23368,7 @@ function createInstanceFacetAccumulator(opts) {
23191
23368
  const action = /* @__PURE__ */ new Map();
23192
23369
  const status = /* @__PURE__ */ new Map();
23193
23370
  const tool = /* @__PURE__ */ new Map();
23371
+ const deployment = /* @__PURE__ */ new Map();
23194
23372
  return {
23195
23373
  add(row) {
23196
23374
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23205,6 +23383,9 @@ function createInstanceFacetAccumulator(opts) {
23205
23383
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23206
23384
  bump(tool, row.toolName);
23207
23385
  }
23386
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23387
+ bump(deployment, row.delivery.state);
23388
+ }
23208
23389
  },
23209
23390
  facets: () => ({
23210
23391
  severity: toItems(severity),
@@ -23212,7 +23393,8 @@ function createInstanceFacetAccumulator(opts) {
23212
23393
  provider: toItems(provider),
23213
23394
  action: toItems(action),
23214
23395
  status: toItems(status),
23215
- tool: toItems(tool)
23396
+ tool: toItems(tool),
23397
+ deployment: toItems(deployment)
23216
23398
  })
23217
23399
  };
23218
23400
  }
@@ -23226,6 +23408,7 @@ function toInstanceDetail(row) {
23226
23408
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23227
23409
  eventId: row.eventId,
23228
23410
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23411
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23229
23412
  ...row.user === void 0 ? {} : { user: row.user },
23230
23413
  action: toApiAction(row.actionTaken),
23231
23414
  detectedAt: row.occurredAt,
@@ -23240,12 +23423,6 @@ function toInstanceDetail(row) {
23240
23423
  policy: { id: `category:${category}`, name: category }
23241
23424
  };
23242
23425
  }
23243
- var SEVERITY_ORDER2 = {
23244
- critical: 0,
23245
- high: 1,
23246
- medium: 2,
23247
- low: 3
23248
- };
23249
23426
  function newLocationAccumulator() {
23250
23427
  return {
23251
23428
  instanceCount: 0,
@@ -23260,7 +23437,7 @@ function newLocationAccumulator() {
23260
23437
  }
23261
23438
  function addToLocation(acc, row) {
23262
23439
  acc.instanceCount += 1;
23263
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23440
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23264
23441
  if (rank < acc.maxSeverityRank) {
23265
23442
  acc.maxSeverityRank = rank;
23266
23443
  acc.maxSeverity = row.severity;
@@ -23270,15 +23447,15 @@ function addToLocation(acc, row) {
23270
23447
  acc.ruleIds.add(row.ruleId);
23271
23448
  }
23272
23449
  function compareLocationOrder(a, b) {
23273
- const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23274
- const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23450
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23451
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23275
23452
  if (rankA !== rankB) return rankA - rankB;
23276
23453
  if (a.latestDetectedAt !== b.latestDetectedAt) {
23277
23454
  return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23278
23455
  }
23279
- if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23280
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23281
- return 0;
23456
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23457
+ if (repoDiff !== 0) return repoDiff;
23458
+ return compareCodePoints(a.file, b.file);
23282
23459
  }
23283
23460
  function encodeLocationId(repo, file2) {
23284
23461
  return `${encodePart(repo)}/${encodePart(file2)}`;
@@ -23353,6 +23530,11 @@ var Policy = external_exports.object({
23353
23530
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23354
23531
  provenance: PolicyProvenance.optional()
23355
23532
  }).meta({ id: "Policy" });
23533
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23534
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23535
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23536
+ id: "RedactFallback"
23537
+ });
23356
23538
  var PolicyBundle = external_exports.object({
23357
23539
  version: external_exports.string(),
23358
23540
  policies: external_exports.array(Policy),
@@ -23400,6 +23582,16 @@ var PolicyBundle = external_exports.object({
23400
23582
  // control plane), so no name resolution stands between the decision and the
23401
23583
  // comparison.
23402
23584
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23585
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23586
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23587
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23588
+ // a control plane can tighten a machine and never loosen one — the same
23589
+ // direction `mergeRaiseOnly` enforces for policies.
23590
+ //
23591
+ // Optional so an older backend, and an older on-disk cache, still parses;
23592
+ // absent leaves the device's own setting in force, which is the behaviour
23593
+ // that predates the field and the safe direction to default.
23594
+ redactFallback: RedactFallback.optional(),
23403
23595
  customKeywords: external_exports.array(external_exports.string()),
23404
23596
  fetchedAt: external_exports.iso.datetime()
23405
23597
  }).meta({ id: "PolicyBundle" });
@@ -23429,11 +23621,6 @@ function severityFloorPolicy(category) {
23429
23621
  const peak = CATEGORY_PEAK_SEVERITY[category];
23430
23622
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23431
23623
  }
23432
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23433
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23434
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23435
- id: "RedactFallback"
23436
- });
23437
23624
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23438
23625
  var BUILTIN_POLICY_SPECS = {
23439
23626
  monitor: {
@@ -23726,7 +23913,7 @@ var VaultConsent = external_exports.object({
23726
23913
  });
23727
23914
 
23728
23915
  // ../../packages/schema/src/zod/local.ts
23729
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23916
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23730
23917
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23731
23918
  var RunMode = external_exports.enum(["standalone", "attached"]);
23732
23919
  var ControlPlaneConnection = external_exports.object({
@@ -23746,6 +23933,15 @@ var HistorySyncConsent = external_exports.object({
23746
23933
  payloadVersion: external_exports.number().int().positive(),
23747
23934
  endpoint: external_exports.string()
23748
23935
  });
23936
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23937
+ var BodyRetention = external_exports.object({
23938
+ enabled: external_exports.boolean().default(false),
23939
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23940
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23941
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23942
+ // candidate set that is already bounded by "delivered, or never owed".
23943
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23944
+ }).meta({ id: "BodyRetention" });
23749
23945
  var WorkspaceSettings = external_exports.object({
23750
23946
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23751
23947
  runMode: RunMode.default("standalone"),
@@ -23794,7 +23990,13 @@ var WorkspaceSettings = external_exports.object({
23794
23990
  // carry prompt/reply/tool-output text in `content`; the key name predates
23795
23991
  // both widenings. Absent until granted, and a grant for a different endpoint
23796
23992
  // or an older payload no longer counts.
23797
- historySyncConsent: HistorySyncConsent.optional()
23993
+ historySyncConsent: HistorySyncConsent.optional(),
23994
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23995
+ // body never removes the row or its findings.
23996
+ bodyRetention: BodyRetention.default({
23997
+ enabled: false,
23998
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23999
+ })
23798
24000
  });
23799
24001
  function defaultWorkspaceSettings() {
23800
24002
  return WorkspaceSettings.parse({});
@@ -23889,12 +24091,15 @@ function toCaptureAttributes(event) {
23889
24091
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23890
24092
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23891
24093
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24094
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23892
24095
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23893
24096
  // has ever populated either), but every legacy metadata key still rides
23894
24097
  // the bag rather than being silently dropped — CaptureAttributes'
23895
24098
  // `.catchall(z.unknown())` carries the long tail.
23896
24099
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23897
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24100
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24101
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24102
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23898
24103
  };
23899
24104
  }
23900
24105
  function captureDefinitionVersion(finding) {
@@ -23922,13 +24127,22 @@ var ManagedSettingKey = external_exports.enum([
23922
24127
  "vaultInlineReveal",
23923
24128
  "modelJudgeConsent",
23924
24129
  "dataSharesInPlace",
23925
- "redactFallback"
24130
+ "redactFallback",
24131
+ // Pins the toggle and the day count together — see BodyRetention on why the
24132
+ // two are one unit. An administrator mandating a window wants the count
24133
+ // enforced with it, not one a user can widen while the toggle stays on.
24134
+ "bodyRetention"
23926
24135
  ]).meta({ id: "ManagedSettingKey" });
23927
24136
  function isManagedSettingKey(value) {
23928
24137
  return ManagedSettingKey.safeParse(value).success;
23929
24138
  }
23930
24139
  var ManagedSettingsValues = external_exports.object({
23931
24140
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24141
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24142
+ // plain, non-strict objects: a key under either that this build does not know
24143
+ // is stripped and nothing reports it. The unknown-value split in
24144
+ // ManagedSettings below classifies top-level names only, so it stops at
24145
+ // these boundaries.
23932
24146
  controlPlane: external_exports.object({
23933
24147
  endpoint: external_exports.string().min(1),
23934
24148
  label: external_exports.string().min(1).optional()
@@ -23939,7 +24153,8 @@ var ManagedSettingsValues = external_exports.object({
23939
24153
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23940
24154
  modelJudgeConsent: external_exports.boolean().optional(),
23941
24155
  dataSharesInPlace: external_exports.boolean().optional(),
23942
- redactFallback: RedactFallback.optional()
24156
+ redactFallback: RedactFallback.optional(),
24157
+ bodyRetention: BodyRetention.optional()
23943
24158
  }).meta({ id: "ManagedSettingsValues" });
23944
24159
  var ManagedSettings = external_exports.object({
23945
24160
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23947,7 +24162,21 @@ var ManagedSettings = external_exports.object({
23947
24162
  // decision from a bug. Absent renders as a generic "your organization".
23948
24163
  organization: external_exports.string().min(1).optional(),
23949
24164
  // What the administrator pinned.
23950
- values: ManagedSettingsValues.default({}),
24165
+ //
24166
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24167
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24168
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24169
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24170
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24171
+ // exactly the file an administrator is most likely to write while a fleet
24172
+ // is mid-upgrade.
24173
+ //
24174
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24175
+ // file, which is the outcome the lock half already rejected — an older
24176
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24177
+ // value still fails, because the nested schema is re-run over the known
24178
+ // subset and its issues are re-raised on this parse.
24179
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23951
24180
  // Which of those the user may not change. A key here with no matching value
23952
24181
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23953
24182
  // the user may still override. The two are separable on purpose.
@@ -23960,17 +24189,31 @@ var ManagedSettings = external_exports.object({
23960
24189
  // the fleets most likely to carry a version skew. A name outside the enum
23961
24190
  // is still never HONOURED: the lockable set stays explicit above.
23962
24191
  lockedFields: external_exports.array(external_exports.string()).default([])
23963
- }).transform(({ lockedFields, ...rest }) => {
24192
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
23964
24193
  const known = [];
23965
24194
  const unknown2 = [];
23966
24195
  for (const name of lockedFields) {
23967
24196
  if (isManagedSettingKey(name)) known.push(name);
23968
24197
  else unknown2.push(name);
23969
24198
  }
24199
+ const knownValues = /* @__PURE__ */ Object.create(null);
24200
+ const unknownValues = [];
24201
+ for (const [name, value] of Object.entries(values)) {
24202
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24203
+ else unknownValues.push(name);
24204
+ }
24205
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24206
+ if (!pinned.success) {
24207
+ for (const issue2 of pinned.error.issues)
24208
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24209
+ return external_exports.NEVER;
24210
+ }
23970
24211
  return {
23971
24212
  ...rest,
24213
+ values: pinned.data,
23972
24214
  lockedFields: known,
23973
- ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
24215
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24216
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
23974
24217
  };
23975
24218
  }).meta({ id: "ManagedSettings" });
23976
24219
 
@@ -24234,7 +24477,23 @@ var SaveSettingsInput = external_exports.object({
24234
24477
  modelJudgeConsent: ModelJudgeConsentChoice,
24235
24478
  historySyncConsent: HistorySyncConsentChoice,
24236
24479
  vaultConsent: external_exports.string(),
24237
- vaultInlineReveal: external_exports.string()
24480
+ vaultInlineReveal: external_exports.string(),
24481
+ // Widened to `string` like its neighbours rather than typed as
24482
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24483
+ // the call site, so the domain check receives the type it was written for.
24484
+ //
24485
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24486
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24487
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24488
+ // trade against. The real cost runs the other way and is the part worth
24489
+ // knowing: a value this schema admits and the domain enum then rejects lands
24490
+ // on the action's shared refusal, which names NO field, where a shape
24491
+ // rejection reaches `malformedInput` and names the schema key.
24492
+ redactFallback: external_exports.string(),
24493
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24494
+ // `BodyRetention`'s and the action checks it there, so there is one place
24495
+ // that decides what a legal horizon is rather than two that can drift.
24496
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24238
24497
  });
24239
24498
  var AttachInput = external_exports.object({
24240
24499
  endpoint: external_exports.string(),
@@ -24406,6 +24665,52 @@ function reviewSeverityRank(reasons) {
24406
24665
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24407
24666
  }
24408
24667
 
24668
+ // ../../packages/schema/src/zod/web-capture.ts
24669
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24670
+ var WebUsage = external_exports.object({
24671
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24672
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24673
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24674
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24675
+ });
24676
+ var WebToolCall = external_exports.object({
24677
+ toolUseId: external_exports.string().min(1),
24678
+ toolName: external_exports.string().min(1),
24679
+ target: external_exports.string().optional(),
24680
+ isError: external_exports.boolean().optional(),
24681
+ inputSize: external_exports.number().int().nonnegative().optional(),
24682
+ outputSize: external_exports.number().int().nonnegative().optional()
24683
+ });
24684
+ var WebExchange = external_exports.object({
24685
+ messageId: external_exports.string().min(1),
24686
+ startedAt: external_exports.iso.datetime(),
24687
+ model: external_exports.string().optional(),
24688
+ usage: WebUsage.optional(),
24689
+ usageSource: WebUsageSource,
24690
+ stopReason: external_exports.string().optional(),
24691
+ conversationId: external_exports.string().optional(),
24692
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24693
+ toolCalls: external_exports.array(WebToolCall).default([]),
24694
+ // Absent when the adapter recovered no text. Capped by the caller at
24695
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24696
+ // short capture is never mistaken for a short reply.
24697
+ responseText: external_exports.string().optional(),
24698
+ truncated: external_exports.boolean().default(false)
24699
+ });
24700
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24701
+ var WebCaptureStatus = external_exports.object({
24702
+ patched: external_exports.boolean(),
24703
+ live: external_exports.boolean(),
24704
+ blind: external_exports.boolean(),
24705
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24706
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24707
+ parseFailures: external_exports.number().int().nonnegative(),
24708
+ unparsedBodies: external_exports.number().int().nonnegative(),
24709
+ // The adapter-declared JSON key paths that were absent from a real payload —
24710
+ // the earliest signal that a site's contract moved.
24711
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24712
+ });
24713
+
24409
24714
  // ../../packages/persistence/src/paths.ts
24410
24715
  import {
24411
24716
  chmodSync,
@@ -24736,6 +25041,22 @@ function discardStore(file2, backup) {
24736
25041
  }
24737
25042
  }
24738
25043
 
25044
+ // ../../packages/persistence/src/internal/sql-functions.ts
25045
+ var utf8 = new TextDecoder();
25046
+ function akaLower(value) {
25047
+ if (value === null) return null;
25048
+ if (typeof value === "string") return value.toLowerCase();
25049
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25050
+ return utf8.decode(value).toLowerCase();
25051
+ }
25052
+ function registerSqlFunctions(db) {
25053
+ db.function(
25054
+ "aka_lower",
25055
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25056
+ akaLower
25057
+ );
25058
+ }
25059
+
24739
25060
  // ../../packages/persistence/src/internal/sql-text.ts
24740
25061
  function escapeLikePattern(s) {
24741
25062
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24820,6 +25141,11 @@ function schemaObjectExists(db, kind, name) {
24820
25141
  function indexExists(db, name) {
24821
25142
  return schemaObjectExists(db, "index", name);
24822
25143
  }
25144
+ function indexColumns(db, name) {
25145
+ if (!indexExists(db, name)) return [];
25146
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25147
+ return columns.map((c) => c.name).filter((c) => c !== null);
25148
+ }
24823
25149
  function columnNames(db, table2, opts) {
24824
25150
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24825
25151
  const columns = db.prepare(`PRAGMA ${pragma}(${table2})`).all();
@@ -24881,178 +25207,820 @@ function mapRowsTolerant(rows, map2) {
24881
25207
  return out;
24882
25208
  }
24883
25209
 
24884
- // ../../packages/persistence/src/migrations.ts
24885
- function describeObject(object2) {
24886
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24887
- }
24888
- function splitStatements(sql) {
24889
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24890
- }
24891
- function createdIndexName(statement) {
24892
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24893
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25210
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25211
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25212
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25213
+
25214
+ // ../../packages/persistence/src/sync-failure.ts
25215
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25216
+ function syncFailureRejectCondition(column = "sync_failure") {
25217
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25218
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24894
25219
  }
24895
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24896
- function applyMigrations(db, file2) {
24897
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24898
- db.exec(
24899
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24900
- );
24901
- const applied = new Set(
24902
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24903
- );
24904
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24905
- const record2 = db.prepare(
24906
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24907
- );
24908
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24909
- if (applied.has(migration.tag)) continue;
24910
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24911
- const evidence = evidenceObjects(migration.sql);
24912
- const present = evidence.filter((o) => evidenceExists(db, o));
24913
- if (present.length > 0 && present.length < evidence.length) {
24914
- const missing = evidence.filter((o) => !present.includes(o));
24915
- const message = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
24916
- akaWarn(message);
24917
- throw new Error(`[aka] ${message}`);
24918
- }
24919
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24920
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24921
- const statements = splitStatements(migration.sql);
24922
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24923
- try {
24924
- withTransaction(
24925
- db,
24926
- () => {
24927
- for (const statement of statements) {
24928
- const indexName = createdIndexName(statement);
24929
- if (indexName === void 0) {
24930
- if (alreadyApplied) continue;
24931
- } else if (indexExists(db, indexName)) {
24932
- continue;
24933
- }
24934
- db.exec(statement);
24935
- }
24936
- if (wantsFkOff && !alreadyApplied) {
24937
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24938
- if (violations.length > 0) {
24939
- throw new Error(
24940
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24941
- );
24942
- }
24943
- }
24944
- record2.run(migration.tag, Date.now());
24945
- },
24946
- "IMMEDIATE"
24947
- );
24948
- } finally {
24949
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24950
- }
25220
+
25221
+ // ../../packages/persistence/src/repositories/history-sync.ts
25222
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25223
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25224
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25225
+ var COUNTED_EVENT_TYPES = [
25226
+ ...STRUCTURAL_EVENT_TYPES,
25227
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25228
+ ];
25229
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25230
+ var PARTITION_BUCKETS = `
25231
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25232
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25233
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25234
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25235
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25236
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25237
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25238
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25239
+ -- added later lands in no bucket and fails the sum assertion, instead
25240
+ -- of silently joining this one.
25241
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25242
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25243
+ THEN 1 ELSE 0 END) AS failed,
25244
+ COUNT(*) AS total`;
25245
+ var COUNTED_SCOPE = `
25246
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25247
+ AND (
25248
+ event_type IN (${TYPE_LIST})
25249
+ OR synced_at IS NOT NULL
25250
+ OR outbox_owed = 1
25251
+ )`;
25252
+ var SKIPPED = -1;
25253
+ var ROW_COLUMNS = `id,
25254
+ parent_id AS parentId,
25255
+ root_session_id AS rootSessionId,
25256
+ event_type AS eventType,
25257
+ host_id AS hostId,
25258
+ harness_id AS harnessId,
25259
+ source_project_id AS sourceProjectId,
25260
+ started_at AS startedAt,
25261
+ ended_at AS endedAt,
25262
+ severity,
25263
+ priority,
25264
+ content,
25265
+ content_hash AS contentHash,
25266
+ attributes`;
25267
+ var SqliteHistorySyncRepository = class {
25268
+ constructor(db) {
25269
+ this.db = db;
25270
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25271
+ this.sessionsStmt = db.prepare(
25272
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25273
+ FROM audit_events
25274
+ WHERE synced_at IS NULL
25275
+ AND event_type IN (${TYPE_LIST})
25276
+ AND started_at < :before
25277
+ GROUP BY sessionId
25278
+ ORDER BY earliest
25279
+ LIMIT :limit`
25280
+ );
25281
+ this.rowsStmt = db.prepare(
25282
+ `SELECT ${ROW_COLUMNS}
25283
+ FROM audit_events
25284
+ WHERE synced_at IS NULL
25285
+ AND event_type IN (${TYPE_LIST})
25286
+ AND started_at < :before
25287
+ AND COALESCE(root_session_id, id) = :sessionId
25288
+ ORDER BY (event_type = 'session') DESC, started_at
25289
+ LIMIT :limit`
25290
+ );
25291
+ this.captureRowsStmt = db.prepare(
25292
+ `SELECT ${ROW_COLUMNS}
25293
+ FROM audit_events
25294
+ WHERE synced_at IS NULL
25295
+ AND sync_claimed_at IS NULL
25296
+ AND outbox_owed = 1
25297
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25298
+ AND started_at < :before
25299
+ ORDER BY started_at
25300
+ LIMIT :limit`
25301
+ );
25302
+ this.markOwedStmt = db.prepare(
25303
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25304
+ );
25305
+ this.markCaptureBacklogOwedStmt = db.prepare(
25306
+ `UPDATE audit_events SET outbox_owed = 1
25307
+ WHERE synced_at IS NULL
25308
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25309
+ AND started_at < :before`
25310
+ );
25311
+ this.stampStmt = db.prepare(
25312
+ `UPDATE audit_events
25313
+ SET synced_at = :at,
25314
+ sync_claimed_at = NULL,
25315
+ sync_failed_at = :failedAt,
25316
+ sync_failure = :failure
25317
+ WHERE id = :id`
25318
+ );
25319
+ this.claimRowStmt = db.prepare(
25320
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25321
+ );
25322
+ this.releaseRowStmt = db.prepare(
25323
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25324
+ );
25325
+ this.releaseStaleClaimsStmt = db.prepare(
25326
+ `UPDATE audit_events SET sync_claimed_at = NULL
25327
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25328
+ );
25329
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25330
+ FROM audit_events${COUNTED_SCOPE}`);
25331
+ this.partitionByKindStmt = db.prepare(
25332
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25333
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25334
+ GROUP BY event_type`
25335
+ );
25336
+ this.countsStmt = db.prepare(
25337
+ `SELECT
25338
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25339
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25340
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25341
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25342
+ THEN 1 ELSE 0 END) AS skipped,
25343
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25344
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25345
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25346
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25347
+ FROM audit_events
25348
+ WHERE event_type IN (${TYPE_LIST})`
25349
+ );
25350
+ this.captureSkipCountStmt = db.prepare(
25351
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25352
+ // way the structural totals are. The split exists because a refusal is
25353
+ // terminal only against the deployment that gave it, and the structural
25354
+ // re-arm frees it on a change of deployment. The capture lane has no such
25355
+ // escape: re-arming a capture would offer one deployment's undelivered
25356
+ // prompts, with their text, to a deployment that never saw them, which is
25357
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25358
+ // reasons mean the same thing — this row will not be sent — and splitting
25359
+ // them would put refused captures in a bucket nothing reads and nothing
25360
+ // frees.
25361
+ `SELECT COUNT(*) AS skipped
25362
+ FROM audit_events
25363
+ WHERE synced_at = ${String(SKIPPED)}
25364
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25365
+ );
25366
+ this.fingerprintStmt = db.prepare(
25367
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25368
+ FROM history_sync WHERE id = 1`
25369
+ );
25370
+ this.setFingerprintStmt = db.prepare(
25371
+ `UPDATE history_sync
25372
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25373
+ WHERE id = 1`
25374
+ );
25375
+ this.disownCapturesStmt = db.prepare(
25376
+ `UPDATE audit_events SET outbox_owed = NULL
25377
+ WHERE outbox_owed IS NOT NULL
25378
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25379
+ AND started_at < :attachedAt`
25380
+ );
25381
+ this.rearmStmt = db.prepare(
25382
+ `UPDATE audit_events
25383
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25384
+ WHERE (synced_at > 0
25385
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25386
+ AND event_type IN (${TYPE_LIST})`
25387
+ );
25388
+ this.claimStmt = db.prepare(
25389
+ `UPDATE history_sync
25390
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25391
+ WHERE id = 1
25392
+ AND (owner_pid IS NULL
25393
+ OR heartbeat_at IS NULL
25394
+ OR heartbeat_at < :staleBefore
25395
+ OR heartbeat_at > :now)`
25396
+ );
25397
+ this.heartbeatStmt = db.prepare(
25398
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25399
+ );
25400
+ this.releaseStmt = db.prepare(
25401
+ `UPDATE history_sync
25402
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25403
+ WHERE id = 1 AND owner_pid = :pid`
25404
+ );
25405
+ this.closeWindowStmt = db.prepare(
25406
+ `UPDATE audit_events
25407
+ SET synced_at = ${String(SKIPPED)},
25408
+ sync_failed_at = :at,
25409
+ sync_failure = 'detached_undelivered'
25410
+ WHERE synced_at IS NULL
25411
+ AND event_type IN (${TYPE_LIST})
25412
+ AND started_at >= :attachedAt`
25413
+ );
25414
+ this.releaseBoundaryStmt = db.prepare(
25415
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25416
+ );
25417
+ this.freezeBoundaryStmt = db.prepare(
25418
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25419
+ );
25420
+ this.leaseStmt = db.prepare(
25421
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25422
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25423
+ FROM history_sync WHERE id = 1`
25424
+ );
25425
+ this.inspectionsStmt = db.prepare(
25426
+ `SELECT d.rule_id AS ruleId,
25427
+ d.name AS ruleName,
25428
+ d.version AS ruleVersion,
25429
+ d.category AS category,
25430
+ d.severity AS severity,
25431
+ f.span_start AS spanStart,
25432
+ f.span_end AS spanEnd,
25433
+ f.masked_match AS maskedMatch,
25434
+ f.action_taken AS actionTaken,
25435
+ f.confidence AS confidence
25436
+ FROM inspection_findings f
25437
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25438
+ WHERE f.audit_event_id = :auditEventId
25439
+ ORDER BY f.span_start, f.id`
25440
+ );
24951
25441
  }
24952
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24953
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25442
+ db;
25443
+ ensureRowStmt;
25444
+ sessionsStmt;
25445
+ rowsStmt;
25446
+ stampStmt;
25447
+ countsStmt;
25448
+ fingerprintStmt;
25449
+ setFingerprintStmt;
25450
+ rearmStmt;
25451
+ claimStmt;
25452
+ heartbeatStmt;
25453
+ releaseStmt;
25454
+ leaseStmt;
25455
+ inspectionsStmt;
25456
+ closeWindowStmt;
25457
+ releaseBoundaryStmt;
25458
+ freezeBoundaryStmt;
25459
+ captureRowsStmt;
25460
+ markOwedStmt;
25461
+ markCaptureBacklogOwedStmt;
25462
+ captureSkipCountStmt;
25463
+ disownCapturesStmt;
25464
+ partitionStmt;
25465
+ partitionByKindStmt;
25466
+ claimRowStmt;
25467
+ releaseRowStmt;
25468
+ releaseStaleClaimsStmt;
25469
+ /**
25470
+ * The masked detections recorded against one tool call.
25471
+ *
25472
+ * These travel with the event because a tool call's target is not
25473
+ * re-inspectable from the event alone — unlike a capture, where the text
25474
+ * itself is re-scannable. What crosses is the masked match and the rule that
25475
+ * produced it, never the value.
25476
+ */
25477
+ inspectionsFor(auditEventId) {
25478
+ return allRows(this.inspectionsStmt, { auditEventId });
24954
25479
  }
24955
- ensureSyncedAtColumn(db, "audit_events");
24956
- ensureScanLedgerTable(db);
24957
- ensureHistorySyncTable(db);
24958
- ensureBlockedDetectionsTable(db);
24959
- ensureRuleProbeCacheTable(db);
24960
- ensureWriteGateTrigger(db);
24961
- ensureTokenUsageColumns(db);
24962
- reconcileSourceProjectIds(db);
24963
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24964
- const drained = runLegacyHistoryBackfill(db);
24965
- if (drained) applyLegacyDropMigration(db, file2);
25480
+ /**
25481
+ * Sessions with structural rows still to send, oldest first.
25482
+ *
25483
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25484
+ * read. Anything recorded after the machine attached is the live forward
25485
+ * path's to deliver; this drain exists for what was recorded before it, and a
25486
+ * row both paths send is at best a duplicate request and at worst — for a
25487
+ * session root — an overwrite of the inventory ids the live path resolved.
25488
+ */
25489
+ pendingSessions(limit, before) {
25490
+ return allRows(this.sessionsStmt, { limit, before }).map(
25491
+ (r) => r.sessionId
25492
+ );
24966
25493
  }
24967
- }
24968
- function readLegacyTables(db) {
24969
- let holdsRows = false;
24970
- const marks = [];
24971
- for (const table2 of ["events", "findings"]) {
24972
- try {
24973
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table2}`).get();
24974
- if (row === void 0) {
24975
- holdsRows = true;
24976
- marks.push(`${table2}:unreadable`);
24977
- continue;
24978
- }
24979
- if (row.n > 0) holdsRows = true;
24980
- marks.push(`${table2}:${String(row.n)}:${String(row.hi)}`);
24981
- } catch {
24982
- holdsRows = true;
24983
- marks.push(`${table2}:unreadable`);
24984
- }
25494
+ /** One session's undelivered structural rows within the backlog, root first. */
25495
+ pendingRows(sessionId, limit, before) {
25496
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24985
25497
  }
24986
- return { holdsRows, mark: marks.join("|") };
24987
- }
24988
- function applyLegacyDropMigration(db, file2) {
24989
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24990
- if (!migration) return;
24991
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24992
- if (file2 !== void 0 && before?.holdsRows === true) {
24993
- try {
24994
- backupBeforeLegacyDrop(db, file2);
24995
- } catch (error61) {
24996
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24997
- return;
24998
- }
25498
+ /**
25499
+ * Captures this machine still owes the deployment, oldest first.
25500
+ *
25501
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25502
+ * by a time window — see captureRowsStmt for why a window could not express
25503
+ * this. `before` is the grace window that leaves a just-recorded capture to
25504
+ * the live path.
25505
+ */
25506
+ pendingCaptureRows(limit, before) {
25507
+ return allRows(this.captureRowsStmt, { limit, before });
24999
25508
  }
25000
- try {
25509
+ /**
25510
+ * Record that a capture is OWED to the deployment.
25511
+ *
25512
+ * Written by the attached forward path when a live send did not confirm
25513
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25514
+ * a fact rather than an inference: the machine was attached, the send did not
25515
+ * land, so the row is owed — which no time window can state, because the same
25516
+ * window that holds the rows a past attachment left owed also holds every
25517
+ * capture recorded while the machine was DETACHED, and those were never
25518
+ * offered to anyone.
25519
+ *
25520
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25521
+ * out of the drain's read.
25522
+ */
25523
+ markCaptureOwed(id) {
25524
+ this.markOwedStmt.run({ id });
25525
+ }
25526
+ /**
25527
+ * Mark every capture already on disk as owed, as of `before`.
25528
+ *
25529
+ * The consent-time backfill, called once from `aka attach` when a human
25530
+ * grants existing-history consent — never from an ongoing drain pass, and
25531
+ * never inferred from a boundary that could later move. `before` is the
25532
+ * caller's own "now" at the moment consent was granted, so what this marks
25533
+ * is exactly the backlog the consent prompt already counted, not whatever a
25534
+ * later re-attach or key rotation might widen it to.
25535
+ *
25536
+ * Returns how many rows matched, for the caller to log or test against. Not a
25537
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25538
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25539
+ */
25540
+ markCaptureBacklogOwed(before) {
25541
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25542
+ }
25543
+ /**
25544
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25545
+ *
25546
+ * CLEARS any failure reason in the same statement. A row that failed against
25547
+ * one deployment and then landed is delivered, and leaving the reason behind
25548
+ * would leave the store holding two contradictory answers about one row —
25549
+ * with the surface free to render either.
25550
+ */
25551
+ markSynced(ids, atMs) {
25552
+ this.stampAll(ids, atMs, null);
25553
+ }
25554
+ /**
25555
+ * Record that THIS MACHINE cannot express the row on the wire.
25556
+ *
25557
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25558
+ * payload, or a body the client itself refused to send. It fails identically
25559
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25560
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25561
+ * is retried; marking those would turn one outage into permanent data loss.
25562
+ */
25563
+ markSkipped(ids, atMs) {
25564
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25565
+ }
25566
+ /**
25567
+ * Record that THIS DEPLOYMENT refused the row.
25568
+ *
25569
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25570
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25571
+ * row is outstanding rather than why. What separates them is the reason, and
25572
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25573
+ * on one body, so it is terminal only for as long as this machine points at
25574
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25575
+ *
25576
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25577
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25578
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25579
+ */
25580
+ markRefused(ids, atMs) {
25581
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25582
+ }
25583
+ eachInTransaction(ids, run) {
25584
+ if (ids.length === 0) return;
25001
25585
  withTransaction(
25002
- db,
25586
+ this.db,
25003
25587
  () => {
25004
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25005
- if (alreadyDropped) return;
25006
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25007
- akaWarn(
25008
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25009
- );
25010
- return;
25011
- }
25012
- for (const statement of splitStatements(migration.sql)) {
25013
- db.exec(statement);
25014
- }
25015
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25016
- migration.tag,
25017
- Date.now()
25018
- );
25588
+ for (const id of ids) run(id);
25019
25589
  },
25020
25590
  "IMMEDIATE"
25021
25591
  );
25022
- } catch (error61) {
25023
- akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
25024
25592
  }
25025
- }
25026
- function backupBeforeLegacyDrop(db, file2) {
25027
- reapStalePartials(file2);
25028
- const backup = backupPath(file2, "pre-drop");
25029
- snapshotStore(db, backup);
25030
- return backup;
25031
- }
25032
- var TOKEN_USAGE_COLUMNS = [
25033
- {
25034
- name: "input_tokens",
25035
- ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
25036
- },
25037
- {
25038
- name: "output_tokens",
25039
- ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
25040
- },
25041
- {
25042
- name: "cache_creation_input_tokens",
25043
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
25044
- },
25045
- {
25046
- name: "cache_read_input_tokens",
25047
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
25048
- },
25049
- {
25050
- name: "model",
25051
- ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25052
- },
25053
- {
25054
- name: "provider",
25055
- ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
25593
+ stampAll(ids, value, failure, failedAtMs) {
25594
+ if (ids.length === 0) return;
25595
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25596
+ withTransaction(
25597
+ this.db,
25598
+ () => {
25599
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25600
+ },
25601
+ "IMMEDIATE"
25602
+ );
25603
+ }
25604
+ /**
25605
+ * Claim rows as in-flight.
25606
+ *
25607
+ * Advisory in exactly the sense the lease is: it records that a send is in
25608
+ * progress so a surface can say so, and a lost claim costs a row showing as
25609
+ * queued while it is actually being sent. It is not exclusion — the far side
25610
+ * settles a duplicate on the row id.
25611
+ */
25612
+ claimRows(ids, atMs) {
25613
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25614
+ }
25615
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25616
+ releaseRows(ids) {
25617
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25618
+ }
25619
+ /**
25620
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25621
+ *
25622
+ * A process killed between claiming and settling leaves rows claimed with
25623
+ * nothing left to settle them. Without this they read as "sending" for ever.
25624
+ */
25625
+ releaseStaleClaims(staleBefore) {
25626
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25627
+ }
25628
+ /**
25629
+ * Every tracked row in exactly one delivery state.
25630
+ *
25631
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25632
+ * pick up now", which is a different question from "what state is this row
25633
+ * in" — and a machine that has never attached has no boundary to pass, so
25634
+ * requiring one would force a caller to invent one and report the whole store
25635
+ * as queued.
25636
+ */
25637
+ /**
25638
+ * The same partition, one row per kind that a lane carries.
25639
+ *
25640
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25641
+ * scope decides which rows exist at all, so a kind that has never been
25642
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25643
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25644
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25645
+ * different things.
25646
+ */
25647
+ partitionByKind() {
25648
+ return allRows(
25649
+ this.partitionByKindStmt,
25650
+ {}
25651
+ ).map((row) => ({
25652
+ kind: row.kind,
25653
+ queued: row.queued ?? 0,
25654
+ inProgress: row.inProgress ?? 0,
25655
+ synced: row.synced ?? 0,
25656
+ failed: row.failed ?? 0,
25657
+ refused: row.refused ?? 0,
25658
+ detached: row.detached ?? 0,
25659
+ total: row.total ?? 0
25660
+ }));
25661
+ }
25662
+ partition() {
25663
+ const row = getRow(this.partitionStmt, {});
25664
+ return {
25665
+ queued: row?.queued ?? 0,
25666
+ inProgress: row?.inProgress ?? 0,
25667
+ synced: row?.synced ?? 0,
25668
+ failed: row?.failed ?? 0,
25669
+ refused: row?.refused ?? 0,
25670
+ detached: row?.detached ?? 0,
25671
+ total: row?.total ?? 0
25672
+ };
25673
+ }
25674
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25675
+ counts(before) {
25676
+ const row = getRow(this.countsStmt, { before });
25677
+ const captures = getRow(this.captureSkipCountStmt);
25678
+ return {
25679
+ pending: row?.pending ?? 0,
25680
+ sent: row?.sent ?? 0,
25681
+ skipped: row?.skipped ?? 0,
25682
+ refused: row?.refused ?? 0,
25683
+ detached: row?.detached ?? 0,
25684
+ capturesSkipped: captures?.skipped ?? 0
25685
+ };
25686
+ }
25687
+ /**
25688
+ * The deployment the current stamps were made against, and where its backlog
25689
+ * ends.
25690
+ *
25691
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25692
+ * machine that has never drained is — and every writer below seeds the row
25693
+ * before it needs one, so nothing depends on this creating it. Keeping the
25694
+ * write off the gate path matters because the gate runs on every pass while a
25695
+ * write has to take the database's write lock.
25696
+ */
25697
+ deployment() {
25698
+ const row = getRow(
25699
+ this.fingerprintStmt
25700
+ );
25701
+ return {
25702
+ fingerprint: row?.fingerprint ?? void 0,
25703
+ backlogBefore: row?.backlogBefore ?? void 0
25704
+ };
25705
+ }
25706
+ /**
25707
+ * Point the ledger at a different deployment, discarding what it recorded
25708
+ * about the previous one.
25709
+ *
25710
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25711
+ * machine has just left are undelivered as far as the new one is concerned.
25712
+ * All four in one transaction, so a crash between them cannot leave stamps
25713
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25714
+ * a disown with no re-mark to follow it.
25715
+ *
25716
+ * The boundary is written HERE and only here, which is what freezes it: a
25717
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25718
+ * unchanged, so this never runs and the backlog does not widen back over rows
25719
+ * the live path has since delivered.
25720
+ *
25721
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25722
+ * granted existing-history consent for the deployment this call is arming —
25723
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25724
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25725
+ * apart. Passed only when that grant is valid, since this method has no way
25726
+ * to check consent itself and must not mark a row owed for a machine that
25727
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25728
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25729
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25730
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25731
+ * on the cleared side of that bound — and the re-mark in the same
25732
+ * transaction is what puts those rows back. A crash between the two cannot
25733
+ * strand the ledger disowned with nothing re-marked — the transaction either
25734
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25735
+ * committed re-enters this method on the very next pass. Omit it (the
25736
+ * structural-only tests do) to exercise the disown in isolation.
25737
+ *
25738
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25739
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25740
+ * live path can mark a capture owed from the moment `aka attach` writes the
25741
+ * descriptor, before the drain's first pass ever reaches this method, and
25742
+ * such a row sits at or after the bound rather than below it. What keeps the
25743
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25744
+ * bound — disown runs first, re-mark second, both inside the one
25745
+ * transaction above.
25746
+ */
25747
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25748
+ this.ensureRowStmt.run();
25749
+ withTransaction(
25750
+ this.db,
25751
+ () => {
25752
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25753
+ this.rearmStmt.run();
25754
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25755
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25756
+ }
25757
+ if (backfillCapturesBefore !== void 0) {
25758
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25759
+ }
25760
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25761
+ },
25762
+ "IMMEDIATE"
25763
+ );
25764
+ }
25765
+ /**
25766
+ * End the attached period: hand its rows to the live path, and release the
25767
+ * boundary so the next attachment can freeze a new one.
25768
+ *
25769
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25770
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25771
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25772
+ * during the detached period, because the machine is not attached. Rows
25773
+ * recorded in that window sit after the boundary and before the re-attach, so
25774
+ * neither path takes them, and the pending count reports none outstanding.
25775
+ *
25776
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25777
+ * closing attachment's to deliver and are no longer outstanding — that is what
25778
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25779
+ * distinction is not academic: this used to write a delivery TIME, which every
25780
+ * read treats as delivery, so one detach turned a window of undelivered rows
25781
+ * into a window of delivered ones and no surface could tell. It writes the
25782
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25783
+ * "received" stop being the same fact.
25784
+ *
25785
+ * A change of deployment still frees them (see the re-arm), because the next
25786
+ * deployment has seen none of this machine's history — so the rows reach it
25787
+ * exactly as they did when this wrote a delivery time.
25788
+ *
25789
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25790
+ * window unstamped — that half-state would re-send the whole attached period
25791
+ * on the next attach, which is the failure the boundary exists to prevent.
25792
+ */
25793
+ closeAttachedWindow(attachedAtMs, atMs) {
25794
+ this.ensureRowStmt.run();
25795
+ withTransaction(
25796
+ this.db,
25797
+ () => {
25798
+ const row = getRow(this.fingerprintStmt);
25799
+ const from = row?.backlogBefore ?? attachedAtMs;
25800
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25801
+ this.releaseBoundaryStmt.run();
25802
+ },
25803
+ "IMMEDIATE"
25804
+ );
25805
+ }
25806
+ /**
25807
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25808
+ *
25809
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25810
+ * different deployment and therefore discards what was delivered to the old
25811
+ * one: here the recipient is the same, so everything already sent to it stays
25812
+ * sent.
25813
+ */
25814
+ freezeBoundary(backlogBefore) {
25815
+ this.ensureRowStmt.run();
25816
+ this.freezeBoundaryStmt.run({ backlogBefore });
25817
+ }
25818
+ /** Take the claim, or report that someone live already holds it. */
25819
+ claim(pid, host, nowMs, staleAfterMs) {
25820
+ this.ensureRowStmt.run();
25821
+ let taken = false;
25822
+ withTransaction(
25823
+ this.db,
25824
+ () => {
25825
+ const result = this.claimStmt.run({
25826
+ pid,
25827
+ host,
25828
+ now: nowMs,
25829
+ staleBefore: nowMs - staleAfterMs
25830
+ });
25831
+ taken = result.changes === 1;
25832
+ },
25833
+ "IMMEDIATE"
25834
+ );
25835
+ return taken;
25836
+ }
25837
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25838
+ heartbeat(pid, nowMs) {
25839
+ this.heartbeatStmt.run({ now: nowMs, pid });
25840
+ }
25841
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25842
+ release(pid) {
25843
+ this.releaseStmt.run({ pid });
25844
+ }
25845
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25846
+ lease() {
25847
+ return getRow(this.leaseStmt);
25848
+ }
25849
+ };
25850
+
25851
+ // ../../packages/persistence/src/migrations.ts
25852
+ function describeObject(object2) {
25853
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25854
+ }
25855
+ function splitStatements(sql) {
25856
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25857
+ }
25858
+ function createdIndexName(statement) {
25859
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25860
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25861
+ }
25862
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25863
+ function applyMigrations(db, file2, options = {}) {
25864
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25865
+ db.exec(
25866
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25867
+ );
25868
+ const applied = new Set(
25869
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25870
+ );
25871
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25872
+ const record2 = db.prepare(
25873
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25874
+ );
25875
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25876
+ if (applied.has(migration.tag)) continue;
25877
+ if (options.skipTags?.has(migration.tag) === true) continue;
25878
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25879
+ const evidence = evidenceObjects(migration.sql);
25880
+ const present = evidence.filter((o) => evidenceExists(db, o));
25881
+ if (present.length > 0 && present.length < evidence.length) {
25882
+ const missing = evidence.filter((o) => !present.includes(o));
25883
+ const message = `sqlite migration ${migration.tag} has no ledger row, but the store already has ${present.map(describeObject).join(", ")} while missing ${missing.map(describeObject).join(", ")} \u2014 the schema diverged from the migration history; refusing to replay or skip.`;
25884
+ akaWarn(message);
25885
+ throw new Error(`[aka] ${message}`);
25886
+ }
25887
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25888
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25889
+ const statements = splitStatements(migration.sql);
25890
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25891
+ try {
25892
+ withTransaction(
25893
+ db,
25894
+ () => {
25895
+ for (const statement of statements) {
25896
+ const indexName = createdIndexName(statement);
25897
+ if (indexName === void 0) {
25898
+ if (alreadyApplied) continue;
25899
+ } else if (indexExists(db, indexName)) {
25900
+ continue;
25901
+ }
25902
+ db.exec(statement);
25903
+ }
25904
+ if (wantsFkOff && !alreadyApplied) {
25905
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25906
+ if (violations.length > 0) {
25907
+ throw new Error(
25908
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25909
+ );
25910
+ }
25911
+ }
25912
+ record2.run(migration.tag, Date.now());
25913
+ },
25914
+ "IMMEDIATE"
25915
+ );
25916
+ } finally {
25917
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25918
+ }
25919
+ }
25920
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25921
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25922
+ }
25923
+ ensureSyncedAtColumn(db, "audit_events");
25924
+ ensureScanLedgerTable(db);
25925
+ ensureHistorySyncTable(db);
25926
+ ensureBlockedDetectionsTable(db);
25927
+ ensureRuleProbeCacheTable(db);
25928
+ ensureWriteGateTrigger(db);
25929
+ ensureTokenUsageColumns(db);
25930
+ reconcileSourceProjectIds(db);
25931
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25932
+ const drained = runLegacyHistoryBackfill(db);
25933
+ if (drained) applyLegacyDropMigration(db, file2);
25934
+ }
25935
+ }
25936
+ function readLegacyTables(db) {
25937
+ let holdsRows = false;
25938
+ const marks = [];
25939
+ for (const table2 of ["events", "findings"]) {
25940
+ try {
25941
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table2}`).get();
25942
+ if (row === void 0) {
25943
+ holdsRows = true;
25944
+ marks.push(`${table2}:unreadable`);
25945
+ continue;
25946
+ }
25947
+ if (row.n > 0) holdsRows = true;
25948
+ marks.push(`${table2}:${String(row.n)}:${String(row.hi)}`);
25949
+ } catch {
25950
+ holdsRows = true;
25951
+ marks.push(`${table2}:unreadable`);
25952
+ }
25953
+ }
25954
+ return { holdsRows, mark: marks.join("|") };
25955
+ }
25956
+ function applyLegacyDropMigration(db, file2) {
25957
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25958
+ if (!migration) return;
25959
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25960
+ if (file2 !== void 0 && before?.holdsRows === true) {
25961
+ try {
25962
+ backupBeforeLegacyDrop(db, file2);
25963
+ } catch (error61) {
25964
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25965
+ return;
25966
+ }
25967
+ }
25968
+ try {
25969
+ withTransaction(
25970
+ db,
25971
+ () => {
25972
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25973
+ if (alreadyDropped) return;
25974
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25975
+ akaWarn(
25976
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25977
+ );
25978
+ return;
25979
+ }
25980
+ for (const statement of splitStatements(migration.sql)) {
25981
+ db.exec(statement);
25982
+ }
25983
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25984
+ migration.tag,
25985
+ Date.now()
25986
+ );
25987
+ },
25988
+ "IMMEDIATE"
25989
+ );
25990
+ } catch (error61) {
25991
+ akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
25992
+ }
25993
+ }
25994
+ function backupBeforeLegacyDrop(db, file2) {
25995
+ reapStalePartials(file2);
25996
+ const backup = backupPath(file2, "pre-drop");
25997
+ snapshotStore(db, backup);
25998
+ return backup;
25999
+ }
26000
+ var TOKEN_USAGE_COLUMNS = [
26001
+ {
26002
+ name: "input_tokens",
26003
+ ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
26004
+ },
26005
+ {
26006
+ name: "output_tokens",
26007
+ ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
26008
+ },
26009
+ {
26010
+ name: "cache_creation_input_tokens",
26011
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
26012
+ },
26013
+ {
26014
+ name: "cache_read_input_tokens",
26015
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
26016
+ },
26017
+ {
26018
+ name: "model",
26019
+ ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
26020
+ },
26021
+ {
26022
+ name: "provider",
26023
+ ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
25056
26024
  }
25057
26025
  ];
25058
26026
  function ensureTokenUsageColumns(db) {
@@ -25313,10 +26281,62 @@ function ensureSyncedAtColumn(db, table2) {
25313
26281
  if (!columns.includes("outbox_owed")) {
25314
26282
  db.exec(`ALTER TABLE ${table2} ADD COLUMN outbox_owed integer`);
25315
26283
  }
26284
+ if (!columns.includes("sync_failed_at")) {
26285
+ db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failed_at integer`);
26286
+ }
26287
+ if (!columns.includes("sync_failure")) {
26288
+ withTransaction(
26289
+ db,
26290
+ () => {
26291
+ db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failure text`);
26292
+ db.exec(
26293
+ `UPDATE ${table2} SET synced_at = NULL
26294
+ WHERE synced_at = -1
26295
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26296
+ );
26297
+ },
26298
+ "IMMEDIATE"
26299
+ );
26300
+ }
25316
26301
  db.exec(
25317
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25318
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26302
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26303
+ BEFORE UPDATE OF sync_failure ON ${table2}
26304
+ WHEN ${syncFailureRejectCondition()}
26305
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25319
26306
  );
26307
+ const syncIndexColumns = [
26308
+ "event_type",
26309
+ "synced_at",
26310
+ "sync_claimed_at",
26311
+ "started_at",
26312
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26313
+ // has to be in the index for the read to stay covered — but putting it
26314
+ // ahead of `started_at` would reorder the prefix the structural drain's
26315
+ // reads match on.
26316
+ "sync_failure"
26317
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26318
+ //
26319
+ // The delivery-state read tests it — a capture's state depends on whether a
26320
+ // live forward marked it owed — so carrying it here makes that read covering
26321
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26322
+ // But a sixth column changes what the planner charges for this index, and
26323
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26324
+ // then stops choosing the per-session index for the token rollup and walks
26325
+ // every `llm_call` in the store through the event-type index instead. That
26326
+ // read grows with the store; this one does not.
26327
+ //
26328
+ // 40 ms on the largest store measured, once per render, is a cost worth
26329
+ // paying to leave every other read's plan where it was.
26330
+ ];
26331
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26332
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26333
+ if (!syncIndexMatches) {
26334
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26335
+ db.exec(
26336
+ `CREATE INDEX idx_audit_events_sync
26337
+ ON audit_events (${syncIndexColumns.join(", ")})`
26338
+ );
26339
+ }
25320
26340
  db.exec(
25321
26341
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25322
26342
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25538,7 +26558,11 @@ function buildAuditEvent(row) {
25538
26558
  link: linkParsed?.success ? linkParsed.data : null,
25539
26559
  targetId: row.target_id,
25540
26560
  internal: intToBool(row.internal),
25541
- flagged: intToBool(row.flagged)
26561
+ flagged: intToBool(row.flagged),
26562
+ // Only meaningful when the title came out empty — a row whose body was
26563
+ // expired but whose title fell back to `tool_name` still has something to
26564
+ // render, and flagging it would make the view apologise for nothing.
26565
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25542
26566
  };
25543
26567
  }
25544
26568
  var TIMELINE_COLUMNS = `
@@ -25546,6 +26570,7 @@ var TIMELINE_COLUMNS = `
25546
26570
  event_type,
25547
26571
  started_at,
25548
26572
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26573
+ content_expired_at,
25549
26574
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25550
26575
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25551
26576
  json_extract(attributes, '$.severity') AS severity,
@@ -26211,6 +27236,88 @@ var SqliteAuditEventsRepository = class {
26211
27236
  }
26212
27237
  };
26213
27238
 
27239
+ // ../../packages/persistence/src/repositories/body-retention.ts
27240
+ var DEFAULT_BATCH_SIZE = 500;
27241
+ var DEFAULT_MAX_ROWS = 5e4;
27242
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27243
+ var SqliteBodyRetentionRepository = class {
27244
+ constructor(db) {
27245
+ this.db = db;
27246
+ const select = (laneClause) => `
27247
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27248
+ FROM audit_events
27249
+ WHERE content IS NOT NULL
27250
+ AND started_at < :cutoff
27251
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27252
+ ${laneClause}
27253
+ ORDER BY started_at
27254
+ LIMIT :limit`;
27255
+ this.candidatesStmt = this.db.prepare(select(""));
27256
+ this.candidatesSyncSafeStmt = this.db.prepare(
27257
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27258
+ );
27259
+ this.heldBySyncStmt = this.db.prepare(`
27260
+ SELECT COUNT(*) AS n
27261
+ FROM audit_events
27262
+ WHERE content IS NOT NULL
27263
+ AND started_at < :cutoff
27264
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27265
+ AND synced_at IS NULL`);
27266
+ this.expireStmt = this.db.prepare(
27267
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27268
+ );
27269
+ }
27270
+ db;
27271
+ candidatesStmt;
27272
+ candidatesSyncSafeStmt;
27273
+ heldBySyncStmt;
27274
+ expireStmt;
27275
+ /** How many bytes a pass with these options would free, changing nothing. */
27276
+ preview(opts) {
27277
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27278
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27279
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27280
+ return {
27281
+ rowsExpired: rows.length,
27282
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27283
+ rowsHeldBySync: this.countHeldBySync(opts)
27284
+ };
27285
+ }
27286
+ /** Clear eligible bodies, in bounded batches. */
27287
+ expire(opts) {
27288
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27289
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27290
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27291
+ let rowsExpired = 0;
27292
+ let bytesFreed = 0;
27293
+ let done = true;
27294
+ while (rowsExpired < maxRows) {
27295
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27296
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27297
+ if (batch.length === 0) break;
27298
+ withTransaction(
27299
+ this.db,
27300
+ () => {
27301
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27302
+ },
27303
+ "IMMEDIATE"
27304
+ );
27305
+ rowsExpired += batch.length;
27306
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27307
+ if (batch.length < remaining) break;
27308
+ if (rowsExpired >= maxRows) {
27309
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27310
+ }
27311
+ }
27312
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27313
+ }
27314
+ countHeldBySync(opts) {
27315
+ if (opts.sweepSyncLane) return 0;
27316
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27317
+ return row.n;
27318
+ }
27319
+ };
27320
+
26214
27321
  // ../../packages/persistence/src/repositories/classified-data.ts
26215
27322
  var SqliteClassifiedDataRepository = class {
26216
27323
  constructor(db) {
@@ -27039,7 +28146,15 @@ function toFlatFindingRow(r) {
27039
28146
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
27040
28147
  eventId: r.event_id,
27041
28148
  ...r.session_id === null ? {} : { sessionId: r.session_id },
27042
- status: deriveInstanceStatus(r)
28149
+ status: deriveInstanceStatus(r),
28150
+ delivery: deriveFindingDelivery({
28151
+ kind: r.kind,
28152
+ syncedAt: r.synced_at,
28153
+ syncClaimedAt: r.sync_claimed_at,
28154
+ syncFailedAt: r.sync_failed_at,
28155
+ syncFailure: r.sync_failure,
28156
+ outboxOwed: r.outbox_owed
28157
+ })
27043
28158
  };
27044
28159
  }
27045
28160
  function encodeGroupCursor(group) {
@@ -27103,7 +28218,10 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
27103
28218
  e.tool_name AS tool_name,
27104
28219
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
27105
28220
  e.event_type AS kind, f.finding_key AS finding_key,
27106
- ${latestResolutionStatusSql("f")} AS latest_status`;
28221
+ ${latestResolutionStatusSql("f")} AS latest_status,
28222
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28223
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28224
+ e.outbox_owed AS outbox_owed`;
27107
28225
  var DAY_MS3 = 864e5;
27108
28226
  var SqliteFindingsRepository = class {
27109
28227
  constructor(db) {
@@ -27348,6 +28466,7 @@ var SqliteFindingsRepository = class {
27348
28466
  providers: query.provider,
27349
28467
  actions: query.action,
27350
28468
  statuses: query.status,
28469
+ deliveries: query.deployment,
27351
28470
  tools: query.tool,
27352
28471
  repo: query.repo,
27353
28472
  file: query.file,
@@ -27415,6 +28534,7 @@ var SqliteFindingsRepository = class {
27415
28534
  providers: query.provider,
27416
28535
  actions: query.action,
27417
28536
  statuses: query.status,
28537
+ deliveries: query.deployment,
27418
28538
  tools: query.tool,
27419
28539
  q: query.q
27420
28540
  };
@@ -27678,7 +28798,9 @@ var SqliteFindingsRepository = class {
27678
28798
  )
27679
28799
  );
27680
28800
  for (const row of grouped) {
27681
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28801
+ if (Object.hasOwn(byAction, row.action_taken)) {
28802
+ byAction[row.action_taken] = row.c;
28803
+ }
27682
28804
  }
27683
28805
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27684
28806
  const sevRows = allRows(
@@ -27695,7 +28817,9 @@ var SqliteFindingsRepository = class {
27695
28817
  )
27696
28818
  );
27697
28819
  for (const row of sevRows) {
27698
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28820
+ if (Object.hasOwn(bySeverity, row.severity)) {
28821
+ bySeverity[row.severity] = row.c;
28822
+ }
27699
28823
  }
27700
28824
  const categories = ENFORCEABLE_CATEGORIES;
27701
28825
  const enabledRows = allRows(
@@ -27744,525 +28868,6 @@ function isoDay(ms) {
27744
28868
  return new Date(ms).toISOString().slice(0, 10);
27745
28869
  }
27746
28870
 
27747
- // ../../packages/persistence/src/repositories/history-sync.ts
27748
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27749
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27750
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27751
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27752
- var SKIPPED = -1;
27753
- var ROW_COLUMNS = `id,
27754
- parent_id AS parentId,
27755
- root_session_id AS rootSessionId,
27756
- event_type AS eventType,
27757
- host_id AS hostId,
27758
- harness_id AS harnessId,
27759
- source_project_id AS sourceProjectId,
27760
- started_at AS startedAt,
27761
- ended_at AS endedAt,
27762
- severity,
27763
- priority,
27764
- content,
27765
- content_hash AS contentHash,
27766
- attributes`;
27767
- var SqliteHistorySyncRepository = class {
27768
- constructor(db) {
27769
- this.db = db;
27770
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27771
- this.sessionsStmt = db.prepare(
27772
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27773
- FROM audit_events
27774
- WHERE synced_at IS NULL
27775
- AND event_type IN (${TYPE_LIST})
27776
- AND started_at < :before
27777
- GROUP BY sessionId
27778
- ORDER BY earliest
27779
- LIMIT :limit`
27780
- );
27781
- this.rowsStmt = db.prepare(
27782
- `SELECT ${ROW_COLUMNS}
27783
- FROM audit_events
27784
- WHERE synced_at IS NULL
27785
- AND event_type IN (${TYPE_LIST})
27786
- AND started_at < :before
27787
- AND COALESCE(root_session_id, id) = :sessionId
27788
- ORDER BY (event_type = 'session') DESC, started_at
27789
- LIMIT :limit`
27790
- );
27791
- this.captureRowsStmt = db.prepare(
27792
- `SELECT ${ROW_COLUMNS}
27793
- FROM audit_events
27794
- WHERE synced_at IS NULL
27795
- AND sync_claimed_at IS NULL
27796
- AND outbox_owed = 1
27797
- AND event_type IN (${CAPTURE_TYPE_LIST})
27798
- AND started_at < :before
27799
- ORDER BY started_at
27800
- LIMIT :limit`
27801
- );
27802
- this.markOwedStmt = db.prepare(
27803
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27804
- );
27805
- this.markCaptureBacklogOwedStmt = db.prepare(
27806
- `UPDATE audit_events SET outbox_owed = 1
27807
- WHERE synced_at IS NULL
27808
- AND event_type IN (${CAPTURE_TYPE_LIST})
27809
- AND started_at < :before`
27810
- );
27811
- this.stampStmt = db.prepare(
27812
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27813
- );
27814
- this.claimRowStmt = db.prepare(
27815
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27816
- );
27817
- this.releaseRowStmt = db.prepare(
27818
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27819
- );
27820
- this.releaseStaleClaimsStmt = db.prepare(
27821
- `UPDATE audit_events SET sync_claimed_at = NULL
27822
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27823
- );
27824
- this.partitionStmt = db.prepare(
27825
- `SELECT
27826
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27827
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27828
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27829
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27830
- COUNT(*) AS total
27831
- FROM audit_events
27832
- WHERE event_type IN (${TYPE_LIST})`
27833
- );
27834
- this.countsStmt = db.prepare(
27835
- `SELECT
27836
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27837
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27838
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27839
- FROM audit_events
27840
- WHERE event_type IN (${TYPE_LIST})`
27841
- );
27842
- this.captureSkipCountStmt = db.prepare(
27843
- `SELECT COUNT(*) AS skipped
27844
- FROM audit_events
27845
- WHERE synced_at = ${String(SKIPPED)}
27846
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27847
- );
27848
- this.fingerprintStmt = db.prepare(
27849
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27850
- FROM history_sync WHERE id = 1`
27851
- );
27852
- this.setFingerprintStmt = db.prepare(
27853
- `UPDATE history_sync
27854
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27855
- WHERE id = 1`
27856
- );
27857
- this.disownCapturesStmt = db.prepare(
27858
- `UPDATE audit_events SET outbox_owed = NULL
27859
- WHERE outbox_owed IS NOT NULL
27860
- AND event_type IN (${CAPTURE_TYPE_LIST})
27861
- AND started_at < :attachedAt`
27862
- );
27863
- this.rearmStmt = db.prepare(
27864
- `UPDATE audit_events SET synced_at = NULL
27865
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27866
- );
27867
- this.claimStmt = db.prepare(
27868
- `UPDATE history_sync
27869
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27870
- WHERE id = 1
27871
- AND (owner_pid IS NULL
27872
- OR heartbeat_at IS NULL
27873
- OR heartbeat_at < :staleBefore
27874
- OR heartbeat_at > :now)`
27875
- );
27876
- this.heartbeatStmt = db.prepare(
27877
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27878
- );
27879
- this.releaseStmt = db.prepare(
27880
- `UPDATE history_sync
27881
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27882
- WHERE id = 1 AND owner_pid = :pid`
27883
- );
27884
- this.closeWindowStmt = db.prepare(
27885
- `UPDATE audit_events SET synced_at = :at
27886
- WHERE synced_at IS NULL
27887
- AND event_type IN (${TYPE_LIST})
27888
- AND started_at >= :attachedAt`
27889
- );
27890
- this.releaseBoundaryStmt = db.prepare(
27891
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27892
- );
27893
- this.freezeBoundaryStmt = db.prepare(
27894
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27895
- );
27896
- this.leaseStmt = db.prepare(
27897
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27898
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27899
- FROM history_sync WHERE id = 1`
27900
- );
27901
- this.inspectionsStmt = db.prepare(
27902
- `SELECT d.rule_id AS ruleId,
27903
- d.name AS ruleName,
27904
- d.version AS ruleVersion,
27905
- d.category AS category,
27906
- d.severity AS severity,
27907
- f.span_start AS spanStart,
27908
- f.span_end AS spanEnd,
27909
- f.masked_match AS maskedMatch,
27910
- f.action_taken AS actionTaken,
27911
- f.confidence AS confidence
27912
- FROM inspection_findings f
27913
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27914
- WHERE f.audit_event_id = :auditEventId
27915
- ORDER BY f.span_start, f.id`
27916
- );
27917
- }
27918
- db;
27919
- ensureRowStmt;
27920
- sessionsStmt;
27921
- rowsStmt;
27922
- stampStmt;
27923
- countsStmt;
27924
- fingerprintStmt;
27925
- setFingerprintStmt;
27926
- rearmStmt;
27927
- claimStmt;
27928
- heartbeatStmt;
27929
- releaseStmt;
27930
- leaseStmt;
27931
- inspectionsStmt;
27932
- closeWindowStmt;
27933
- releaseBoundaryStmt;
27934
- freezeBoundaryStmt;
27935
- captureRowsStmt;
27936
- markOwedStmt;
27937
- markCaptureBacklogOwedStmt;
27938
- captureSkipCountStmt;
27939
- disownCapturesStmt;
27940
- partitionStmt;
27941
- claimRowStmt;
27942
- releaseRowStmt;
27943
- releaseStaleClaimsStmt;
27944
- /**
27945
- * The masked detections recorded against one tool call.
27946
- *
27947
- * These travel with the event because a tool call's target is not
27948
- * re-inspectable from the event alone — unlike a capture, where the text
27949
- * itself is re-scannable. What crosses is the masked match and the rule that
27950
- * produced it, never the value.
27951
- */
27952
- inspectionsFor(auditEventId) {
27953
- return allRows(this.inspectionsStmt, { auditEventId });
27954
- }
27955
- /**
27956
- * Sessions with structural rows still to send, oldest first.
27957
- *
27958
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27959
- * read. Anything recorded after the machine attached is the live forward
27960
- * path's to deliver; this drain exists for what was recorded before it, and a
27961
- * row both paths send is at best a duplicate request and at worst — for a
27962
- * session root — an overwrite of the inventory ids the live path resolved.
27963
- */
27964
- pendingSessions(limit, before) {
27965
- return allRows(this.sessionsStmt, { limit, before }).map(
27966
- (r) => r.sessionId
27967
- );
27968
- }
27969
- /** One session's undelivered structural rows within the backlog, root first. */
27970
- pendingRows(sessionId, limit, before) {
27971
- return allRows(this.rowsStmt, { sessionId, limit, before });
27972
- }
27973
- /**
27974
- * Captures this machine still owes the deployment, oldest first.
27975
- *
27976
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27977
- * by a time window — see captureRowsStmt for why a window could not express
27978
- * this. `before` is the grace window that leaves a just-recorded capture to
27979
- * the live path.
27980
- */
27981
- pendingCaptureRows(limit, before) {
27982
- return allRows(this.captureRowsStmt, { limit, before });
27983
- }
27984
- /**
27985
- * Record that a capture is OWED to the deployment.
27986
- *
27987
- * Written by the attached forward path when a live send did not confirm
27988
- * delivery, and read by the drain as the whole of its eligibility test. It is
27989
- * a fact rather than an inference: the machine was attached, the send did not
27990
- * land, so the row is owed — which no time window can state, because the same
27991
- * window that holds the rows a past attachment left owed also holds every
27992
- * capture recorded while the machine was DETACHED, and those were never
27993
- * offered to anyone.
27994
- *
27995
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27996
- * out of the drain's read.
27997
- */
27998
- markCaptureOwed(id) {
27999
- this.markOwedStmt.run({ id });
28000
- }
28001
- /**
28002
- * Mark every capture already on disk as owed, as of `before`.
28003
- *
28004
- * The consent-time backfill, called once from `aka attach` when a human
28005
- * grants existing-history consent — never from an ongoing drain pass, and
28006
- * never inferred from a boundary that could later move. `before` is the
28007
- * caller's own "now" at the moment consent was granted, so what this marks
28008
- * is exactly the backlog the consent prompt already counted, not whatever a
28009
- * later re-attach or key rotation might widen it to.
28010
- *
28011
- * Returns how many rows matched, for the caller to log or test against. Not a
28012
- * count of NEWLY marked rows — a row still unsynced from an earlier call
28013
- * matches again and is counted again, the same as `UPDATE`'s own `changes`.
28014
- */
28015
- markCaptureBacklogOwed(before) {
28016
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
28017
- }
28018
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
28019
- markSynced(ids, atMs) {
28020
- this.stampAll(ids, atMs);
28021
- }
28022
- /**
28023
- * Record that a row will never be sent.
28024
- *
28025
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
28026
- * payload. A row that merely failed to reach the deployment stays NULL, so it
28027
- * is retried; marking those would turn one outage into permanent data loss.
28028
- */
28029
- markSkipped(ids) {
28030
- this.stampAll(ids, SKIPPED);
28031
- }
28032
- eachInTransaction(ids, run) {
28033
- if (ids.length === 0) return;
28034
- withTransaction(
28035
- this.db,
28036
- () => {
28037
- for (const id of ids) run(id);
28038
- },
28039
- "IMMEDIATE"
28040
- );
28041
- }
28042
- stampAll(ids, value) {
28043
- if (ids.length === 0) return;
28044
- withTransaction(
28045
- this.db,
28046
- () => {
28047
- for (const id of ids) this.stampStmt.run({ at: value, id });
28048
- },
28049
- "IMMEDIATE"
28050
- );
28051
- }
28052
- /**
28053
- * Claim rows as in-flight.
28054
- *
28055
- * Advisory in exactly the sense the lease is: it records that a send is in
28056
- * progress so a surface can say so, and a lost claim costs a row showing as
28057
- * queued while it is actually being sent. It is not exclusion — the far side
28058
- * settles a duplicate on the row id.
28059
- */
28060
- claimRows(ids, atMs) {
28061
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
28062
- }
28063
- /** Give back a claim without settling — the send failed, the row is queued again. */
28064
- releaseRows(ids) {
28065
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
28066
- }
28067
- /**
28068
- * Clear claims older than `staleBefore`, and report how many were cleared.
28069
- *
28070
- * A process killed between claiming and settling leaves rows claimed with
28071
- * nothing left to settle them. Without this they read as "sending" for ever.
28072
- */
28073
- releaseStaleClaims(staleBefore) {
28074
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
28075
- }
28076
- /**
28077
- * Every tracked row in exactly one delivery state.
28078
- *
28079
- * Takes no boundary on purpose. The boundary answers "what should the drain
28080
- * pick up now", which is a different question from "what state is this row
28081
- * in" — and a machine that has never attached has no boundary to pass, so
28082
- * requiring one would force a caller to invent one and report the whole store
28083
- * as queued.
28084
- */
28085
- partition() {
28086
- const row = getRow(this.partitionStmt, {});
28087
- return {
28088
- queued: row?.queued ?? 0,
28089
- inProgress: row?.inProgress ?? 0,
28090
- synced: row?.synced ?? 0,
28091
- failed: row?.failed ?? 0,
28092
- total: row?.total ?? 0
28093
- };
28094
- }
28095
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
28096
- counts(before) {
28097
- const row = getRow(
28098
- this.countsStmt,
28099
- { before }
28100
- );
28101
- const captures = getRow(this.captureSkipCountStmt);
28102
- return {
28103
- pending: row?.pending ?? 0,
28104
- sent: row?.sent ?? 0,
28105
- skipped: row?.skipped ?? 0,
28106
- capturesSkipped: captures?.skipped ?? 0
28107
- };
28108
- }
28109
- /**
28110
- * The deployment the current stamps were made against, and where its backlog
28111
- * ends.
28112
- *
28113
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
28114
- * machine that has never drained is — and every writer below seeds the row
28115
- * before it needs one, so nothing depends on this creating it. Keeping the
28116
- * write off the gate path matters because the gate runs on every pass while a
28117
- * write has to take the database's write lock.
28118
- */
28119
- deployment() {
28120
- const row = getRow(
28121
- this.fingerprintStmt
28122
- );
28123
- return {
28124
- fingerprint: row?.fingerprint ?? void 0,
28125
- backlogBefore: row?.backlogBefore ?? void 0
28126
- };
28127
- }
28128
- /**
28129
- * Point the ledger at a different deployment, discarding what it recorded
28130
- * about the previous one.
28131
- *
28132
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28133
- * machine has just left are undelivered as far as the new one is concerned.
28134
- * All four in one transaction, so a crash between them cannot leave stamps
28135
- * attributed to the wrong deployment, a boundary that belongs to another, or
28136
- * a disown with no re-mark to follow it.
28137
- *
28138
- * The boundary is written HERE and only here, which is what freezes it: a
28139
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28140
- * unchanged, so this never runs and the backlog does not widen back over rows
28141
- * the live path has since delivered.
28142
- *
28143
- * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28144
- * granted existing-history consent for the deployment this call is arming —
28145
- * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28146
- * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28147
- * apart. Passed only when that grant is valid, since this method has no way
28148
- * to check consent itself and must not mark a row owed for a machine that
28149
- * never agreed to it. Applied AFTER the disown above, in the SAME
28150
- * transaction: what the disown clears is every marker below `backlogBefore`,
28151
- * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28152
- * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28153
- * on the cleared side of that bound — and the re-mark in the same
28154
- * transaction is what puts those rows back. A crash between the two cannot
28155
- * strand the ledger disowned with nothing re-marked — the transaction either
28156
- * lands whole or not at all, and a fingerprint mismatch that has not yet
28157
- * committed re-enters this method on the very next pass. Omit it (the
28158
- * structural-only tests do) to exercise the disown in isolation.
28159
- *
28160
- * The disown is bounded by `backlogBefore`, which is what keeps it from
28161
- * touching a marker the NEW deployment's OWN live path has already set: B's
28162
- * live path can mark a capture owed from the moment `aka attach` writes the
28163
- * descriptor, before the drain's first pass ever reaches this method, and
28164
- * such a row sits at or after the bound rather than below it. What keeps the
28165
- * disown from eating THIS SAME CALL's own re-mark is the order, not the
28166
- * bound — disown runs first, re-mark second, both inside the one
28167
- * transaction above.
28168
- */
28169
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28170
- this.ensureRowStmt.run();
28171
- withTransaction(
28172
- this.db,
28173
- () => {
28174
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28175
- this.rearmStmt.run();
28176
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28177
- this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28178
- }
28179
- if (backfillCapturesBefore !== void 0) {
28180
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28181
- }
28182
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28183
- },
28184
- "IMMEDIATE"
28185
- );
28186
- }
28187
- /**
28188
- * End the attached period: hand its rows to the live path, and release the
28189
- * boundary so the next attachment can freeze a new one.
28190
- *
28191
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28192
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28193
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28194
- * during the detached period, because the machine is not attached. Rows
28195
- * recorded in that window sit after the boundary and before the re-attach, so
28196
- * neither path takes them, and the pending count reports none outstanding.
28197
- *
28198
- * Stamping the attached window is not a claim that every one of those rows
28199
- * reached the deployment — the live path drops on failure and says so
28200
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28201
- * status quo: they sit outside the frozen boundary today and are equally never
28202
- * re-sent. Making it explicit is what lets the boundary move.
28203
- *
28204
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28205
- * window unstamped — that half-state would re-send the whole attached period
28206
- * on the next attach, which is the failure the boundary exists to prevent.
28207
- */
28208
- closeAttachedWindow(attachedAtMs, atMs) {
28209
- this.ensureRowStmt.run();
28210
- withTransaction(
28211
- this.db,
28212
- () => {
28213
- const row = getRow(this.fingerprintStmt);
28214
- const from = row?.backlogBefore ?? attachedAtMs;
28215
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28216
- this.releaseBoundaryStmt.run();
28217
- },
28218
- "IMMEDIATE"
28219
- );
28220
- }
28221
- /**
28222
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28223
- *
28224
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28225
- * different deployment and therefore discards what was delivered to the old
28226
- * one: here the recipient is the same, so everything already sent to it stays
28227
- * sent.
28228
- */
28229
- freezeBoundary(backlogBefore) {
28230
- this.ensureRowStmt.run();
28231
- this.freezeBoundaryStmt.run({ backlogBefore });
28232
- }
28233
- /** Take the claim, or report that someone live already holds it. */
28234
- claim(pid, host, nowMs, staleAfterMs) {
28235
- this.ensureRowStmt.run();
28236
- let taken = false;
28237
- withTransaction(
28238
- this.db,
28239
- () => {
28240
- const result = this.claimStmt.run({
28241
- pid,
28242
- host,
28243
- now: nowMs,
28244
- staleBefore: nowMs - staleAfterMs
28245
- });
28246
- taken = result.changes === 1;
28247
- },
28248
- "IMMEDIATE"
28249
- );
28250
- return taken;
28251
- }
28252
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28253
- heartbeat(pid, nowMs) {
28254
- this.heartbeatStmt.run({ now: nowMs, pid });
28255
- }
28256
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28257
- release(pid) {
28258
- this.releaseStmt.run({ pid });
28259
- }
28260
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28261
- lease() {
28262
- return getRow(this.leaseStmt);
28263
- }
28264
- };
28265
-
28266
28871
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28267
28872
  var SqliteInspectionDefinitionsRepository = class {
28268
28873
  constructor(db) {
@@ -28490,6 +29095,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28490
29095
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28491
29096
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28492
29097
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29098
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28493
29099
  if (values.vaultConsent !== void 0) {
28494
29100
  merged.vaultConsent = values.vaultConsent ? (
28495
29101
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30997,7 +31603,7 @@ var SqliteSecurityRepository = class {
30997
31603
  ELSE 0
30998
31604
  END) AS open_at_rest
30999
31605
  FROM inspection_findings f
31000
- JOIN audit_events e ON e.id = f.audit_event_id
31606
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31001
31607
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31002
31608
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31003
31609
  ON latest.finding_key = f.finding_key
@@ -31223,7 +31829,7 @@ var SqliteSecurityRepository = class {
31223
31829
  this.db.prepare(
31224
31830
  `SELECT e.repo AS repo, count(*) AS c
31225
31831
  FROM inspection_findings f
31226
- JOIN audit_events e ON e.id = f.audit_event_id
31832
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31227
31833
  WHERE e.started_at >= :from AND e.started_at < :to
31228
31834
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31229
31835
  AND e.repo IS NOT NULL
@@ -31347,7 +31953,7 @@ var SqliteSecurityRepository = class {
31347
31953
  d.severity AS severity,
31348
31954
  COUNT(*) AS count
31349
31955
  FROM inspection_findings f
31350
- JOIN audit_events e ON e.id = f.audit_event_id
31956
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31351
31957
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31352
31958
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31353
31959
  ON latest.finding_key = f.finding_key
@@ -31382,7 +31988,7 @@ var SqliteSecurityRepository = class {
31382
31988
  `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31383
31989
  d.rule_id AS rule_id, d.category AS category
31384
31990
  FROM inspection_findings f
31385
- JOIN audit_events e ON e.id = f.audit_event_id
31991
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31386
31992
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31387
31993
  WHERE e.started_at >= :from AND e.started_at < :to
31388
31994
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -32223,6 +32829,7 @@ function openWithPragmas(file2) {
32223
32829
  db.exec("PRAGMA journal_mode = WAL");
32224
32830
  db.exec("PRAGMA busy_timeout = 2000");
32225
32831
  db.exec("PRAGMA foreign_keys = ON");
32832
+ registerSqlFunctions(db);
32226
32833
  } catch (err) {
32227
32834
  closeQuietly(db);
32228
32835
  throw err;
@@ -32252,7 +32859,7 @@ function backupLegacyStore(db, file2) {
32252
32859
  discardStore(file2, backup);
32253
32860
  return backup;
32254
32861
  }
32255
- function openAndInitialize(file2, base) {
32862
+ function openAndInitialize(file2, base, skipTags) {
32256
32863
  let db = openWithPragmas(file2);
32257
32864
  try {
32258
32865
  if (isForeignSqliteLineage(db)) {
@@ -32262,7 +32869,7 @@ function openAndInitialize(file2, base) {
32262
32869
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32263
32870
  );
32264
32871
  }
32265
- applyMigrations(db, file2);
32872
+ applyMigrations(db, file2, { skipTags });
32266
32873
  tightenPerms(file2);
32267
32874
  const policies = new SqlitePoliciesRepository(db);
32268
32875
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32277,6 +32884,7 @@ function openAndInitialize(file2, base) {
32277
32884
  exceptions: new SqliteExceptionsRepository(db),
32278
32885
  resolutions: new SqliteResolutionsRepository(db),
32279
32886
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32887
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32280
32888
  security: new SqliteSecurityRepository(db),
32281
32889
  detections: new SqliteDetectionsRepository(db),
32282
32890
  shares: new SqliteSharesRepository(db),
@@ -32299,7 +32907,8 @@ function openAndInitialize(file2, base) {
32299
32907
  throw err;
32300
32908
  }
32301
32909
  }
32302
- function openLocalDatabase(dir) {
32910
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32911
+ function openLocalDatabase(dir, options = {}) {
32303
32912
  ensureDataDirSync(dir);
32304
32913
  const file2 = join7(dir, DB_FILENAME);
32305
32914
  reapStalePartials(file2);
@@ -32311,6 +32920,7 @@ function openLocalDatabase(dir) {
32311
32920
  installedPacks,
32312
32921
  scanLedger,
32313
32922
  historySync,
32923
+ bodyRetention,
32314
32924
  secretVault,
32315
32925
  exceptions,
32316
32926
  resolutions,
@@ -32334,7 +32944,8 @@ function openLocalDatabase(dir) {
32334
32944
  // `dir` is always `<base>/data` — every caller resolves it through
32335
32945
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32336
32946
  // settings/ and data/, and the pack-policy floor needs both halves.
32337
- dirname2(dir)
32947
+ dirname2(dir),
32948
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32338
32949
  );
32339
32950
  function captureRowId(event) {
32340
32951
  return captureId(
@@ -32527,6 +33138,7 @@ function openLocalDatabase(dir) {
32527
33138
  installedPacks,
32528
33139
  scanLedger,
32529
33140
  historySync,
33141
+ bodyRetention,
32530
33142
  secretVault,
32531
33143
  exceptions,
32532
33144
  resolutions,
@@ -32567,8 +33179,35 @@ function openLocalDatabase(dir) {
32567
33179
 
32568
33180
  // ../../packages/persistence/src/egress-wire.ts
32569
33181
  import { createHash as createHash3 } from "crypto";
33182
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33183
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33184
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33185
+ var FILE_URL = /^file:\/\//i;
33186
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33187
+ var SLASH = "/".charCodeAt(0);
33188
+ var GIT_SUFFIX = ".git";
33189
+ function trimSlashes(path) {
33190
+ let start = 0;
33191
+ let end = path.length;
33192
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33193
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33194
+ return path.slice(start, end);
33195
+ }
33196
+ function canonicalGitUrl(url2) {
33197
+ const trimmed = url2.trim();
33198
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33199
+ const scheme = SCHEME_FORM.exec(trimmed);
33200
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33201
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33202
+ if (host === void 0) return trimmed;
33203
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33204
+ const bare = trimSlashes(path);
33205
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33206
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33207
+ }
32570
33208
  function hashProjectKey(projectKey) {
32571
- return createHash3("sha256").update(projectKey, "utf8").digest("hex");
33209
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33210
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
32572
33211
  }
32573
33212
  function toIngestHit(hit) {
32574
33213
  return {
@@ -32644,18 +33283,50 @@ function readFingerprintKey(dataDir2) {
32644
33283
  return parseKeyFile(raw);
32645
33284
  }
32646
33285
 
33286
+ // ../../packages/persistence/src/forward-health.ts
33287
+ import { readFileSync as readFileSync7 } from "fs";
33288
+ import { join as join9 } from "path";
33289
+ var FAILURES = /* @__PURE__ */ new Set([
33290
+ "unauthorized",
33291
+ "forbidden",
33292
+ "unreachable"
33293
+ ]);
33294
+ var BREAKER_COOLDOWN_MS = 3e4;
33295
+ function parseForwardHealth(raw, nowMs) {
33296
+ try {
33297
+ const parsed2 = JSON.parse(raw);
33298
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33299
+ const record2 = parsed2;
33300
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33301
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33302
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33303
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33304
+ } catch {
33305
+ return null;
33306
+ }
33307
+ }
33308
+ function isForwardPaused(health, nowMs) {
33309
+ const openedAtMs = health?.openedAtMs ?? null;
33310
+ if (openedAtMs === null) return false;
33311
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33312
+ }
33313
+
32647
33314
  // ../../packages/persistence/src/history-backfill.ts
32648
33315
  import { existsSync as existsSync4 } from "fs";
32649
- import { join as join9 } from "path";
33316
+ import { join as join10 } from "path";
32650
33317
 
32651
33318
  // ../../packages/persistence/src/history-preview.ts
32652
33319
  import { existsSync as existsSync5 } from "fs";
32653
- import { join as join10 } from "path";
33320
+ import { join as join11 } from "path";
32654
33321
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32655
33322
 
33323
+ // ../../packages/persistence/src/history-sync-state.ts
33324
+ import { readFileSync as readFileSync8 } from "fs";
33325
+ import { join as join12 } from "path";
33326
+
32656
33327
  // ../../packages/persistence/src/store-symlinks.ts
32657
33328
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32658
- import { dirname as dirname3, join as join11, resolve } from "path";
33329
+ import { dirname as dirname3, join as join13, resolve } from "path";
32659
33330
 
32660
33331
  // ../../packages/persistence/src/vault/crypto.ts
32661
33332
  import {
@@ -32669,19 +33340,19 @@ import {
32669
33340
  // ../../packages/persistence/src/vault/key-provider.ts
32670
33341
  import { execFileSync } from "child_process";
32671
33342
  import { randomBytes as randomBytes2 } from "crypto";
32672
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32673
- import { join as join12 } from "path";
33343
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33344
+ import { join as join14 } from "path";
32674
33345
 
32675
33346
  // ../../packages/persistence/src/vault/vault.ts
32676
33347
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32677
33348
 
32678
33349
  // ../../packages/persistence/src/warn-era-cap.ts
32679
33350
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
32680
- import { join as join13 } from "path";
33351
+ import { join as join15 } from "path";
32681
33352
  var MARKER = "warn-era-capped";
32682
33353
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32683
33354
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32684
- const marker = join13(dataDir2, MARKER);
33355
+ const marker = join15(dataDir2, MARKER);
32685
33356
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32686
33357
  const capped = db.policies.capCategoryActions();
32687
33358
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -32872,10 +33543,10 @@ function parsed(schema, body, route) {
32872
33543
  }
32873
33544
  function withoutTrailingSlashes(endpoint) {
32874
33545
  let end = endpoint.length;
32875
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
33546
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
32876
33547
  return endpoint.slice(0, end);
32877
33548
  }
32878
- var SLASH = "/".charCodeAt(0);
33549
+ var SLASH2 = "/".charCodeAt(0);
32879
33550
  function createRemoteClient(options) {
32880
33551
  const base = withoutTrailingSlashes(options.endpoint);
32881
33552
  const url2 = (route) => `${base}${route}`;
@@ -33057,11 +33728,11 @@ function withTimeout(promise2, ms) {
33057
33728
  }
33058
33729
 
33059
33730
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
33060
- import { readFileSync as readFileSync8 } from "fs";
33061
- import { join as join14 } from "path";
33731
+ import { readFileSync as readFileSync10 } from "fs";
33732
+ import { join as join16 } from "path";
33062
33733
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
33063
33734
  function forwardDropsPath(dataDir2) {
33064
- return join14(dataDir2, FORWARD_DROPS_FILENAME);
33735
+ return join16(dataDir2, FORWARD_DROPS_FILENAME);
33065
33736
  }
33066
33737
  function recordForwardDrops(dataDir2, count, nowMs) {
33067
33738
  if (count <= 0) return;
@@ -33079,7 +33750,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
33079
33750
  }
33080
33751
  function readForwardDrops(dataDir2) {
33081
33752
  try {
33082
- const parsed2 = JSON.parse(readFileSync8(forwardDropsPath(dataDir2), "utf8"));
33753
+ const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
33083
33754
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
33084
33755
  const record2 = parsed2;
33085
33756
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -33097,13 +33768,12 @@ function readForwardDrops(dataDir2) {
33097
33768
 
33098
33769
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
33099
33770
  import { randomUUID as randomUUID15 } from "crypto";
33100
- import { readFileSync as readFileSync15 } from "fs";
33101
33771
  import { readFile, rename, writeFile } from "fs/promises";
33102
- import { join as join24 } from "path";
33772
+ import { join as join26 } from "path";
33103
33773
 
33104
33774
  // ../../packages/plugin-sdk/src/config.ts
33105
33775
  import { existsSync as existsSync8 } from "fs";
33106
- import { join as join15 } from "path";
33776
+ import { join as join17 } from "path";
33107
33777
 
33108
33778
  // ../../packages/plugin-sdk/src/provider-env.ts
33109
33779
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -33157,7 +33827,7 @@ function resolveProvider() {
33157
33827
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
33158
33828
  try {
33159
33829
  ensureLayoutDirSync(base);
33160
- const settingsFile = join15(settingsDir(base), "settings.json");
33830
+ const settingsFile = join17(settingsDir(base), "settings.json");
33161
33831
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
33162
33832
  } catch {
33163
33833
  }
@@ -33181,9 +33851,9 @@ function resolveProviderSafe(resolveProviderFn) {
33181
33851
  }
33182
33852
 
33183
33853
  // ../../packages/plugin-sdk/src/config-inventory.ts
33184
- import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33854
+ import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33185
33855
  import { homedir as homedir2 } from "os";
33186
- import { basename as basename3, join as join17 } from "path";
33856
+ import { basename as basename3, join as join19 } from "path";
33187
33857
 
33188
33858
  // ../../packages/detections/src/egress/registry.ts
33189
33859
  var EXTRACTOR_VERSION = "1";
@@ -35966,8 +36636,8 @@ function bundledDetections() {
35966
36636
  }
35967
36637
 
35968
36638
  // ../../packages/plugin-sdk/src/repo.ts
35969
- import { existsSync as existsSync9, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
35970
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join16, sep as sep2 } from "path";
36639
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
36640
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
35971
36641
 
35972
36642
  // ../../packages/plugin-sdk/src/events.ts
35973
36643
  import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
@@ -35978,8 +36648,8 @@ import { fileURLToPath } from "url";
35978
36648
  import { Worker } from "worker_threads";
35979
36649
 
35980
36650
  // ../../packages/plugin-sdk/src/host-floor.ts
35981
- import { readFileSync as readFileSync12 } from "fs";
35982
- import { join as join19 } from "path";
36651
+ import { readFileSync as readFileSync14 } from "fs";
36652
+ import { join as join21 } from "path";
35983
36653
 
35984
36654
  // ../../packages/plugin-sdk/src/model-governance.ts
35985
36655
  import {
@@ -35987,11 +36657,11 @@ import {
35987
36657
  fstatSync,
35988
36658
  mkdirSync as mkdirSync2,
35989
36659
  openSync as openSync2,
35990
- readFileSync as readFileSync11,
36660
+ readFileSync as readFileSync13,
35991
36661
  readSync,
35992
36662
  writeFileSync as writeFileSync5
35993
36663
  } from "fs";
35994
- import { join as join18 } from "path";
36664
+ import { join as join20 } from "path";
35995
36665
  var TAIL_BYTES = 256 * 1024;
35996
36666
 
35997
36667
  // ../../packages/plugin-sdk/src/host-floor.ts
@@ -36014,15 +36684,15 @@ var HOST_FLOORS = {
36014
36684
 
36015
36685
  // ../../packages/plugin-sdk/src/ignore-layers.ts
36016
36686
  var import_ignore = __toESM(require_ignore(), 1);
36017
- import { readFileSync as readFileSync13 } from "fs";
36018
- import { join as join20 } from "path";
36687
+ import { readFileSync as readFileSync15 } from "fs";
36688
+ import { join as join22 } from "path";
36019
36689
 
36020
36690
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
36021
36691
  import { arch, hostname as hostname4, platform, release } from "os";
36022
36692
 
36023
36693
  // ../../packages/plugin-sdk/src/nudge.ts
36024
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync14, writeFileSync as writeFileSync6 } from "fs";
36025
- import { join as join21 } from "path";
36694
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
36695
+ import { join as join23 } from "path";
36026
36696
 
36027
36697
  // ../../packages/plugin-sdk/src/paths.ts
36028
36698
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -36030,7 +36700,7 @@ import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
36030
36700
 
36031
36701
  // ../../packages/plugin-sdk/src/project-files.ts
36032
36702
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
36033
- import { basename as basename5, join as join22 } from "path";
36703
+ import { basename as basename5, join as join24 } from "path";
36034
36704
 
36035
36705
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
36036
36706
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -36066,7 +36736,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
36066
36736
 
36067
36737
  // ../../packages/plugin-sdk/src/throttle.ts
36068
36738
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
36069
- import { join as join23 } from "path";
36739
+ import { join as join25 } from "path";
36070
36740
 
36071
36741
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
36072
36742
  function isInvalidRequest(err) {
@@ -36082,31 +36752,12 @@ function isServerRejection(err) {
36082
36752
  var FORWARD_BUDGET_MS = 1500;
36083
36753
  var DECISION_PATH_BUDGET_MS = 800;
36084
36754
  var BREAKER_FAILURE_THRESHOLD = 3;
36085
- var BREAKER_COOLDOWN_MS = 3e4;
36086
36755
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
36087
- var FAILURES = /* @__PURE__ */ new Set([
36088
- "unauthorized",
36089
- "forbidden",
36090
- "unreachable"
36091
- ]);
36092
36756
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
36093
36757
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
36094
- function parseBreakerState(raw, nowMs) {
36095
- try {
36096
- const parsed2 = JSON.parse(raw);
36097
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
36098
- const record2 = parsed2;
36099
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
36100
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
36101
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
36102
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
36103
- } catch {
36104
- return null;
36105
- }
36106
- }
36107
36758
  function createForwardPolicy(deps) {
36108
36759
  const now = deps.now ?? (() => Date.now());
36109
- const file2 = join24(deps.dir, STATE_FILENAME);
36760
+ const file2 = join26(deps.dir, STATE_FILENAME);
36110
36761
  let state = null;
36111
36762
  let loading = null;
36112
36763
  async function readState() {
@@ -36116,7 +36767,7 @@ function createForwardPolicy(deps) {
36116
36767
  } catch {
36117
36768
  return { ...CLOSED };
36118
36769
  }
36119
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
36770
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
36120
36771
  }
36121
36772
  async function load() {
36122
36773
  if (state !== null) return state;
@@ -36162,7 +36813,7 @@ function createForwardPolicy(deps) {
36162
36813
  };
36163
36814
  const at = now();
36164
36815
  if (current.openedAtMs !== null) {
36165
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
36816
+ if (isForwardPaused(current, at)) {
36166
36817
  return { ok: false, reason: "breaker-open" };
36167
36818
  }
36168
36819
  await persist({
@@ -36699,7 +37350,18 @@ var AttachedDataGateway = class {
36699
37350
  // and the spread above would otherwise drop the field silently — which is
36700
37351
  // exactly what it did, leaving the whole control inert on every device
36701
37352
  // while every test around it stayed green.
36702
- prohibitedModels: cached2.prohibitedModels
37353
+ prohibitedModels: cached2.prohibitedModels,
37354
+ // NAMED for the same reason as the line above, and it is the same defect
37355
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
37356
+ // only the cache carries is dropped in silence. That is what left
37357
+ // `prohibitedModels` inert on every attached device with every test
37358
+ // around it green.
37359
+ //
37360
+ // Taken from the cache rather than merged here, because merging it needs
37361
+ // the device's own SETTING — which is not a bundle field and is not in
37362
+ // scope at this seam. The runtime does that merge, raise-only, where both
37363
+ // values are in hand (createPluginRuntime's ensureInitialized).
37364
+ redactFallback: cached2.redactFallback
36703
37365
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
36704
37366
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
36705
37367
  // it emits, so an 'authored' policy arriving from the control plane
@@ -36827,10 +37489,6 @@ function toolAuditEvent(input2) {
36827
37489
  };
36828
37490
  }
36829
37491
 
36830
- // ../../packages/plugin-runtime/src/attached/history-state.ts
36831
- import { readFileSync as readFileSync16 } from "fs";
36832
- import { join as join25 } from "path";
36833
-
36834
37492
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
36835
37493
  import { createHash as createHash6 } from "crypto";
36836
37494
  import { hostname as hostname5 } from "os";
@@ -36839,6 +37497,10 @@ import { hostname as hostname5 } from "os";
36839
37497
  var CORRELATION_ID = EventMetadata.shape.correlationId;
36840
37498
  var TRACE_ID = EventMetadata.shape.traceId;
36841
37499
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
37500
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
37501
+
37502
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
37503
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
36842
37504
 
36843
37505
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
36844
37506
  import { spawn } from "child_process";
@@ -36865,7 +37527,7 @@ function createPluginBlock(build, policyStore) {
36865
37527
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
36866
37528
  import { randomUUID as randomUUID16 } from "crypto";
36867
37529
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
36868
- import { join as join26 } from "path";
37530
+ import { join as join27 } from "path";
36869
37531
 
36870
37532
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
36871
37533
  import { rename as rename2 } from "fs/promises";
@@ -36889,7 +37551,7 @@ async function publishByRename(tmp, file2, move = rename2) {
36889
37551
 
36890
37552
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
36891
37553
  function createPolicyStore(dir = dataDir()) {
36892
- const file2 = join26(dir, "policy-cache.json");
37554
+ const file2 = join27(dir, "policy-cache.json");
36893
37555
  async function read() {
36894
37556
  try {
36895
37557
  const raw = await readFile2(file2, "utf8");
@@ -37120,11 +37782,11 @@ function readStorePosture(dbPath2) {
37120
37782
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
37121
37783
  import { randomUUID as randomUUID17 } from "crypto";
37122
37784
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
37123
- import { join as join27 } from "path";
37785
+ import { join as join28 } from "path";
37124
37786
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
37125
37787
  function createPostureStore(dir = settingsDir(), legacyDir) {
37126
- const file2 = join27(dir, "posture-state.json");
37127
- const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
37788
+ const file2 = join28(dir, "posture-state.json");
37789
+ const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
37128
37790
  async function persist(state) {
37129
37791
  await ensureDataDir(dir);
37130
37792
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -37193,7 +37855,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
37193
37855
 
37194
37856
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
37195
37857
  import { readFileSync as readFileSync18 } from "fs";
37196
- import { join as join28 } from "path";
37858
+ import { join as join29 } from "path";
37197
37859
 
37198
37860
  // ../../packages/plugin-runtime/src/attached/status.ts
37199
37861
  var REFUSAL_LINES = {
@@ -37214,6 +37876,14 @@ import { spawn as spawn2 } from "child_process";
37214
37876
  import { fileURLToPath as fileURLToPath3 } from "url";
37215
37877
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
37216
37878
 
37879
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
37880
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
37881
+
37882
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
37883
+ import { spawn as spawn3 } from "child_process";
37884
+ import { fileURLToPath as fileURLToPath4 } from "url";
37885
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
37886
+
37217
37887
  // ../../packages/plugin-runtime/src/attached/factory.ts
37218
37888
  import { hostname as hostname6 } from "os";
37219
37889
 
@@ -37665,9 +38335,9 @@ var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
37665
38335
 
37666
38336
  // src/command-registry.ts
37667
38337
  import { readdirSync as readdirSync5 } from "fs";
37668
- import { fileURLToPath as fileURLToPath4 } from "url";
38338
+ import { fileURLToPath as fileURLToPath5 } from "url";
37669
38339
  var COMMAND_NAMESPACE = "aka";
37670
- var COMMANDS_DIR = fileURLToPath4(new URL("../commands", import.meta.url));
38340
+ var COMMANDS_DIR = fileURLToPath5(new URL("../commands", import.meta.url));
37671
38341
  function readRegisteredCommands() {
37672
38342
  return readdirSync5(COMMANDS_DIR).filter((f) => f.endsWith(".md")).map((f) => `/${COMMAND_NAMESPACE}:${f.replace(/\.md$/, "")}`);
37673
38343
  }
@@ -37777,7 +38447,7 @@ function show(body) {
37777
38447
 
37778
38448
  // ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
37779
38449
  import { writeFileSync as writeFileSync8 } from "fs";
37780
- import { join as join29 } from "path";
38450
+ import { join as join30 } from "path";
37781
38451
 
37782
38452
  // ../../packages/setup-wizard/src/triage/merge.ts
37783
38453
  var RANK = Object.fromEntries(
@@ -37787,7 +38457,7 @@ var RANK = Object.fromEntries(
37787
38457
  // ../../packages/setup-wizard/src/triage/plan-file.ts
37788
38458
  import { mkdtempSync, readFileSync as readFileSync19, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
37789
38459
  import { tmpdir } from "os";
37790
- import { basename as basename6, dirname as dirname6, join as join30 } from "path";
38460
+ import { basename as basename6, dirname as dirname6, join as join31 } from "path";
37791
38461
  var SuppressionEntrySchema = external_exports.object({
37792
38462
  ruleId: external_exports.string(),
37793
38463
  category: DetectionCategory,