@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 SLASH = "/";
53
+ var SLASH2 = "/";
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(SLASH).filter(Boolean);
425
+ const slices = path.split(SLASH2).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH) + SLASH,
429
+ slices.join(SLASH2) + SLASH2,
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(SLASH).filter(Boolean);
445
+ slices = path.split(SLASH2).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(SLASH) + SLASH,
452
+ slices.join(SLASH2) + SLASH2,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -492,9 +492,9 @@ var require_ignore = __commonJS({
492
492
  });
493
493
 
494
494
  // src/apply-suppressions.ts
495
- import { existsSync as existsSync12, readFileSync as readFileSync16 } from "fs";
495
+ import { existsSync as existsSync12, readFileSync as readFileSync18 } from "fs";
496
496
  import { userInfo } from "os";
497
- import { dirname as dirname8, join as join26 } from "path";
497
+ import { dirname as dirname8, join as join28 } from "path";
498
498
  import { fileURLToPath as fileURLToPath4 } from "url";
499
499
 
500
500
  // ../../packages/persistence/src/attached-derived.ts
@@ -506,6 +506,14 @@ var POLICY_CACHE_FILENAME = "policy-cache.json";
506
506
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
507
507
  import { join as join2 } from "path";
508
508
 
509
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
510
+ var DEFERRED_MIGRATION_TAGS = [
511
+ "0031_audit_capture_by_time_index",
512
+ "0032_audit_capture_by_id_index",
513
+ "0033_audit_capture_location_index",
514
+ "0034_findings_read_indexes"
515
+ ];
516
+
509
517
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
510
518
  var SQLITE_MIGRATIONS = [
511
519
  {
@@ -623,6 +631,30 @@ var SQLITE_MIGRATIONS = [
623
631
  {
624
632
  tag: "0028_activity_session_probe_indexes",
625
633
  sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"
634
+ },
635
+ {
636
+ tag: "0029_audit_capture_rollup_index",
637
+ sql: "CREATE INDEX `idx_audit_capture_rollup` ON `audit_events` (`event_type`,`started_at`,`repo`,`id`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
638
+ },
639
+ {
640
+ tag: "0030_audit_content_expiry",
641
+ sql: "ALTER TABLE `audit_events` ADD `content_expired_at` integer;--> statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"
642
+ },
643
+ {
644
+ tag: "0031_audit_capture_by_time_index",
645
+ sql: "CREATE INDEX `idx_audit_capture_by_time` ON `audit_events` (`started_at`,`id`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
646
+ },
647
+ {
648
+ tag: "0032_audit_capture_by_id_index",
649
+ sql: "CREATE INDEX `idx_audit_capture_by_id` ON `audit_events` (`id`,`started_at`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
650
+ },
651
+ {
652
+ tag: "0033_audit_capture_location_index",
653
+ sql: "CREATE INDEX `idx_audit_capture_location` ON `audit_events` (`repo`,`file_path`,`started_at`,`id`,`event_type`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
654
+ },
655
+ {
656
+ tag: "0034_findings_read_indexes",
657
+ sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
626
658
  }
627
659
  ];
628
660
 
@@ -20670,6 +20702,15 @@ var FindingCategory = external_exports.enum([
20670
20702
  ]).meta({ id: "FindingCategory" });
20671
20703
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20672
20704
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20705
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20706
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20707
+ var FindingDelivery = external_exports.object({
20708
+ state: FindingDeliveryState,
20709
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20710
+ at: external_exports.iso.datetime().optional(),
20711
+ // Only on `not_sent`, and only when a known reason was recorded.
20712
+ reason: SyncFailureReason.optional()
20713
+ }).meta({ id: "FindingDelivery" });
20673
20714
  var ResolutionMethod = external_exports.enum([
20674
20715
  "enforced-in-flight",
20675
20716
  "fixed-at-source",
@@ -20726,7 +20767,10 @@ var FindingInstance = external_exports.object({
20726
20767
  // The session that event belongs to, when it has one — the seam a
20727
20768
  // per-instance "view session" link needs. Absent for events captured
20728
20769
  // outside a session.
20729
- sessionId: external_exports.string().optional()
20770
+ sessionId: external_exports.string().optional(),
20771
+ // The delivery state of the event above (see FindingDelivery). Optional so
20772
+ // readers that do not project it stay valid.
20773
+ delivery: FindingDelivery.optional()
20730
20774
  }).meta({ id: "FindingInstance" });
20731
20775
  var FindingGroup = external_exports.object({
20732
20776
  id: external_exports.string(),
@@ -20778,7 +20822,10 @@ var FindingFacets = external_exports.object({
20778
20822
  // Host tool (attributes.tool_name). Present only on the instance-level
20779
20823
  // reads, which can filter by it; the type-level read omits the dimension
20780
20824
  // because a group spans tools.
20781
- tool: external_exports.array(FindingFacetItem).optional()
20825
+ tool: external_exports.array(FindingFacetItem).optional(),
20826
+ // Delivery states (FindingDeliveryState). Present only on the
20827
+ // instance-level reads, like `tool`.
20828
+ deployment: external_exports.array(FindingFacetItem).optional()
20782
20829
  }).meta({ id: "FindingFacets" });
20783
20830
  var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20784
20831
  id: "FindingTypeSummary"
@@ -20889,6 +20936,8 @@ var ListFindingInstancesQuery = external_exports.object({
20889
20936
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20890
20937
  // where the free-text `q` can only match the rendered "via Bash" label.
20891
20938
  tool: external_exports.array(external_exports.string()).optional(),
20939
+ // The delivery state of each finding's event (see FindingDelivery).
20940
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20892
20941
  // Exact repository / file-path matches, for the drill-down out of the
20893
20942
  // locations view. A row whose event carries no repo/file matches neither.
20894
20943
  repo: external_exports.string().optional(),
@@ -20909,6 +20958,10 @@ var ListFindingInstancesResponse = external_exports.object({
20909
20958
  items: external_exports.array(FindingInstanceDetail),
20910
20959
  nextCursor: external_exports.string().nullable()
20911
20960
  }).meta({ id: "ListFindingInstancesResponse" });
20961
+ var ListFindingInstancesPage = external_exports.object({
20962
+ items: external_exports.array(FindingInstanceDetail),
20963
+ nextCursor: external_exports.string().nullable()
20964
+ }).meta({ id: "ListFindingInstancesPage" });
20912
20965
  var FindingLocationSummary = external_exports.object({
20913
20966
  // Opaque, stable, minted from the pair by encodeLocationId. It exists
20914
20967
  // because a location's identity is two values and a URL param carries one:
@@ -20951,6 +21004,8 @@ var ListFindingLocationsQuery = external_exports.object({
20951
21004
  // instances that match, and folds its status from those.
20952
21005
  status: external_exports.array(FindingStatus).optional(),
20953
21006
  tool: external_exports.array(external_exports.string()).optional(),
21007
+ // The delivery state of each finding's event (see FindingDelivery).
21008
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20954
21009
  q: external_exports.string().optional(),
20955
21010
  sessionId: external_exports.string().optional(),
20956
21011
  from: external_exports.iso.datetime().optional(),
@@ -21153,6 +21208,10 @@ var CaptureAttributes = external_exports.object({
21153
21208
  // to 'allow' — the enforcement audit trail's link back to the grant that
21154
21209
  // authorized the bypass.
21155
21210
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21211
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21212
+ // join back to the `llm_call` leaf for the same assistant turn.
21213
+ message_id: external_exports.string().optional(),
21214
+ conversation_id: external_exports.string().optional(),
21156
21215
  // Whole milliseconds this capture's inspection blocked its caller — the
21157
21216
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21158
21217
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21161,7 +21220,19 @@ var CaptureAttributes = external_exports.object({
21161
21220
  // inline json_extract and is not itself an optimization.
21162
21221
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21163
21222
  // before the measurement shipped — never present as a placeholder 0.
21164
- inspection_ms: external_exports.number().int().nonnegative().optional()
21223
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21224
+ // What a `redact` this capture could not carry out became instead (see
21225
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21226
+ // degrade actually happened, so absence is the ordinary case rather than a
21227
+ // reader having to distinguish it from a zero.
21228
+ //
21229
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21230
+ // so on a multi-finding row this does not say which finding degraded, and
21231
+ // its presence does not mean the fallback decided the capture's action. A
21232
+ // capture denied by another finding's own Block policy carries `block`
21233
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21234
+ // repeated rather than referenced because a store reader opens this file.
21235
+ redact_degraded_to: ActionTaken.optional()
21165
21236
  }).catchall(external_exports.unknown());
21166
21237
  var ToolCallInspection = external_exports.object({
21167
21238
  ruleId: external_exports.string().min(1),
@@ -21360,7 +21431,17 @@ var AuditEvent = external_exports.object({
21360
21431
  /** `share` to a first-party/internal destination. */
21361
21432
  internal: external_exports.boolean(),
21362
21433
  /** Event needs review (e.g. unverified egress). */
21363
- flagged: external_exports.boolean()
21434
+ flagged: external_exports.boolean(),
21435
+ /**
21436
+ * The body this event's `title` is drawn from was cleared by local body
21437
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21438
+ *
21439
+ * A separate flag rather than a sentinel written into `title`: the title is
21440
+ * rendered text, and a store-layer module that invented display copy for it
21441
+ * would be choosing words the view is supposed to choose. Additive and
21442
+ * defaulted, so an older producer still validates.
21443
+ */
21444
+ bodyExpired: external_exports.boolean().default(false)
21364
21445
  }).meta({ id: "ActivityAuditEvent" });
21365
21446
  var ActivitySessionSummary = external_exports.object({
21366
21447
  id: external_exports.string(),
@@ -22700,6 +22781,12 @@ var EventMetadata = external_exports.object({
22700
22781
  // to 'allow' — the enforcement audit trail's link back to the grant that
22701
22782
  // authorized the bypass. Absent on captures where no exception applied.
22702
22783
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22784
+ // The assistant message this capture belongs to, and the conversation it sits
22785
+ // in — set by the browser extension's network capture so a stored `response`
22786
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22787
+ // on every other capture path, which has no such id.
22788
+ messageId: external_exports.string().optional(),
22789
+ conversationId: external_exports.string().optional(),
22703
22790
  // How long THIS capture's inspection blocked its caller, in whole
22704
22791
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22705
22792
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22712,7 +22799,37 @@ var EventMetadata = external_exports.object({
22712
22799
  // Absent is also what every pre-measurement client writes, and what a
22713
22800
  // clock failure degrades to — a reader must treat absence as "not measured"
22714
22801
  // and never as a zero, which would read as "inspection is free".
22715
- inspectionMs: external_exports.number().int().nonnegative().optional()
22802
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22803
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22804
+ // workspace's `redactFallback`, applied because the field could not be
22805
+ // masked in place (a shell command, a URL, or any argument on a host whose
22806
+ // hook contract offers no rewrite channel).
22807
+ //
22808
+ // It exists because the action alone cannot say why. A finding recorded as
22809
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22810
+ // assigned Redact on a field that could not take one — and those are
22811
+ // different facts about the same row: the first is a policy the user chose,
22812
+ // the second is a masking the host could not perform. Absent means no
22813
+ // degrade happened, which is every ordinary capture.
22814
+ //
22815
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22816
+ // is the CAPTURE while `actionTaken` is per FINDING:
22817
+ //
22818
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22819
+ // `redact` alongside a finding ASSIGNED the same action stores both
22820
+ // identically and one reason for the pair; attributing it to both
22821
+ // describes the assigned one wrongly, and to neither loses the degrade.
22822
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22823
+ // became, not the reason the capture ended as it did — a capture denied
22824
+ // by some other finding's own Block policy still carries `block` here,
22825
+ // and clearing the workspace's fallback would not have let it through.
22826
+ // Gate on the value against what a fallback can produce; never read the
22827
+ // field's presence as "this was the fallback's doing".
22828
+ //
22829
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22830
+ // Closing either means moving the reason onto the finding row, which
22831
+ // already carries its own action.
22832
+ redactDegradedTo: ActionTaken.optional()
22716
22833
  }).meta({ id: "EventMetadata" });
22717
22834
  var Event = external_exports.object({
22718
22835
  id: external_exports.guid(),
@@ -22822,7 +22939,32 @@ var RotateKeyInput = external_exports.object({
22822
22939
  confirmation: external_exports.string()
22823
22940
  });
22824
22941
 
22942
+ // ../../packages/schema/src/zod/finding-delivery.ts
22943
+ var KNOWN_REASONS = SyncFailureReason.options;
22944
+ function knownReason(value) {
22945
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
22946
+ }
22947
+ function deriveFindingDelivery(row) {
22948
+ if (row.kind === "code_change") return { state: "local_scan" };
22949
+ if (row.syncedAt !== null && row.syncedAt > 0) {
22950
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
22951
+ }
22952
+ if (row.syncedAt !== null) {
22953
+ const reason = knownReason(row.syncFailure);
22954
+ return {
22955
+ state: "not_sent",
22956
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
22957
+ ...reason === void 0 ? {} : { reason }
22958
+ };
22959
+ }
22960
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
22961
+ return { state: "never_offered" };
22962
+ }
22963
+
22825
22964
  // ../../packages/schema/src/zod/findings-group-build.ts
22965
+ function lookupOwn(map2, key) {
22966
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
22967
+ }
22826
22968
  function toApiAction(dbVal) {
22827
22969
  const map2 = {
22828
22970
  log: "monitored",
@@ -22831,7 +22973,7 @@ function toApiAction(dbVal) {
22831
22973
  warn: "warned",
22832
22974
  allow: "allowed"
22833
22975
  };
22834
- return map2[dbVal] ?? "allowed";
22976
+ return lookupOwn(map2, dbVal) ?? "allowed";
22835
22977
  }
22836
22978
  function toApiCategory(dbVal) {
22837
22979
  if (dbVal === "code_context") return "source_code";
@@ -22839,13 +22981,18 @@ function toApiCategory(dbVal) {
22839
22981
  return parsed.success ? parsed.data : "custom";
22840
22982
  }
22841
22983
  function toApiProvider(sourceTool) {
22842
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
22984
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22843
22985
  }
22844
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
22986
+ var FINDING_STATUS_PRECEDENCE = [
22987
+ "open",
22988
+ "handled",
22989
+ "dismissed",
22990
+ "resolved"
22991
+ ];
22845
22992
  function foldGroupStatus(instanceStatuses) {
22846
22993
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22847
22994
  if (statuses.size === 0) return void 0;
22848
- for (const candidate of STATUS_PRECEDENCE) {
22995
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22849
22996
  if (statuses.has(candidate)) return candidate;
22850
22997
  }
22851
22998
  return void 0;
@@ -22952,11 +23099,16 @@ function applyFindingFilters(types, opts) {
22952
23099
  }
22953
23100
  return filtered;
22954
23101
  }
22955
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22956
- var SEVERITY_RANK = SEVERITY_ORDER;
23102
+ function rankByOrder(members2) {
23103
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23104
+ }
23105
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23106
+ function severityRank(severity) {
23107
+ return lookupOwn(SEVERITY_RANK, severity);
23108
+ }
22957
23109
  function compareFindingGroupOrder(a, b) {
22958
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22959
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23110
+ const rankA = severityRank(a.severity) ?? -1;
23111
+ const rankB = severityRank(b.severity) ?? -1;
22960
23112
  const severityDiff = rankA - rankB;
22961
23113
  if (severityDiff !== 0) return severityDiff;
22962
23114
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
@@ -23031,6 +23183,20 @@ function computeFindingFacets(allTypes, opts) {
23031
23183
  }
23032
23184
 
23033
23185
  // ../../packages/schema/src/zod/findings-flat-build.ts
23186
+ function compareCodePoints(a, b) {
23187
+ const aIter = a[Symbol.iterator]();
23188
+ const bIter = b[Symbol.iterator]();
23189
+ for (; ; ) {
23190
+ const aNext = aIter.next();
23191
+ const bNext = bIter.next();
23192
+ if (aNext.done && bNext.done) return 0;
23193
+ if (aNext.done) return -1;
23194
+ if (bNext.done) return 1;
23195
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23196
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23197
+ if (aPoint !== bPoint) return aPoint - bPoint;
23198
+ }
23199
+ }
23034
23200
  function rowHaystack(row) {
23035
23201
  return [
23036
23202
  row.ruleId,
@@ -23055,6 +23221,8 @@ function matchesDimension(row, opts, dimension) {
23055
23221
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23056
23222
  case "statuses":
23057
23223
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23224
+ case "deliveries":
23225
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23058
23226
  case "tools":
23059
23227
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23060
23228
  // An EMPTY value is a real filter here, not an absent one. The location
@@ -23081,6 +23249,7 @@ var DIMENSIONS = [
23081
23249
  "providers",
23082
23250
  "actions",
23083
23251
  "statuses",
23252
+ "deliveries",
23084
23253
  "tools",
23085
23254
  "repo",
23086
23255
  "file",
@@ -23094,10 +23263,19 @@ function matchesInstanceFilters(row, opts, except) {
23094
23263
  return true;
23095
23264
  }
23096
23265
  function toItems(counts) {
23097
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23266
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23267
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23268
+ // NFD spelling of the same text) as equal, so a count tie between
23269
+ // them would otherwise be ordered by whichever the Map iteration
23270
+ // produced. compareCodePoints breaks that tie deterministically, which
23271
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23272
+ // which it need not: foldFacetTuples runs this same sort over grouped
23273
+ // tuples, so both paths order facets identically by construction.
23274
+ compareCodePoints(a.value, b.value)
23275
+ );
23098
23276
  }
23099
- function bump(counts, value) {
23100
- counts.set(value, (counts.get(value) ?? 0) + 1);
23277
+ function bump(counts, value, by = 1) {
23278
+ counts.set(value, (counts.get(value) ?? 0) + by);
23101
23279
  }
23102
23280
  function createInstanceFacetAccumulator(opts) {
23103
23281
  const severity = /* @__PURE__ */ new Map();
@@ -23106,6 +23284,7 @@ function createInstanceFacetAccumulator(opts) {
23106
23284
  const action = /* @__PURE__ */ new Map();
23107
23285
  const status = /* @__PURE__ */ new Map();
23108
23286
  const tool = /* @__PURE__ */ new Map();
23287
+ const deployment = /* @__PURE__ */ new Map();
23109
23288
  return {
23110
23289
  add(row) {
23111
23290
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23120,6 +23299,9 @@ function createInstanceFacetAccumulator(opts) {
23120
23299
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23121
23300
  bump(tool, row.toolName);
23122
23301
  }
23302
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23303
+ bump(deployment, row.delivery.state);
23304
+ }
23123
23305
  },
23124
23306
  facets: () => ({
23125
23307
  severity: toItems(severity),
@@ -23127,7 +23309,8 @@ function createInstanceFacetAccumulator(opts) {
23127
23309
  provider: toItems(provider),
23128
23310
  action: toItems(action),
23129
23311
  status: toItems(status),
23130
- tool: toItems(tool)
23312
+ tool: toItems(tool),
23313
+ deployment: toItems(deployment)
23131
23314
  })
23132
23315
  };
23133
23316
  }
@@ -23141,6 +23324,7 @@ function toInstanceDetail(row) {
23141
23324
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23142
23325
  eventId: row.eventId,
23143
23326
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23327
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23144
23328
  ...row.user === void 0 ? {} : { user: row.user },
23145
23329
  action: toApiAction(row.actionTaken),
23146
23330
  detectedAt: row.occurredAt,
@@ -23155,12 +23339,6 @@ function toInstanceDetail(row) {
23155
23339
  policy: { id: `category:${category}`, name: category }
23156
23340
  };
23157
23341
  }
23158
- var SEVERITY_ORDER2 = {
23159
- critical: 0,
23160
- high: 1,
23161
- medium: 2,
23162
- low: 3
23163
- };
23164
23342
  function newLocationAccumulator() {
23165
23343
  return {
23166
23344
  instanceCount: 0,
@@ -23175,7 +23353,7 @@ function newLocationAccumulator() {
23175
23353
  }
23176
23354
  function addToLocation(acc, row) {
23177
23355
  acc.instanceCount += 1;
23178
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23356
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23179
23357
  if (rank < acc.maxSeverityRank) {
23180
23358
  acc.maxSeverityRank = rank;
23181
23359
  acc.maxSeverity = row.severity;
@@ -23185,15 +23363,15 @@ function addToLocation(acc, row) {
23185
23363
  acc.ruleIds.add(row.ruleId);
23186
23364
  }
23187
23365
  function compareLocationOrder(a, b) {
23188
- const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23189
- const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23366
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23367
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23190
23368
  if (rankA !== rankB) return rankA - rankB;
23191
23369
  if (a.latestDetectedAt !== b.latestDetectedAt) {
23192
23370
  return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23193
23371
  }
23194
- if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23195
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23196
- return 0;
23372
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23373
+ if (repoDiff !== 0) return repoDiff;
23374
+ return compareCodePoints(a.file, b.file);
23197
23375
  }
23198
23376
  function encodeLocationId(repo, file2) {
23199
23377
  return `${encodePart(repo)}/${encodePart(file2)}`;
@@ -23268,6 +23446,11 @@ var Policy = external_exports.object({
23268
23446
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23269
23447
  provenance: PolicyProvenance.optional()
23270
23448
  }).meta({ id: "Policy" });
23449
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23450
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23451
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23452
+ id: "RedactFallback"
23453
+ });
23271
23454
  var PolicyBundle = external_exports.object({
23272
23455
  version: external_exports.string(),
23273
23456
  policies: external_exports.array(Policy),
@@ -23315,6 +23498,16 @@ var PolicyBundle = external_exports.object({
23315
23498
  // control plane), so no name resolution stands between the decision and the
23316
23499
  // comparison.
23317
23500
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23501
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23502
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23503
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23504
+ // a control plane can tighten a machine and never loosen one — the same
23505
+ // direction `mergeRaiseOnly` enforces for policies.
23506
+ //
23507
+ // Optional so an older backend, and an older on-disk cache, still parses;
23508
+ // absent leaves the device's own setting in force, which is the behaviour
23509
+ // that predates the field and the safe direction to default.
23510
+ redactFallback: RedactFallback.optional(),
23318
23511
  customKeywords: external_exports.array(external_exports.string()),
23319
23512
  fetchedAt: external_exports.iso.datetime()
23320
23513
  }).meta({ id: "PolicyBundle" });
@@ -23349,11 +23542,6 @@ function severityFloorPosture() {
23349
23542
  for (const c of DetectionCategory.options) out[c] = severityFloorPolicy(c);
23350
23543
  return out;
23351
23544
  }
23352
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23353
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23354
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23355
- id: "RedactFallback"
23356
- });
23357
23545
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23358
23546
  var BUILTIN_POLICY_SPECS = {
23359
23547
  monitor: {
@@ -23649,7 +23837,7 @@ var VaultConsent = external_exports.object({
23649
23837
  });
23650
23838
 
23651
23839
  // ../../packages/schema/src/zod/local.ts
23652
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23840
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23653
23841
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23654
23842
  var RunMode = external_exports.enum(["standalone", "attached"]);
23655
23843
  var ControlPlaneConnection = external_exports.object({
@@ -23672,6 +23860,15 @@ var HistorySyncConsent = external_exports.object({
23672
23860
  payloadVersion: external_exports.number().int().positive(),
23673
23861
  endpoint: external_exports.string()
23674
23862
  });
23863
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23864
+ var BodyRetention = external_exports.object({
23865
+ enabled: external_exports.boolean().default(false),
23866
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23867
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23868
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23869
+ // candidate set that is already bounded by "delivered, or never owed".
23870
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23871
+ }).meta({ id: "BodyRetention" });
23675
23872
  var WorkspaceSettings = external_exports.object({
23676
23873
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23677
23874
  runMode: RunMode.default("standalone"),
@@ -23720,7 +23917,13 @@ var WorkspaceSettings = external_exports.object({
23720
23917
  // carry prompt/reply/tool-output text in `content`; the key name predates
23721
23918
  // both widenings. Absent until granted, and a grant for a different endpoint
23722
23919
  // or an older payload no longer counts.
23723
- historySyncConsent: HistorySyncConsent.optional()
23920
+ historySyncConsent: HistorySyncConsent.optional(),
23921
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23922
+ // body never removes the row or its findings.
23923
+ bodyRetention: BodyRetention.default({
23924
+ enabled: false,
23925
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23926
+ })
23724
23927
  });
23725
23928
  function defaultWorkspaceSettings() {
23726
23929
  return WorkspaceSettings.parse({});
@@ -23815,12 +24018,15 @@ function toCaptureAttributes(event) {
23815
24018
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23816
24019
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23817
24020
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24021
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23818
24022
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23819
24023
  // has ever populated either), but every legacy metadata key still rides
23820
24024
  // the bag rather than being silently dropped — CaptureAttributes'
23821
24025
  // `.catchall(z.unknown())` carries the long tail.
23822
24026
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23823
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24027
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24028
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24029
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23824
24030
  };
23825
24031
  }
23826
24032
  function captureDefinitionVersion(finding) {
@@ -23848,13 +24054,22 @@ var ManagedSettingKey = external_exports.enum([
23848
24054
  "vaultInlineReveal",
23849
24055
  "modelJudgeConsent",
23850
24056
  "dataSharesInPlace",
23851
- "redactFallback"
24057
+ "redactFallback",
24058
+ // Pins the toggle and the day count together — see BodyRetention on why the
24059
+ // two are one unit. An administrator mandating a window wants the count
24060
+ // enforced with it, not one a user can widen while the toggle stays on.
24061
+ "bodyRetention"
23852
24062
  ]).meta({ id: "ManagedSettingKey" });
23853
24063
  function isManagedSettingKey(value) {
23854
24064
  return ManagedSettingKey.safeParse(value).success;
23855
24065
  }
23856
24066
  var ManagedSettingsValues = external_exports.object({
23857
24067
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24068
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24069
+ // plain, non-strict objects: a key under either that this build does not know
24070
+ // is stripped and nothing reports it. The unknown-value split in
24071
+ // ManagedSettings below classifies top-level names only, so it stops at
24072
+ // these boundaries.
23858
24073
  controlPlane: external_exports.object({
23859
24074
  endpoint: external_exports.string().min(1),
23860
24075
  label: external_exports.string().min(1).optional()
@@ -23865,7 +24080,8 @@ var ManagedSettingsValues = external_exports.object({
23865
24080
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23866
24081
  modelJudgeConsent: external_exports.boolean().optional(),
23867
24082
  dataSharesInPlace: external_exports.boolean().optional(),
23868
- redactFallback: RedactFallback.optional()
24083
+ redactFallback: RedactFallback.optional(),
24084
+ bodyRetention: BodyRetention.optional()
23869
24085
  }).meta({ id: "ManagedSettingsValues" });
23870
24086
  var ManagedSettings = external_exports.object({
23871
24087
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23873,7 +24089,21 @@ var ManagedSettings = external_exports.object({
23873
24089
  // decision from a bug. Absent renders as a generic "your organization".
23874
24090
  organization: external_exports.string().min(1).optional(),
23875
24091
  // What the administrator pinned.
23876
- values: ManagedSettingsValues.default({}),
24092
+ //
24093
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24094
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24095
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24096
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24097
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24098
+ // exactly the file an administrator is most likely to write while a fleet
24099
+ // is mid-upgrade.
24100
+ //
24101
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24102
+ // file, which is the outcome the lock half already rejected — an older
24103
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24104
+ // value still fails, because the nested schema is re-run over the known
24105
+ // subset and its issues are re-raised on this parse.
24106
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23877
24107
  // Which of those the user may not change. A key here with no matching value
23878
24108
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23879
24109
  // the user may still override. The two are separable on purpose.
@@ -23886,17 +24116,31 @@ var ManagedSettings = external_exports.object({
23886
24116
  // the fleets most likely to carry a version skew. A name outside the enum
23887
24117
  // is still never HONOURED: the lockable set stays explicit above.
23888
24118
  lockedFields: external_exports.array(external_exports.string()).default([])
23889
- }).transform(({ lockedFields, ...rest }) => {
24119
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
23890
24120
  const known = [];
23891
24121
  const unknown2 = [];
23892
24122
  for (const name of lockedFields) {
23893
24123
  if (isManagedSettingKey(name)) known.push(name);
23894
24124
  else unknown2.push(name);
23895
24125
  }
24126
+ const knownValues = /* @__PURE__ */ Object.create(null);
24127
+ const unknownValues = [];
24128
+ for (const [name, value] of Object.entries(values)) {
24129
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24130
+ else unknownValues.push(name);
24131
+ }
24132
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24133
+ if (!pinned.success) {
24134
+ for (const issue2 of pinned.error.issues)
24135
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24136
+ return external_exports.NEVER;
24137
+ }
23896
24138
  return {
23897
24139
  ...rest,
24140
+ values: pinned.data,
23898
24141
  lockedFields: known,
23899
- ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
24142
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24143
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
23900
24144
  };
23901
24145
  }).meta({ id: "ManagedSettings" });
23902
24146
 
@@ -24160,7 +24404,23 @@ var SaveSettingsInput = external_exports.object({
24160
24404
  modelJudgeConsent: ModelJudgeConsentChoice,
24161
24405
  historySyncConsent: HistorySyncConsentChoice,
24162
24406
  vaultConsent: external_exports.string(),
24163
- vaultInlineReveal: external_exports.string()
24407
+ vaultInlineReveal: external_exports.string(),
24408
+ // Widened to `string` like its neighbours rather than typed as
24409
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24410
+ // the call site, so the domain check receives the type it was written for.
24411
+ //
24412
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24413
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24414
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24415
+ // trade against. The real cost runs the other way and is the part worth
24416
+ // knowing: a value this schema admits and the domain enum then rejects lands
24417
+ // on the action's shared refusal, which names NO field, where a shape
24418
+ // rejection reaches `malformedInput` and names the schema key.
24419
+ redactFallback: external_exports.string(),
24420
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24421
+ // `BodyRetention`'s and the action checks it there, so there is one place
24422
+ // that decides what a legal horizon is rather than two that can drift.
24423
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24164
24424
  });
24165
24425
  var AttachInput = external_exports.object({
24166
24426
  endpoint: external_exports.string(),
@@ -24332,6 +24592,52 @@ function reviewSeverityRank(reasons) {
24332
24592
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24333
24593
  }
24334
24594
 
24595
+ // ../../packages/schema/src/zod/web-capture.ts
24596
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24597
+ var WebUsage = external_exports.object({
24598
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24599
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24600
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24601
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24602
+ });
24603
+ var WebToolCall = external_exports.object({
24604
+ toolUseId: external_exports.string().min(1),
24605
+ toolName: external_exports.string().min(1),
24606
+ target: external_exports.string().optional(),
24607
+ isError: external_exports.boolean().optional(),
24608
+ inputSize: external_exports.number().int().nonnegative().optional(),
24609
+ outputSize: external_exports.number().int().nonnegative().optional()
24610
+ });
24611
+ var WebExchange = external_exports.object({
24612
+ messageId: external_exports.string().min(1),
24613
+ startedAt: external_exports.iso.datetime(),
24614
+ model: external_exports.string().optional(),
24615
+ usage: WebUsage.optional(),
24616
+ usageSource: WebUsageSource,
24617
+ stopReason: external_exports.string().optional(),
24618
+ conversationId: external_exports.string().optional(),
24619
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24620
+ toolCalls: external_exports.array(WebToolCall).default([]),
24621
+ // Absent when the adapter recovered no text. Capped by the caller at
24622
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24623
+ // short capture is never mistaken for a short reply.
24624
+ responseText: external_exports.string().optional(),
24625
+ truncated: external_exports.boolean().default(false)
24626
+ });
24627
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24628
+ var WebCaptureStatus = external_exports.object({
24629
+ patched: external_exports.boolean(),
24630
+ live: external_exports.boolean(),
24631
+ blind: external_exports.boolean(),
24632
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24633
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24634
+ parseFailures: external_exports.number().int().nonnegative(),
24635
+ unparsedBodies: external_exports.number().int().nonnegative(),
24636
+ // The adapter-declared JSON key paths that were absent from a real payload —
24637
+ // the earliest signal that a site's contract moved.
24638
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24639
+ });
24640
+
24335
24641
  // ../../packages/persistence/src/paths.ts
24336
24642
  import {
24337
24643
  chmodSync,
@@ -24524,6 +24830,22 @@ function discardStore(file2, backup) {
24524
24830
  }
24525
24831
  }
24526
24832
 
24833
+ // ../../packages/persistence/src/internal/sql-functions.ts
24834
+ var utf8 = new TextDecoder();
24835
+ function akaLower(value) {
24836
+ if (value === null) return null;
24837
+ if (typeof value === "string") return value.toLowerCase();
24838
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
24839
+ return utf8.decode(value).toLowerCase();
24840
+ }
24841
+ function registerSqlFunctions(db) {
24842
+ db.function(
24843
+ "aka_lower",
24844
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
24845
+ akaLower
24846
+ );
24847
+ }
24848
+
24527
24849
  // ../../packages/persistence/src/internal/sql-text.ts
24528
24850
  function escapeLikePattern(s) {
24529
24851
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24608,6 +24930,11 @@ function schemaObjectExists(db, kind, name) {
24608
24930
  function indexExists(db, name) {
24609
24931
  return schemaObjectExists(db, "index", name);
24610
24932
  }
24933
+ function indexColumns(db, name) {
24934
+ if (!indexExists(db, name)) return [];
24935
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
24936
+ return columns.map((c) => c.name).filter((c) => c !== null);
24937
+ }
24611
24938
  function columnNames(db, table2, opts) {
24612
24939
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24613
24940
  const columns = db.prepare(`PRAGMA ${pragma}(${table2})`).all();
@@ -24669,178 +24996,820 @@ function mapRowsTolerant(rows, map2) {
24669
24996
  return out;
24670
24997
  }
24671
24998
 
24672
- // ../../packages/persistence/src/migrations.ts
24673
- function describeObject(object2) {
24674
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24675
- }
24676
- function splitStatements(sql) {
24677
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24678
- }
24679
- function createdIndexName(statement) {
24680
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24681
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
24999
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25000
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25001
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25002
+
25003
+ // ../../packages/persistence/src/sync-failure.ts
25004
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25005
+ function syncFailureRejectCondition(column = "sync_failure") {
25006
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25007
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24682
25008
  }
24683
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24684
- function applyMigrations(db, file2) {
24685
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24686
- db.exec(
24687
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24688
- );
24689
- const applied = new Set(
24690
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24691
- );
24692
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24693
- const record2 = db.prepare(
24694
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24695
- );
24696
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24697
- if (applied.has(migration.tag)) continue;
24698
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24699
- const evidence = evidenceObjects(migration.sql);
24700
- const present = evidence.filter((o) => evidenceExists(db, o));
24701
- if (present.length > 0 && present.length < evidence.length) {
24702
- const missing = evidence.filter((o) => !present.includes(o));
24703
- 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.`;
24704
- akaWarn(message);
24705
- throw new Error(`[aka] ${message}`);
24706
- }
24707
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24708
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24709
- const statements = splitStatements(migration.sql);
24710
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24711
- try {
24712
- withTransaction(
24713
- db,
24714
- () => {
24715
- for (const statement of statements) {
24716
- const indexName = createdIndexName(statement);
24717
- if (indexName === void 0) {
24718
- if (alreadyApplied) continue;
24719
- } else if (indexExists(db, indexName)) {
24720
- continue;
24721
- }
24722
- db.exec(statement);
24723
- }
24724
- if (wantsFkOff && !alreadyApplied) {
24725
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24726
- if (violations.length > 0) {
24727
- throw new Error(
24728
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24729
- );
24730
- }
24731
- }
24732
- record2.run(migration.tag, Date.now());
24733
- },
24734
- "IMMEDIATE"
24735
- );
24736
- } finally {
24737
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24738
- }
25009
+
25010
+ // ../../packages/persistence/src/repositories/history-sync.ts
25011
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25012
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25013
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25014
+ var COUNTED_EVENT_TYPES = [
25015
+ ...STRUCTURAL_EVENT_TYPES,
25016
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25017
+ ];
25018
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25019
+ var PARTITION_BUCKETS = `
25020
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25021
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25022
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25023
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25024
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25025
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25026
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25027
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25028
+ -- added later lands in no bucket and fails the sum assertion, instead
25029
+ -- of silently joining this one.
25030
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25031
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25032
+ THEN 1 ELSE 0 END) AS failed,
25033
+ COUNT(*) AS total`;
25034
+ var COUNTED_SCOPE = `
25035
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25036
+ AND (
25037
+ event_type IN (${TYPE_LIST})
25038
+ OR synced_at IS NOT NULL
25039
+ OR outbox_owed = 1
25040
+ )`;
25041
+ var SKIPPED = -1;
25042
+ var ROW_COLUMNS = `id,
25043
+ parent_id AS parentId,
25044
+ root_session_id AS rootSessionId,
25045
+ event_type AS eventType,
25046
+ host_id AS hostId,
25047
+ harness_id AS harnessId,
25048
+ source_project_id AS sourceProjectId,
25049
+ started_at AS startedAt,
25050
+ ended_at AS endedAt,
25051
+ severity,
25052
+ priority,
25053
+ content,
25054
+ content_hash AS contentHash,
25055
+ attributes`;
25056
+ var SqliteHistorySyncRepository = class {
25057
+ constructor(db) {
25058
+ this.db = db;
25059
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25060
+ this.sessionsStmt = db.prepare(
25061
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25062
+ FROM audit_events
25063
+ WHERE synced_at IS NULL
25064
+ AND event_type IN (${TYPE_LIST})
25065
+ AND started_at < :before
25066
+ GROUP BY sessionId
25067
+ ORDER BY earliest
25068
+ LIMIT :limit`
25069
+ );
25070
+ this.rowsStmt = db.prepare(
25071
+ `SELECT ${ROW_COLUMNS}
25072
+ FROM audit_events
25073
+ WHERE synced_at IS NULL
25074
+ AND event_type IN (${TYPE_LIST})
25075
+ AND started_at < :before
25076
+ AND COALESCE(root_session_id, id) = :sessionId
25077
+ ORDER BY (event_type = 'session') DESC, started_at
25078
+ LIMIT :limit`
25079
+ );
25080
+ this.captureRowsStmt = db.prepare(
25081
+ `SELECT ${ROW_COLUMNS}
25082
+ FROM audit_events
25083
+ WHERE synced_at IS NULL
25084
+ AND sync_claimed_at IS NULL
25085
+ AND outbox_owed = 1
25086
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25087
+ AND started_at < :before
25088
+ ORDER BY started_at
25089
+ LIMIT :limit`
25090
+ );
25091
+ this.markOwedStmt = db.prepare(
25092
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25093
+ );
25094
+ this.markCaptureBacklogOwedStmt = db.prepare(
25095
+ `UPDATE audit_events SET outbox_owed = 1
25096
+ WHERE synced_at IS NULL
25097
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25098
+ AND started_at < :before`
25099
+ );
25100
+ this.stampStmt = db.prepare(
25101
+ `UPDATE audit_events
25102
+ SET synced_at = :at,
25103
+ sync_claimed_at = NULL,
25104
+ sync_failed_at = :failedAt,
25105
+ sync_failure = :failure
25106
+ WHERE id = :id`
25107
+ );
25108
+ this.claimRowStmt = db.prepare(
25109
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25110
+ );
25111
+ this.releaseRowStmt = db.prepare(
25112
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25113
+ );
25114
+ this.releaseStaleClaimsStmt = db.prepare(
25115
+ `UPDATE audit_events SET sync_claimed_at = NULL
25116
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25117
+ );
25118
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25119
+ FROM audit_events${COUNTED_SCOPE}`);
25120
+ this.partitionByKindStmt = db.prepare(
25121
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25122
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25123
+ GROUP BY event_type`
25124
+ );
25125
+ this.countsStmt = db.prepare(
25126
+ `SELECT
25127
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25128
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25129
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25130
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25131
+ THEN 1 ELSE 0 END) AS skipped,
25132
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25133
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25134
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25135
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25136
+ FROM audit_events
25137
+ WHERE event_type IN (${TYPE_LIST})`
25138
+ );
25139
+ this.captureSkipCountStmt = db.prepare(
25140
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25141
+ // way the structural totals are. The split exists because a refusal is
25142
+ // terminal only against the deployment that gave it, and the structural
25143
+ // re-arm frees it on a change of deployment. The capture lane has no such
25144
+ // escape: re-arming a capture would offer one deployment's undelivered
25145
+ // prompts, with their text, to a deployment that never saw them, which is
25146
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25147
+ // reasons mean the same thing — this row will not be sent — and splitting
25148
+ // them would put refused captures in a bucket nothing reads and nothing
25149
+ // frees.
25150
+ `SELECT COUNT(*) AS skipped
25151
+ FROM audit_events
25152
+ WHERE synced_at = ${String(SKIPPED)}
25153
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25154
+ );
25155
+ this.fingerprintStmt = db.prepare(
25156
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25157
+ FROM history_sync WHERE id = 1`
25158
+ );
25159
+ this.setFingerprintStmt = db.prepare(
25160
+ `UPDATE history_sync
25161
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25162
+ WHERE id = 1`
25163
+ );
25164
+ this.disownCapturesStmt = db.prepare(
25165
+ `UPDATE audit_events SET outbox_owed = NULL
25166
+ WHERE outbox_owed IS NOT NULL
25167
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25168
+ AND started_at < :attachedAt`
25169
+ );
25170
+ this.rearmStmt = db.prepare(
25171
+ `UPDATE audit_events
25172
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25173
+ WHERE (synced_at > 0
25174
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25175
+ AND event_type IN (${TYPE_LIST})`
25176
+ );
25177
+ this.claimStmt = db.prepare(
25178
+ `UPDATE history_sync
25179
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25180
+ WHERE id = 1
25181
+ AND (owner_pid IS NULL
25182
+ OR heartbeat_at IS NULL
25183
+ OR heartbeat_at < :staleBefore
25184
+ OR heartbeat_at > :now)`
25185
+ );
25186
+ this.heartbeatStmt = db.prepare(
25187
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25188
+ );
25189
+ this.releaseStmt = db.prepare(
25190
+ `UPDATE history_sync
25191
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25192
+ WHERE id = 1 AND owner_pid = :pid`
25193
+ );
25194
+ this.closeWindowStmt = db.prepare(
25195
+ `UPDATE audit_events
25196
+ SET synced_at = ${String(SKIPPED)},
25197
+ sync_failed_at = :at,
25198
+ sync_failure = 'detached_undelivered'
25199
+ WHERE synced_at IS NULL
25200
+ AND event_type IN (${TYPE_LIST})
25201
+ AND started_at >= :attachedAt`
25202
+ );
25203
+ this.releaseBoundaryStmt = db.prepare(
25204
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25205
+ );
25206
+ this.freezeBoundaryStmt = db.prepare(
25207
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25208
+ );
25209
+ this.leaseStmt = db.prepare(
25210
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25211
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25212
+ FROM history_sync WHERE id = 1`
25213
+ );
25214
+ this.inspectionsStmt = db.prepare(
25215
+ `SELECT d.rule_id AS ruleId,
25216
+ d.name AS ruleName,
25217
+ d.version AS ruleVersion,
25218
+ d.category AS category,
25219
+ d.severity AS severity,
25220
+ f.span_start AS spanStart,
25221
+ f.span_end AS spanEnd,
25222
+ f.masked_match AS maskedMatch,
25223
+ f.action_taken AS actionTaken,
25224
+ f.confidence AS confidence
25225
+ FROM inspection_findings f
25226
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25227
+ WHERE f.audit_event_id = :auditEventId
25228
+ ORDER BY f.span_start, f.id`
25229
+ );
24739
25230
  }
24740
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24741
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25231
+ db;
25232
+ ensureRowStmt;
25233
+ sessionsStmt;
25234
+ rowsStmt;
25235
+ stampStmt;
25236
+ countsStmt;
25237
+ fingerprintStmt;
25238
+ setFingerprintStmt;
25239
+ rearmStmt;
25240
+ claimStmt;
25241
+ heartbeatStmt;
25242
+ releaseStmt;
25243
+ leaseStmt;
25244
+ inspectionsStmt;
25245
+ closeWindowStmt;
25246
+ releaseBoundaryStmt;
25247
+ freezeBoundaryStmt;
25248
+ captureRowsStmt;
25249
+ markOwedStmt;
25250
+ markCaptureBacklogOwedStmt;
25251
+ captureSkipCountStmt;
25252
+ disownCapturesStmt;
25253
+ partitionStmt;
25254
+ partitionByKindStmt;
25255
+ claimRowStmt;
25256
+ releaseRowStmt;
25257
+ releaseStaleClaimsStmt;
25258
+ /**
25259
+ * The masked detections recorded against one tool call.
25260
+ *
25261
+ * These travel with the event because a tool call's target is not
25262
+ * re-inspectable from the event alone — unlike a capture, where the text
25263
+ * itself is re-scannable. What crosses is the masked match and the rule that
25264
+ * produced it, never the value.
25265
+ */
25266
+ inspectionsFor(auditEventId) {
25267
+ return allRows(this.inspectionsStmt, { auditEventId });
24742
25268
  }
24743
- ensureSyncedAtColumn(db, "audit_events");
24744
- ensureScanLedgerTable(db);
24745
- ensureHistorySyncTable(db);
24746
- ensureBlockedDetectionsTable(db);
24747
- ensureRuleProbeCacheTable(db);
24748
- ensureWriteGateTrigger(db);
24749
- ensureTokenUsageColumns(db);
24750
- reconcileSourceProjectIds(db);
24751
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24752
- const drained = runLegacyHistoryBackfill(db);
24753
- if (drained) applyLegacyDropMigration(db, file2);
25269
+ /**
25270
+ * Sessions with structural rows still to send, oldest first.
25271
+ *
25272
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25273
+ * read. Anything recorded after the machine attached is the live forward
25274
+ * path's to deliver; this drain exists for what was recorded before it, and a
25275
+ * row both paths send is at best a duplicate request and at worst — for a
25276
+ * session root — an overwrite of the inventory ids the live path resolved.
25277
+ */
25278
+ pendingSessions(limit, before) {
25279
+ return allRows(this.sessionsStmt, { limit, before }).map(
25280
+ (r) => r.sessionId
25281
+ );
24754
25282
  }
24755
- }
24756
- function readLegacyTables(db) {
24757
- let holdsRows = false;
24758
- const marks = [];
24759
- for (const table2 of ["events", "findings"]) {
24760
- try {
24761
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table2}`).get();
24762
- if (row === void 0) {
24763
- holdsRows = true;
24764
- marks.push(`${table2}:unreadable`);
24765
- continue;
24766
- }
24767
- if (row.n > 0) holdsRows = true;
24768
- marks.push(`${table2}:${String(row.n)}:${String(row.hi)}`);
24769
- } catch {
24770
- holdsRows = true;
24771
- marks.push(`${table2}:unreadable`);
24772
- }
25283
+ /** One session's undelivered structural rows within the backlog, root first. */
25284
+ pendingRows(sessionId, limit, before) {
25285
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24773
25286
  }
24774
- return { holdsRows, mark: marks.join("|") };
24775
- }
24776
- function applyLegacyDropMigration(db, file2) {
24777
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24778
- if (!migration) return;
24779
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24780
- if (file2 !== void 0 && before?.holdsRows === true) {
24781
- try {
24782
- backupBeforeLegacyDrop(db, file2);
24783
- } catch (error61) {
24784
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24785
- return;
24786
- }
25287
+ /**
25288
+ * Captures this machine still owes the deployment, oldest first.
25289
+ *
25290
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25291
+ * by a time window — see captureRowsStmt for why a window could not express
25292
+ * this. `before` is the grace window that leaves a just-recorded capture to
25293
+ * the live path.
25294
+ */
25295
+ pendingCaptureRows(limit, before) {
25296
+ return allRows(this.captureRowsStmt, { limit, before });
24787
25297
  }
24788
- try {
25298
+ /**
25299
+ * Record that a capture is OWED to the deployment.
25300
+ *
25301
+ * Written by the attached forward path when a live send did not confirm
25302
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25303
+ * a fact rather than an inference: the machine was attached, the send did not
25304
+ * land, so the row is owed — which no time window can state, because the same
25305
+ * window that holds the rows a past attachment left owed also holds every
25306
+ * capture recorded while the machine was DETACHED, and those were never
25307
+ * offered to anyone.
25308
+ *
25309
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25310
+ * out of the drain's read.
25311
+ */
25312
+ markCaptureOwed(id) {
25313
+ this.markOwedStmt.run({ id });
25314
+ }
25315
+ /**
25316
+ * Mark every capture already on disk as owed, as of `before`.
25317
+ *
25318
+ * The consent-time backfill, called once from `aka attach` when a human
25319
+ * grants existing-history consent — never from an ongoing drain pass, and
25320
+ * never inferred from a boundary that could later move. `before` is the
25321
+ * caller's own "now" at the moment consent was granted, so what this marks
25322
+ * is exactly the backlog the consent prompt already counted, not whatever a
25323
+ * later re-attach or key rotation might widen it to.
25324
+ *
25325
+ * Returns how many rows matched, for the caller to log or test against. Not a
25326
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25327
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25328
+ */
25329
+ markCaptureBacklogOwed(before) {
25330
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25331
+ }
25332
+ /**
25333
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25334
+ *
25335
+ * CLEARS any failure reason in the same statement. A row that failed against
25336
+ * one deployment and then landed is delivered, and leaving the reason behind
25337
+ * would leave the store holding two contradictory answers about one row —
25338
+ * with the surface free to render either.
25339
+ */
25340
+ markSynced(ids, atMs) {
25341
+ this.stampAll(ids, atMs, null);
25342
+ }
25343
+ /**
25344
+ * Record that THIS MACHINE cannot express the row on the wire.
25345
+ *
25346
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25347
+ * payload, or a body the client itself refused to send. It fails identically
25348
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25349
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25350
+ * is retried; marking those would turn one outage into permanent data loss.
25351
+ */
25352
+ markSkipped(ids, atMs) {
25353
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25354
+ }
25355
+ /**
25356
+ * Record that THIS DEPLOYMENT refused the row.
25357
+ *
25358
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25359
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25360
+ * row is outstanding rather than why. What separates them is the reason, and
25361
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25362
+ * on one body, so it is terminal only for as long as this machine points at
25363
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25364
+ *
25365
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25366
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25367
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25368
+ */
25369
+ markRefused(ids, atMs) {
25370
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25371
+ }
25372
+ eachInTransaction(ids, run) {
25373
+ if (ids.length === 0) return;
24789
25374
  withTransaction(
24790
- db,
25375
+ this.db,
24791
25376
  () => {
24792
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24793
- if (alreadyDropped) return;
24794
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24795
- akaWarn(
24796
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24797
- );
24798
- return;
24799
- }
24800
- for (const statement of splitStatements(migration.sql)) {
24801
- db.exec(statement);
24802
- }
24803
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
24804
- migration.tag,
24805
- Date.now()
24806
- );
25377
+ for (const id of ids) run(id);
24807
25378
  },
24808
25379
  "IMMEDIATE"
24809
25380
  );
24810
- } catch (error61) {
24811
- akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
24812
- }
24813
- }
24814
- function backupBeforeLegacyDrop(db, file2) {
24815
- reapStalePartials(file2);
24816
- const backup = backupPath(file2, "pre-drop");
24817
- snapshotStore(db, backup);
24818
- return backup;
24819
- }
24820
- var TOKEN_USAGE_COLUMNS = [
24821
- {
24822
- name: "input_tokens",
24823
- ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
24824
- },
24825
- {
24826
- name: "output_tokens",
24827
- ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
24828
- },
24829
- {
24830
- name: "cache_creation_input_tokens",
24831
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
24832
- },
24833
- {
24834
- name: "cache_read_input_tokens",
24835
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
24836
- },
24837
- {
24838
- name: "model",
24839
- ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
24840
- },
24841
- {
24842
- name: "provider",
24843
- ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
25381
+ }
25382
+ stampAll(ids, value, failure, failedAtMs) {
25383
+ if (ids.length === 0) return;
25384
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25385
+ withTransaction(
25386
+ this.db,
25387
+ () => {
25388
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25389
+ },
25390
+ "IMMEDIATE"
25391
+ );
25392
+ }
25393
+ /**
25394
+ * Claim rows as in-flight.
25395
+ *
25396
+ * Advisory in exactly the sense the lease is: it records that a send is in
25397
+ * progress so a surface can say so, and a lost claim costs a row showing as
25398
+ * queued while it is actually being sent. It is not exclusion — the far side
25399
+ * settles a duplicate on the row id.
25400
+ */
25401
+ claimRows(ids, atMs) {
25402
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25403
+ }
25404
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25405
+ releaseRows(ids) {
25406
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25407
+ }
25408
+ /**
25409
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25410
+ *
25411
+ * A process killed between claiming and settling leaves rows claimed with
25412
+ * nothing left to settle them. Without this they read as "sending" for ever.
25413
+ */
25414
+ releaseStaleClaims(staleBefore) {
25415
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25416
+ }
25417
+ /**
25418
+ * Every tracked row in exactly one delivery state.
25419
+ *
25420
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25421
+ * pick up now", which is a different question from "what state is this row
25422
+ * in" — and a machine that has never attached has no boundary to pass, so
25423
+ * requiring one would force a caller to invent one and report the whole store
25424
+ * as queued.
25425
+ */
25426
+ /**
25427
+ * The same partition, one row per kind that a lane carries.
25428
+ *
25429
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25430
+ * scope decides which rows exist at all, so a kind that has never been
25431
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25432
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25433
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25434
+ * different things.
25435
+ */
25436
+ partitionByKind() {
25437
+ return allRows(
25438
+ this.partitionByKindStmt,
25439
+ {}
25440
+ ).map((row) => ({
25441
+ kind: row.kind,
25442
+ queued: row.queued ?? 0,
25443
+ inProgress: row.inProgress ?? 0,
25444
+ synced: row.synced ?? 0,
25445
+ failed: row.failed ?? 0,
25446
+ refused: row.refused ?? 0,
25447
+ detached: row.detached ?? 0,
25448
+ total: row.total ?? 0
25449
+ }));
25450
+ }
25451
+ partition() {
25452
+ const row = getRow(this.partitionStmt, {});
25453
+ return {
25454
+ queued: row?.queued ?? 0,
25455
+ inProgress: row?.inProgress ?? 0,
25456
+ synced: row?.synced ?? 0,
25457
+ failed: row?.failed ?? 0,
25458
+ refused: row?.refused ?? 0,
25459
+ detached: row?.detached ?? 0,
25460
+ total: row?.total ?? 0
25461
+ };
25462
+ }
25463
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25464
+ counts(before) {
25465
+ const row = getRow(this.countsStmt, { before });
25466
+ const captures = getRow(this.captureSkipCountStmt);
25467
+ return {
25468
+ pending: row?.pending ?? 0,
25469
+ sent: row?.sent ?? 0,
25470
+ skipped: row?.skipped ?? 0,
25471
+ refused: row?.refused ?? 0,
25472
+ detached: row?.detached ?? 0,
25473
+ capturesSkipped: captures?.skipped ?? 0
25474
+ };
25475
+ }
25476
+ /**
25477
+ * The deployment the current stamps were made against, and where its backlog
25478
+ * ends.
25479
+ *
25480
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25481
+ * machine that has never drained is — and every writer below seeds the row
25482
+ * before it needs one, so nothing depends on this creating it. Keeping the
25483
+ * write off the gate path matters because the gate runs on every pass while a
25484
+ * write has to take the database's write lock.
25485
+ */
25486
+ deployment() {
25487
+ const row = getRow(
25488
+ this.fingerprintStmt
25489
+ );
25490
+ return {
25491
+ fingerprint: row?.fingerprint ?? void 0,
25492
+ backlogBefore: row?.backlogBefore ?? void 0
25493
+ };
25494
+ }
25495
+ /**
25496
+ * Point the ledger at a different deployment, discarding what it recorded
25497
+ * about the previous one.
25498
+ *
25499
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25500
+ * machine has just left are undelivered as far as the new one is concerned.
25501
+ * All four in one transaction, so a crash between them cannot leave stamps
25502
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25503
+ * a disown with no re-mark to follow it.
25504
+ *
25505
+ * The boundary is written HERE and only here, which is what freezes it: a
25506
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25507
+ * unchanged, so this never runs and the backlog does not widen back over rows
25508
+ * the live path has since delivered.
25509
+ *
25510
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25511
+ * granted existing-history consent for the deployment this call is arming —
25512
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25513
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25514
+ * apart. Passed only when that grant is valid, since this method has no way
25515
+ * to check consent itself and must not mark a row owed for a machine that
25516
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25517
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25518
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25519
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25520
+ * on the cleared side of that bound — and the re-mark in the same
25521
+ * transaction is what puts those rows back. A crash between the two cannot
25522
+ * strand the ledger disowned with nothing re-marked — the transaction either
25523
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25524
+ * committed re-enters this method on the very next pass. Omit it (the
25525
+ * structural-only tests do) to exercise the disown in isolation.
25526
+ *
25527
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25528
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25529
+ * live path can mark a capture owed from the moment `aka attach` writes the
25530
+ * descriptor, before the drain's first pass ever reaches this method, and
25531
+ * such a row sits at or after the bound rather than below it. What keeps the
25532
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25533
+ * bound — disown runs first, re-mark second, both inside the one
25534
+ * transaction above.
25535
+ */
25536
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25537
+ this.ensureRowStmt.run();
25538
+ withTransaction(
25539
+ this.db,
25540
+ () => {
25541
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25542
+ this.rearmStmt.run();
25543
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25544
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25545
+ }
25546
+ if (backfillCapturesBefore !== void 0) {
25547
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25548
+ }
25549
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25550
+ },
25551
+ "IMMEDIATE"
25552
+ );
25553
+ }
25554
+ /**
25555
+ * End the attached period: hand its rows to the live path, and release the
25556
+ * boundary so the next attachment can freeze a new one.
25557
+ *
25558
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25559
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25560
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25561
+ * during the detached period, because the machine is not attached. Rows
25562
+ * recorded in that window sit after the boundary and before the re-attach, so
25563
+ * neither path takes them, and the pending count reports none outstanding.
25564
+ *
25565
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25566
+ * closing attachment's to deliver and are no longer outstanding — that is what
25567
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25568
+ * distinction is not academic: this used to write a delivery TIME, which every
25569
+ * read treats as delivery, so one detach turned a window of undelivered rows
25570
+ * into a window of delivered ones and no surface could tell. It writes the
25571
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25572
+ * "received" stop being the same fact.
25573
+ *
25574
+ * A change of deployment still frees them (see the re-arm), because the next
25575
+ * deployment has seen none of this machine's history — so the rows reach it
25576
+ * exactly as they did when this wrote a delivery time.
25577
+ *
25578
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25579
+ * window unstamped — that half-state would re-send the whole attached period
25580
+ * on the next attach, which is the failure the boundary exists to prevent.
25581
+ */
25582
+ closeAttachedWindow(attachedAtMs, atMs) {
25583
+ this.ensureRowStmt.run();
25584
+ withTransaction(
25585
+ this.db,
25586
+ () => {
25587
+ const row = getRow(this.fingerprintStmt);
25588
+ const from = row?.backlogBefore ?? attachedAtMs;
25589
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25590
+ this.releaseBoundaryStmt.run();
25591
+ },
25592
+ "IMMEDIATE"
25593
+ );
25594
+ }
25595
+ /**
25596
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25597
+ *
25598
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25599
+ * different deployment and therefore discards what was delivered to the old
25600
+ * one: here the recipient is the same, so everything already sent to it stays
25601
+ * sent.
25602
+ */
25603
+ freezeBoundary(backlogBefore) {
25604
+ this.ensureRowStmt.run();
25605
+ this.freezeBoundaryStmt.run({ backlogBefore });
25606
+ }
25607
+ /** Take the claim, or report that someone live already holds it. */
25608
+ claim(pid, host, nowMs, staleAfterMs) {
25609
+ this.ensureRowStmt.run();
25610
+ let taken = false;
25611
+ withTransaction(
25612
+ this.db,
25613
+ () => {
25614
+ const result = this.claimStmt.run({
25615
+ pid,
25616
+ host,
25617
+ now: nowMs,
25618
+ staleBefore: nowMs - staleAfterMs
25619
+ });
25620
+ taken = result.changes === 1;
25621
+ },
25622
+ "IMMEDIATE"
25623
+ );
25624
+ return taken;
25625
+ }
25626
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25627
+ heartbeat(pid, nowMs) {
25628
+ this.heartbeatStmt.run({ now: nowMs, pid });
25629
+ }
25630
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25631
+ release(pid) {
25632
+ this.releaseStmt.run({ pid });
25633
+ }
25634
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25635
+ lease() {
25636
+ return getRow(this.leaseStmt);
25637
+ }
25638
+ };
25639
+
25640
+ // ../../packages/persistence/src/migrations.ts
25641
+ function describeObject(object2) {
25642
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25643
+ }
25644
+ function splitStatements(sql) {
25645
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25646
+ }
25647
+ function createdIndexName(statement) {
25648
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25649
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25650
+ }
25651
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25652
+ function applyMigrations(db, file2, options = {}) {
25653
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25654
+ db.exec(
25655
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25656
+ );
25657
+ const applied = new Set(
25658
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25659
+ );
25660
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25661
+ const record2 = db.prepare(
25662
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25663
+ );
25664
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25665
+ if (applied.has(migration.tag)) continue;
25666
+ if (options.skipTags?.has(migration.tag) === true) continue;
25667
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25668
+ const evidence = evidenceObjects(migration.sql);
25669
+ const present = evidence.filter((o) => evidenceExists(db, o));
25670
+ if (present.length > 0 && present.length < evidence.length) {
25671
+ const missing = evidence.filter((o) => !present.includes(o));
25672
+ 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.`;
25673
+ akaWarn(message);
25674
+ throw new Error(`[aka] ${message}`);
25675
+ }
25676
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25677
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25678
+ const statements = splitStatements(migration.sql);
25679
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25680
+ try {
25681
+ withTransaction(
25682
+ db,
25683
+ () => {
25684
+ for (const statement of statements) {
25685
+ const indexName = createdIndexName(statement);
25686
+ if (indexName === void 0) {
25687
+ if (alreadyApplied) continue;
25688
+ } else if (indexExists(db, indexName)) {
25689
+ continue;
25690
+ }
25691
+ db.exec(statement);
25692
+ }
25693
+ if (wantsFkOff && !alreadyApplied) {
25694
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25695
+ if (violations.length > 0) {
25696
+ throw new Error(
25697
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25698
+ );
25699
+ }
25700
+ }
25701
+ record2.run(migration.tag, Date.now());
25702
+ },
25703
+ "IMMEDIATE"
25704
+ );
25705
+ } finally {
25706
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25707
+ }
25708
+ }
25709
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25710
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25711
+ }
25712
+ ensureSyncedAtColumn(db, "audit_events");
25713
+ ensureScanLedgerTable(db);
25714
+ ensureHistorySyncTable(db);
25715
+ ensureBlockedDetectionsTable(db);
25716
+ ensureRuleProbeCacheTable(db);
25717
+ ensureWriteGateTrigger(db);
25718
+ ensureTokenUsageColumns(db);
25719
+ reconcileSourceProjectIds(db);
25720
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25721
+ const drained = runLegacyHistoryBackfill(db);
25722
+ if (drained) applyLegacyDropMigration(db, file2);
25723
+ }
25724
+ }
25725
+ function readLegacyTables(db) {
25726
+ let holdsRows = false;
25727
+ const marks = [];
25728
+ for (const table2 of ["events", "findings"]) {
25729
+ try {
25730
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table2}`).get();
25731
+ if (row === void 0) {
25732
+ holdsRows = true;
25733
+ marks.push(`${table2}:unreadable`);
25734
+ continue;
25735
+ }
25736
+ if (row.n > 0) holdsRows = true;
25737
+ marks.push(`${table2}:${String(row.n)}:${String(row.hi)}`);
25738
+ } catch {
25739
+ holdsRows = true;
25740
+ marks.push(`${table2}:unreadable`);
25741
+ }
25742
+ }
25743
+ return { holdsRows, mark: marks.join("|") };
25744
+ }
25745
+ function applyLegacyDropMigration(db, file2) {
25746
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25747
+ if (!migration) return;
25748
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25749
+ if (file2 !== void 0 && before?.holdsRows === true) {
25750
+ try {
25751
+ backupBeforeLegacyDrop(db, file2);
25752
+ } catch (error61) {
25753
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25754
+ return;
25755
+ }
25756
+ }
25757
+ try {
25758
+ withTransaction(
25759
+ db,
25760
+ () => {
25761
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25762
+ if (alreadyDropped) return;
25763
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25764
+ akaWarn(
25765
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25766
+ );
25767
+ return;
25768
+ }
25769
+ for (const statement of splitStatements(migration.sql)) {
25770
+ db.exec(statement);
25771
+ }
25772
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25773
+ migration.tag,
25774
+ Date.now()
25775
+ );
25776
+ },
25777
+ "IMMEDIATE"
25778
+ );
25779
+ } catch (error61) {
25780
+ akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
25781
+ }
25782
+ }
25783
+ function backupBeforeLegacyDrop(db, file2) {
25784
+ reapStalePartials(file2);
25785
+ const backup = backupPath(file2, "pre-drop");
25786
+ snapshotStore(db, backup);
25787
+ return backup;
25788
+ }
25789
+ var TOKEN_USAGE_COLUMNS = [
25790
+ {
25791
+ name: "input_tokens",
25792
+ ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
25793
+ },
25794
+ {
25795
+ name: "output_tokens",
25796
+ ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
25797
+ },
25798
+ {
25799
+ name: "cache_creation_input_tokens",
25800
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
25801
+ },
25802
+ {
25803
+ name: "cache_read_input_tokens",
25804
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
25805
+ },
25806
+ {
25807
+ name: "model",
25808
+ ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25809
+ },
25810
+ {
25811
+ name: "provider",
25812
+ ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
24844
25813
  }
24845
25814
  ];
24846
25815
  function ensureTokenUsageColumns(db) {
@@ -25101,10 +26070,62 @@ function ensureSyncedAtColumn(db, table2) {
25101
26070
  if (!columns.includes("outbox_owed")) {
25102
26071
  db.exec(`ALTER TABLE ${table2} ADD COLUMN outbox_owed integer`);
25103
26072
  }
26073
+ if (!columns.includes("sync_failed_at")) {
26074
+ db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failed_at integer`);
26075
+ }
26076
+ if (!columns.includes("sync_failure")) {
26077
+ withTransaction(
26078
+ db,
26079
+ () => {
26080
+ db.exec(`ALTER TABLE ${table2} ADD COLUMN sync_failure text`);
26081
+ db.exec(
26082
+ `UPDATE ${table2} SET synced_at = NULL
26083
+ WHERE synced_at = -1
26084
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26085
+ );
26086
+ },
26087
+ "IMMEDIATE"
26088
+ );
26089
+ }
25104
26090
  db.exec(
25105
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25106
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26091
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26092
+ BEFORE UPDATE OF sync_failure ON ${table2}
26093
+ WHEN ${syncFailureRejectCondition()}
26094
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25107
26095
  );
26096
+ const syncIndexColumns = [
26097
+ "event_type",
26098
+ "synced_at",
26099
+ "sync_claimed_at",
26100
+ "started_at",
26101
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26102
+ // has to be in the index for the read to stay covered — but putting it
26103
+ // ahead of `started_at` would reorder the prefix the structural drain's
26104
+ // reads match on.
26105
+ "sync_failure"
26106
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26107
+ //
26108
+ // The delivery-state read tests it — a capture's state depends on whether a
26109
+ // live forward marked it owed — so carrying it here makes that read covering
26110
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26111
+ // But a sixth column changes what the planner charges for this index, and
26112
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26113
+ // then stops choosing the per-session index for the token rollup and walks
26114
+ // every `llm_call` in the store through the event-type index instead. That
26115
+ // read grows with the store; this one does not.
26116
+ //
26117
+ // 40 ms on the largest store measured, once per render, is a cost worth
26118
+ // paying to leave every other read's plan where it was.
26119
+ ];
26120
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26121
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26122
+ if (!syncIndexMatches) {
26123
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26124
+ db.exec(
26125
+ `CREATE INDEX idx_audit_events_sync
26126
+ ON audit_events (${syncIndexColumns.join(", ")})`
26127
+ );
26128
+ }
25108
26129
  db.exec(
25109
26130
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25110
26131
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25326,7 +26347,11 @@ function buildAuditEvent(row) {
25326
26347
  link: linkParsed?.success ? linkParsed.data : null,
25327
26348
  targetId: row.target_id,
25328
26349
  internal: intToBool(row.internal),
25329
- flagged: intToBool(row.flagged)
26350
+ flagged: intToBool(row.flagged),
26351
+ // Only meaningful when the title came out empty — a row whose body was
26352
+ // expired but whose title fell back to `tool_name` still has something to
26353
+ // render, and flagging it would make the view apologise for nothing.
26354
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25330
26355
  };
25331
26356
  }
25332
26357
  var TIMELINE_COLUMNS = `
@@ -25334,6 +26359,7 @@ var TIMELINE_COLUMNS = `
25334
26359
  event_type,
25335
26360
  started_at,
25336
26361
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26362
+ content_expired_at,
25337
26363
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25338
26364
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25339
26365
  json_extract(attributes, '$.severity') AS severity,
@@ -25999,6 +27025,88 @@ var SqliteAuditEventsRepository = class {
25999
27025
  }
26000
27026
  };
26001
27027
 
27028
+ // ../../packages/persistence/src/repositories/body-retention.ts
27029
+ var DEFAULT_BATCH_SIZE = 500;
27030
+ var DEFAULT_MAX_ROWS = 5e4;
27031
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27032
+ var SqliteBodyRetentionRepository = class {
27033
+ constructor(db) {
27034
+ this.db = db;
27035
+ const select = (laneClause) => `
27036
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27037
+ FROM audit_events
27038
+ WHERE content IS NOT NULL
27039
+ AND started_at < :cutoff
27040
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27041
+ ${laneClause}
27042
+ ORDER BY started_at
27043
+ LIMIT :limit`;
27044
+ this.candidatesStmt = this.db.prepare(select(""));
27045
+ this.candidatesSyncSafeStmt = this.db.prepare(
27046
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27047
+ );
27048
+ this.heldBySyncStmt = this.db.prepare(`
27049
+ SELECT COUNT(*) AS n
27050
+ FROM audit_events
27051
+ WHERE content IS NOT NULL
27052
+ AND started_at < :cutoff
27053
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27054
+ AND synced_at IS NULL`);
27055
+ this.expireStmt = this.db.prepare(
27056
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27057
+ );
27058
+ }
27059
+ db;
27060
+ candidatesStmt;
27061
+ candidatesSyncSafeStmt;
27062
+ heldBySyncStmt;
27063
+ expireStmt;
27064
+ /** How many bytes a pass with these options would free, changing nothing. */
27065
+ preview(opts) {
27066
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27067
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27068
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27069
+ return {
27070
+ rowsExpired: rows.length,
27071
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27072
+ rowsHeldBySync: this.countHeldBySync(opts)
27073
+ };
27074
+ }
27075
+ /** Clear eligible bodies, in bounded batches. */
27076
+ expire(opts) {
27077
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27078
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27079
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27080
+ let rowsExpired = 0;
27081
+ let bytesFreed = 0;
27082
+ let done = true;
27083
+ while (rowsExpired < maxRows) {
27084
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27085
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27086
+ if (batch.length === 0) break;
27087
+ withTransaction(
27088
+ this.db,
27089
+ () => {
27090
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27091
+ },
27092
+ "IMMEDIATE"
27093
+ );
27094
+ rowsExpired += batch.length;
27095
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27096
+ if (batch.length < remaining) break;
27097
+ if (rowsExpired >= maxRows) {
27098
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27099
+ }
27100
+ }
27101
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27102
+ }
27103
+ countHeldBySync(opts) {
27104
+ if (opts.sweepSyncLane) return 0;
27105
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27106
+ return row.n;
27107
+ }
27108
+ };
27109
+
26002
27110
  // ../../packages/persistence/src/repositories/classified-data.ts
26003
27111
  var SqliteClassifiedDataRepository = class {
26004
27112
  constructor(db) {
@@ -26827,7 +27935,15 @@ function toFlatFindingRow(r) {
26827
27935
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26828
27936
  eventId: r.event_id,
26829
27937
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26830
- status: deriveInstanceStatus(r)
27938
+ status: deriveInstanceStatus(r),
27939
+ delivery: deriveFindingDelivery({
27940
+ kind: r.kind,
27941
+ syncedAt: r.synced_at,
27942
+ syncClaimedAt: r.sync_claimed_at,
27943
+ syncFailedAt: r.sync_failed_at,
27944
+ syncFailure: r.sync_failure,
27945
+ outboxOwed: r.outbox_owed
27946
+ })
26831
27947
  };
26832
27948
  }
26833
27949
  function encodeGroupCursor(group) {
@@ -26891,7 +28007,10 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
26891
28007
  e.tool_name AS tool_name,
26892
28008
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
26893
28009
  e.event_type AS kind, f.finding_key AS finding_key,
26894
- ${latestResolutionStatusSql("f")} AS latest_status`;
28010
+ ${latestResolutionStatusSql("f")} AS latest_status,
28011
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28012
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28013
+ e.outbox_owed AS outbox_owed`;
26895
28014
  var DAY_MS3 = 864e5;
26896
28015
  var SqliteFindingsRepository = class {
26897
28016
  constructor(db) {
@@ -27136,6 +28255,7 @@ var SqliteFindingsRepository = class {
27136
28255
  providers: query.provider,
27137
28256
  actions: query.action,
27138
28257
  statuses: query.status,
28258
+ deliveries: query.deployment,
27139
28259
  tools: query.tool,
27140
28260
  repo: query.repo,
27141
28261
  file: query.file,
@@ -27203,6 +28323,7 @@ var SqliteFindingsRepository = class {
27203
28323
  providers: query.provider,
27204
28324
  actions: query.action,
27205
28325
  statuses: query.status,
28326
+ deliveries: query.deployment,
27206
28327
  tools: query.tool,
27207
28328
  q: query.q
27208
28329
  };
@@ -27466,7 +28587,9 @@ var SqliteFindingsRepository = class {
27466
28587
  )
27467
28588
  );
27468
28589
  for (const row of grouped) {
27469
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28590
+ if (Object.hasOwn(byAction, row.action_taken)) {
28591
+ byAction[row.action_taken] = row.c;
28592
+ }
27470
28593
  }
27471
28594
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27472
28595
  const sevRows = allRows(
@@ -27483,7 +28606,9 @@ var SqliteFindingsRepository = class {
27483
28606
  )
27484
28607
  );
27485
28608
  for (const row of sevRows) {
27486
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28609
+ if (Object.hasOwn(bySeverity, row.severity)) {
28610
+ bySeverity[row.severity] = row.c;
28611
+ }
27487
28612
  }
27488
28613
  const categories = ENFORCEABLE_CATEGORIES;
27489
28614
  const enabledRows = allRows(
@@ -27532,525 +28657,6 @@ function isoDay(ms) {
27532
28657
  return new Date(ms).toISOString().slice(0, 10);
27533
28658
  }
27534
28659
 
27535
- // ../../packages/persistence/src/repositories/history-sync.ts
27536
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27537
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27538
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27539
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27540
- var SKIPPED = -1;
27541
- var ROW_COLUMNS = `id,
27542
- parent_id AS parentId,
27543
- root_session_id AS rootSessionId,
27544
- event_type AS eventType,
27545
- host_id AS hostId,
27546
- harness_id AS harnessId,
27547
- source_project_id AS sourceProjectId,
27548
- started_at AS startedAt,
27549
- ended_at AS endedAt,
27550
- severity,
27551
- priority,
27552
- content,
27553
- content_hash AS contentHash,
27554
- attributes`;
27555
- var SqliteHistorySyncRepository = class {
27556
- constructor(db) {
27557
- this.db = db;
27558
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27559
- this.sessionsStmt = db.prepare(
27560
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27561
- FROM audit_events
27562
- WHERE synced_at IS NULL
27563
- AND event_type IN (${TYPE_LIST})
27564
- AND started_at < :before
27565
- GROUP BY sessionId
27566
- ORDER BY earliest
27567
- LIMIT :limit`
27568
- );
27569
- this.rowsStmt = db.prepare(
27570
- `SELECT ${ROW_COLUMNS}
27571
- FROM audit_events
27572
- WHERE synced_at IS NULL
27573
- AND event_type IN (${TYPE_LIST})
27574
- AND started_at < :before
27575
- AND COALESCE(root_session_id, id) = :sessionId
27576
- ORDER BY (event_type = 'session') DESC, started_at
27577
- LIMIT :limit`
27578
- );
27579
- this.captureRowsStmt = db.prepare(
27580
- `SELECT ${ROW_COLUMNS}
27581
- FROM audit_events
27582
- WHERE synced_at IS NULL
27583
- AND sync_claimed_at IS NULL
27584
- AND outbox_owed = 1
27585
- AND event_type IN (${CAPTURE_TYPE_LIST})
27586
- AND started_at < :before
27587
- ORDER BY started_at
27588
- LIMIT :limit`
27589
- );
27590
- this.markOwedStmt = db.prepare(
27591
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27592
- );
27593
- this.markCaptureBacklogOwedStmt = db.prepare(
27594
- `UPDATE audit_events SET outbox_owed = 1
27595
- WHERE synced_at IS NULL
27596
- AND event_type IN (${CAPTURE_TYPE_LIST})
27597
- AND started_at < :before`
27598
- );
27599
- this.stampStmt = db.prepare(
27600
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27601
- );
27602
- this.claimRowStmt = db.prepare(
27603
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27604
- );
27605
- this.releaseRowStmt = db.prepare(
27606
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27607
- );
27608
- this.releaseStaleClaimsStmt = db.prepare(
27609
- `UPDATE audit_events SET sync_claimed_at = NULL
27610
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27611
- );
27612
- this.partitionStmt = db.prepare(
27613
- `SELECT
27614
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27615
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27616
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27617
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27618
- COUNT(*) AS total
27619
- FROM audit_events
27620
- WHERE event_type IN (${TYPE_LIST})`
27621
- );
27622
- this.countsStmt = db.prepare(
27623
- `SELECT
27624
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27625
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27626
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27627
- FROM audit_events
27628
- WHERE event_type IN (${TYPE_LIST})`
27629
- );
27630
- this.captureSkipCountStmt = db.prepare(
27631
- `SELECT COUNT(*) AS skipped
27632
- FROM audit_events
27633
- WHERE synced_at = ${String(SKIPPED)}
27634
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27635
- );
27636
- this.fingerprintStmt = db.prepare(
27637
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27638
- FROM history_sync WHERE id = 1`
27639
- );
27640
- this.setFingerprintStmt = db.prepare(
27641
- `UPDATE history_sync
27642
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27643
- WHERE id = 1`
27644
- );
27645
- this.disownCapturesStmt = db.prepare(
27646
- `UPDATE audit_events SET outbox_owed = NULL
27647
- WHERE outbox_owed IS NOT NULL
27648
- AND event_type IN (${CAPTURE_TYPE_LIST})
27649
- AND started_at < :attachedAt`
27650
- );
27651
- this.rearmStmt = db.prepare(
27652
- `UPDATE audit_events SET synced_at = NULL
27653
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27654
- );
27655
- this.claimStmt = db.prepare(
27656
- `UPDATE history_sync
27657
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27658
- WHERE id = 1
27659
- AND (owner_pid IS NULL
27660
- OR heartbeat_at IS NULL
27661
- OR heartbeat_at < :staleBefore
27662
- OR heartbeat_at > :now)`
27663
- );
27664
- this.heartbeatStmt = db.prepare(
27665
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27666
- );
27667
- this.releaseStmt = db.prepare(
27668
- `UPDATE history_sync
27669
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27670
- WHERE id = 1 AND owner_pid = :pid`
27671
- );
27672
- this.closeWindowStmt = db.prepare(
27673
- `UPDATE audit_events SET synced_at = :at
27674
- WHERE synced_at IS NULL
27675
- AND event_type IN (${TYPE_LIST})
27676
- AND started_at >= :attachedAt`
27677
- );
27678
- this.releaseBoundaryStmt = db.prepare(
27679
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27680
- );
27681
- this.freezeBoundaryStmt = db.prepare(
27682
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27683
- );
27684
- this.leaseStmt = db.prepare(
27685
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27686
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27687
- FROM history_sync WHERE id = 1`
27688
- );
27689
- this.inspectionsStmt = db.prepare(
27690
- `SELECT d.rule_id AS ruleId,
27691
- d.name AS ruleName,
27692
- d.version AS ruleVersion,
27693
- d.category AS category,
27694
- d.severity AS severity,
27695
- f.span_start AS spanStart,
27696
- f.span_end AS spanEnd,
27697
- f.masked_match AS maskedMatch,
27698
- f.action_taken AS actionTaken,
27699
- f.confidence AS confidence
27700
- FROM inspection_findings f
27701
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27702
- WHERE f.audit_event_id = :auditEventId
27703
- ORDER BY f.span_start, f.id`
27704
- );
27705
- }
27706
- db;
27707
- ensureRowStmt;
27708
- sessionsStmt;
27709
- rowsStmt;
27710
- stampStmt;
27711
- countsStmt;
27712
- fingerprintStmt;
27713
- setFingerprintStmt;
27714
- rearmStmt;
27715
- claimStmt;
27716
- heartbeatStmt;
27717
- releaseStmt;
27718
- leaseStmt;
27719
- inspectionsStmt;
27720
- closeWindowStmt;
27721
- releaseBoundaryStmt;
27722
- freezeBoundaryStmt;
27723
- captureRowsStmt;
27724
- markOwedStmt;
27725
- markCaptureBacklogOwedStmt;
27726
- captureSkipCountStmt;
27727
- disownCapturesStmt;
27728
- partitionStmt;
27729
- claimRowStmt;
27730
- releaseRowStmt;
27731
- releaseStaleClaimsStmt;
27732
- /**
27733
- * The masked detections recorded against one tool call.
27734
- *
27735
- * These travel with the event because a tool call's target is not
27736
- * re-inspectable from the event alone — unlike a capture, where the text
27737
- * itself is re-scannable. What crosses is the masked match and the rule that
27738
- * produced it, never the value.
27739
- */
27740
- inspectionsFor(auditEventId) {
27741
- return allRows(this.inspectionsStmt, { auditEventId });
27742
- }
27743
- /**
27744
- * Sessions with structural rows still to send, oldest first.
27745
- *
27746
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27747
- * read. Anything recorded after the machine attached is the live forward
27748
- * path's to deliver; this drain exists for what was recorded before it, and a
27749
- * row both paths send is at best a duplicate request and at worst — for a
27750
- * session root — an overwrite of the inventory ids the live path resolved.
27751
- */
27752
- pendingSessions(limit, before) {
27753
- return allRows(this.sessionsStmt, { limit, before }).map(
27754
- (r) => r.sessionId
27755
- );
27756
- }
27757
- /** One session's undelivered structural rows within the backlog, root first. */
27758
- pendingRows(sessionId, limit, before) {
27759
- return allRows(this.rowsStmt, { sessionId, limit, before });
27760
- }
27761
- /**
27762
- * Captures this machine still owes the deployment, oldest first.
27763
- *
27764
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27765
- * by a time window — see captureRowsStmt for why a window could not express
27766
- * this. `before` is the grace window that leaves a just-recorded capture to
27767
- * the live path.
27768
- */
27769
- pendingCaptureRows(limit, before) {
27770
- return allRows(this.captureRowsStmt, { limit, before });
27771
- }
27772
- /**
27773
- * Record that a capture is OWED to the deployment.
27774
- *
27775
- * Written by the attached forward path when a live send did not confirm
27776
- * delivery, and read by the drain as the whole of its eligibility test. It is
27777
- * a fact rather than an inference: the machine was attached, the send did not
27778
- * land, so the row is owed — which no time window can state, because the same
27779
- * window that holds the rows a past attachment left owed also holds every
27780
- * capture recorded while the machine was DETACHED, and those were never
27781
- * offered to anyone.
27782
- *
27783
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27784
- * out of the drain's read.
27785
- */
27786
- markCaptureOwed(id) {
27787
- this.markOwedStmt.run({ id });
27788
- }
27789
- /**
27790
- * Mark every capture already on disk as owed, as of `before`.
27791
- *
27792
- * The consent-time backfill, called once from `aka attach` when a human
27793
- * grants existing-history consent — never from an ongoing drain pass, and
27794
- * never inferred from a boundary that could later move. `before` is the
27795
- * caller's own "now" at the moment consent was granted, so what this marks
27796
- * is exactly the backlog the consent prompt already counted, not whatever a
27797
- * later re-attach or key rotation might widen it to.
27798
- *
27799
- * Returns how many rows matched, for the caller to log or test against. Not a
27800
- * count of NEWLY marked rows — a row still unsynced from an earlier call
27801
- * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27802
- */
27803
- markCaptureBacklogOwed(before) {
27804
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27805
- }
27806
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27807
- markSynced(ids, atMs) {
27808
- this.stampAll(ids, atMs);
27809
- }
27810
- /**
27811
- * Record that a row will never be sent.
27812
- *
27813
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27814
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27815
- * is retried; marking those would turn one outage into permanent data loss.
27816
- */
27817
- markSkipped(ids) {
27818
- this.stampAll(ids, SKIPPED);
27819
- }
27820
- eachInTransaction(ids, run) {
27821
- if (ids.length === 0) return;
27822
- withTransaction(
27823
- this.db,
27824
- () => {
27825
- for (const id of ids) run(id);
27826
- },
27827
- "IMMEDIATE"
27828
- );
27829
- }
27830
- stampAll(ids, value) {
27831
- if (ids.length === 0) return;
27832
- withTransaction(
27833
- this.db,
27834
- () => {
27835
- for (const id of ids) this.stampStmt.run({ at: value, id });
27836
- },
27837
- "IMMEDIATE"
27838
- );
27839
- }
27840
- /**
27841
- * Claim rows as in-flight.
27842
- *
27843
- * Advisory in exactly the sense the lease is: it records that a send is in
27844
- * progress so a surface can say so, and a lost claim costs a row showing as
27845
- * queued while it is actually being sent. It is not exclusion — the far side
27846
- * settles a duplicate on the row id.
27847
- */
27848
- claimRows(ids, atMs) {
27849
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
27850
- }
27851
- /** Give back a claim without settling — the send failed, the row is queued again. */
27852
- releaseRows(ids) {
27853
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
27854
- }
27855
- /**
27856
- * Clear claims older than `staleBefore`, and report how many were cleared.
27857
- *
27858
- * A process killed between claiming and settling leaves rows claimed with
27859
- * nothing left to settle them. Without this they read as "sending" for ever.
27860
- */
27861
- releaseStaleClaims(staleBefore) {
27862
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
27863
- }
27864
- /**
27865
- * Every tracked row in exactly one delivery state.
27866
- *
27867
- * Takes no boundary on purpose. The boundary answers "what should the drain
27868
- * pick up now", which is a different question from "what state is this row
27869
- * in" — and a machine that has never attached has no boundary to pass, so
27870
- * requiring one would force a caller to invent one and report the whole store
27871
- * as queued.
27872
- */
27873
- partition() {
27874
- const row = getRow(this.partitionStmt, {});
27875
- return {
27876
- queued: row?.queued ?? 0,
27877
- inProgress: row?.inProgress ?? 0,
27878
- synced: row?.synced ?? 0,
27879
- failed: row?.failed ?? 0,
27880
- total: row?.total ?? 0
27881
- };
27882
- }
27883
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27884
- counts(before) {
27885
- const row = getRow(
27886
- this.countsStmt,
27887
- { before }
27888
- );
27889
- const captures = getRow(this.captureSkipCountStmt);
27890
- return {
27891
- pending: row?.pending ?? 0,
27892
- sent: row?.sent ?? 0,
27893
- skipped: row?.skipped ?? 0,
27894
- capturesSkipped: captures?.skipped ?? 0
27895
- };
27896
- }
27897
- /**
27898
- * The deployment the current stamps were made against, and where its backlog
27899
- * ends.
27900
- *
27901
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
27902
- * machine that has never drained is — and every writer below seeds the row
27903
- * before it needs one, so nothing depends on this creating it. Keeping the
27904
- * write off the gate path matters because the gate runs on every pass while a
27905
- * write has to take the database's write lock.
27906
- */
27907
- deployment() {
27908
- const row = getRow(
27909
- this.fingerprintStmt
27910
- );
27911
- return {
27912
- fingerprint: row?.fingerprint ?? void 0,
27913
- backlogBefore: row?.backlogBefore ?? void 0
27914
- };
27915
- }
27916
- /**
27917
- * Point the ledger at a different deployment, discarding what it recorded
27918
- * about the previous one.
27919
- *
27920
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
27921
- * machine has just left are undelivered as far as the new one is concerned.
27922
- * All four in one transaction, so a crash between them cannot leave stamps
27923
- * attributed to the wrong deployment, a boundary that belongs to another, or
27924
- * a disown with no re-mark to follow it.
27925
- *
27926
- * The boundary is written HERE and only here, which is what freezes it: a
27927
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
27928
- * unchanged, so this never runs and the backlog does not widen back over rows
27929
- * the live path has since delivered.
27930
- *
27931
- * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
27932
- * granted existing-history consent for the deployment this call is arming —
27933
- * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
27934
- * instant, `backlogBefore` is the ATTACH instant, and the two can be far
27935
- * apart. Passed only when that grant is valid, since this method has no way
27936
- * to check consent itself and must not mark a row owed for a machine that
27937
- * never agreed to it. Applied AFTER the disown above, in the SAME
27938
- * transaction: what the disown clears is every marker below `backlogBefore`,
27939
- * which includes this deployment's OWN pre-attach rows — `aka attach` calls
27940
- * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
27941
- * on the cleared side of that bound — and the re-mark in the same
27942
- * transaction is what puts those rows back. A crash between the two cannot
27943
- * strand the ledger disowned with nothing re-marked — the transaction either
27944
- * lands whole or not at all, and a fingerprint mismatch that has not yet
27945
- * committed re-enters this method on the very next pass. Omit it (the
27946
- * structural-only tests do) to exercise the disown in isolation.
27947
- *
27948
- * The disown is bounded by `backlogBefore`, which is what keeps it from
27949
- * touching a marker the NEW deployment's OWN live path has already set: B's
27950
- * live path can mark a capture owed from the moment `aka attach` writes the
27951
- * descriptor, before the drain's first pass ever reaches this method, and
27952
- * such a row sits at or after the bound rather than below it. What keeps the
27953
- * disown from eating THIS SAME CALL's own re-mark is the order, not the
27954
- * bound — disown runs first, re-mark second, both inside the one
27955
- * transaction above.
27956
- */
27957
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
27958
- this.ensureRowStmt.run();
27959
- withTransaction(
27960
- this.db,
27961
- () => {
27962
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
27963
- this.rearmStmt.run();
27964
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
27965
- this.disownCapturesStmt.run({ attachedAt: backlogBefore });
27966
- }
27967
- if (backfillCapturesBefore !== void 0) {
27968
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
27969
- }
27970
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
27971
- },
27972
- "IMMEDIATE"
27973
- );
27974
- }
27975
- /**
27976
- * End the attached period: hand its rows to the live path, and release the
27977
- * boundary so the next attachment can freeze a new one.
27978
- *
27979
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
27980
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
27981
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
27982
- * during the detached period, because the machine is not attached. Rows
27983
- * recorded in that window sit after the boundary and before the re-attach, so
27984
- * neither path takes them, and the pending count reports none outstanding.
27985
- *
27986
- * Stamping the attached window is not a claim that every one of those rows
27987
- * reached the deployment — the live path drops on failure and says so
27988
- * elsewhere. It records that they were ITS to deliver, which is exactly the
27989
- * status quo: they sit outside the frozen boundary today and are equally never
27990
- * re-sent. Making it explicit is what lets the boundary move.
27991
- *
27992
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
27993
- * window unstamped — that half-state would re-send the whole attached period
27994
- * on the next attach, which is the failure the boundary exists to prevent.
27995
- */
27996
- closeAttachedWindow(attachedAtMs, atMs) {
27997
- this.ensureRowStmt.run();
27998
- withTransaction(
27999
- this.db,
28000
- () => {
28001
- const row = getRow(this.fingerprintStmt);
28002
- const from = row?.backlogBefore ?? attachedAtMs;
28003
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28004
- this.releaseBoundaryStmt.run();
28005
- },
28006
- "IMMEDIATE"
28007
- );
28008
- }
28009
- /**
28010
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28011
- *
28012
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28013
- * different deployment and therefore discards what was delivered to the old
28014
- * one: here the recipient is the same, so everything already sent to it stays
28015
- * sent.
28016
- */
28017
- freezeBoundary(backlogBefore) {
28018
- this.ensureRowStmt.run();
28019
- this.freezeBoundaryStmt.run({ backlogBefore });
28020
- }
28021
- /** Take the claim, or report that someone live already holds it. */
28022
- claim(pid, host, nowMs, staleAfterMs) {
28023
- this.ensureRowStmt.run();
28024
- let taken = false;
28025
- withTransaction(
28026
- this.db,
28027
- () => {
28028
- const result = this.claimStmt.run({
28029
- pid,
28030
- host,
28031
- now: nowMs,
28032
- staleBefore: nowMs - staleAfterMs
28033
- });
28034
- taken = result.changes === 1;
28035
- },
28036
- "IMMEDIATE"
28037
- );
28038
- return taken;
28039
- }
28040
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28041
- heartbeat(pid, nowMs) {
28042
- this.heartbeatStmt.run({ now: nowMs, pid });
28043
- }
28044
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28045
- release(pid) {
28046
- this.releaseStmt.run({ pid });
28047
- }
28048
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28049
- lease() {
28050
- return getRow(this.leaseStmt);
28051
- }
28052
- };
28053
-
28054
28660
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28055
28661
  var SqliteInspectionDefinitionsRepository = class {
28056
28662
  constructor(db) {
@@ -28274,6 +28880,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28274
28880
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28275
28881
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28276
28882
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
28883
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28277
28884
  if (values.vaultConsent !== void 0) {
28278
28885
  merged.vaultConsent = values.vaultConsent ? (
28279
28886
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30781,7 +31388,7 @@ var SqliteSecurityRepository = class {
30781
31388
  ELSE 0
30782
31389
  END) AS open_at_rest
30783
31390
  FROM inspection_findings f
30784
- JOIN audit_events e ON e.id = f.audit_event_id
31391
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30785
31392
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30786
31393
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30787
31394
  ON latest.finding_key = f.finding_key
@@ -31007,7 +31614,7 @@ var SqliteSecurityRepository = class {
31007
31614
  this.db.prepare(
31008
31615
  `SELECT e.repo AS repo, count(*) AS c
31009
31616
  FROM inspection_findings f
31010
- JOIN audit_events e ON e.id = f.audit_event_id
31617
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31011
31618
  WHERE e.started_at >= :from AND e.started_at < :to
31012
31619
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31013
31620
  AND e.repo IS NOT NULL
@@ -31131,7 +31738,7 @@ var SqliteSecurityRepository = class {
31131
31738
  d.severity AS severity,
31132
31739
  COUNT(*) AS count
31133
31740
  FROM inspection_findings f
31134
- JOIN audit_events e ON e.id = f.audit_event_id
31741
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31135
31742
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31136
31743
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31137
31744
  ON latest.finding_key = f.finding_key
@@ -31166,7 +31773,7 @@ var SqliteSecurityRepository = class {
31166
31773
  `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31167
31774
  d.rule_id AS rule_id, d.category AS category
31168
31775
  FROM inspection_findings f
31169
- JOIN audit_events e ON e.id = f.audit_event_id
31776
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31170
31777
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31171
31778
  WHERE e.started_at >= :from AND e.started_at < :to
31172
31779
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -32007,6 +32614,7 @@ function openWithPragmas(file2) {
32007
32614
  db.exec("PRAGMA journal_mode = WAL");
32008
32615
  db.exec("PRAGMA busy_timeout = 2000");
32009
32616
  db.exec("PRAGMA foreign_keys = ON");
32617
+ registerSqlFunctions(db);
32010
32618
  } catch (err) {
32011
32619
  closeQuietly(db);
32012
32620
  throw err;
@@ -32036,7 +32644,7 @@ function backupLegacyStore(db, file2) {
32036
32644
  discardStore(file2, backup);
32037
32645
  return backup;
32038
32646
  }
32039
- function openAndInitialize(file2, base) {
32647
+ function openAndInitialize(file2, base, skipTags) {
32040
32648
  let db = openWithPragmas(file2);
32041
32649
  try {
32042
32650
  if (isForeignSqliteLineage(db)) {
@@ -32046,7 +32654,7 @@ function openAndInitialize(file2, base) {
32046
32654
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32047
32655
  );
32048
32656
  }
32049
- applyMigrations(db, file2);
32657
+ applyMigrations(db, file2, { skipTags });
32050
32658
  tightenPerms(file2);
32051
32659
  const policies = new SqlitePoliciesRepository(db);
32052
32660
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32061,6 +32669,7 @@ function openAndInitialize(file2, base) {
32061
32669
  exceptions: new SqliteExceptionsRepository(db),
32062
32670
  resolutions: new SqliteResolutionsRepository(db),
32063
32671
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32672
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32064
32673
  security: new SqliteSecurityRepository(db),
32065
32674
  detections: new SqliteDetectionsRepository(db),
32066
32675
  shares: new SqliteSharesRepository(db),
@@ -32083,7 +32692,8 @@ function openAndInitialize(file2, base) {
32083
32692
  throw err;
32084
32693
  }
32085
32694
  }
32086
- function openLocalDatabase(dir) {
32695
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32696
+ function openLocalDatabase(dir, options = {}) {
32087
32697
  ensureDataDirSync(dir);
32088
32698
  const file2 = join7(dir, DB_FILENAME);
32089
32699
  reapStalePartials(file2);
@@ -32095,6 +32705,7 @@ function openLocalDatabase(dir) {
32095
32705
  installedPacks,
32096
32706
  scanLedger,
32097
32707
  historySync,
32708
+ bodyRetention,
32098
32709
  secretVault,
32099
32710
  exceptions,
32100
32711
  resolutions,
@@ -32118,7 +32729,8 @@ function openLocalDatabase(dir) {
32118
32729
  // `dir` is always `<base>/data` — every caller resolves it through
32119
32730
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32120
32731
  // settings/ and data/, and the pack-policy floor needs both halves.
32121
- dirname2(dir)
32732
+ dirname2(dir),
32733
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32122
32734
  );
32123
32735
  function captureRowId(event) {
32124
32736
  return captureId(
@@ -32311,6 +32923,7 @@ function openLocalDatabase(dir) {
32311
32923
  installedPacks,
32312
32924
  scanLedger,
32313
32925
  historySync,
32926
+ bodyRetention,
32314
32927
  secretVault,
32315
32928
  exceptions,
32316
32929
  resolutions,
@@ -32351,6 +32964,7 @@ function openLocalDatabase(dir) {
32351
32964
 
32352
32965
  // ../../packages/persistence/src/egress-wire.ts
32353
32966
  import { createHash as createHash3 } from "crypto";
32967
+ var SLASH = "/".charCodeAt(0);
32354
32968
 
32355
32969
  // ../../packages/persistence/src/finding-key.ts
32356
32970
  import { createHash as createHash4 } from "crypto";
@@ -32361,18 +32975,26 @@ import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
32361
32975
  import { join as join8 } from "path";
32362
32976
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
32363
32977
 
32978
+ // ../../packages/persistence/src/forward-health.ts
32979
+ import { readFileSync as readFileSync7 } from "fs";
32980
+ import { join as join9 } from "path";
32981
+
32364
32982
  // ../../packages/persistence/src/history-backfill.ts
32365
32983
  import { existsSync as existsSync4 } from "fs";
32366
- import { join as join9 } from "path";
32984
+ import { join as join10 } from "path";
32367
32985
 
32368
32986
  // ../../packages/persistence/src/history-preview.ts
32369
32987
  import { existsSync as existsSync5 } from "fs";
32370
- import { join as join10 } from "path";
32988
+ import { join as join11 } from "path";
32371
32989
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32372
32990
 
32991
+ // ../../packages/persistence/src/history-sync-state.ts
32992
+ import { readFileSync as readFileSync8 } from "fs";
32993
+ import { join as join12 } from "path";
32994
+
32373
32995
  // ../../packages/persistence/src/store-symlinks.ts
32374
32996
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32375
- import { dirname as dirname3, join as join11, resolve } from "path";
32997
+ import { dirname as dirname3, join as join13, resolve } from "path";
32376
32998
 
32377
32999
  // ../../packages/persistence/src/vault/crypto.ts
32378
33000
  import {
@@ -32386,19 +33008,19 @@ import {
32386
33008
  // ../../packages/persistence/src/vault/key-provider.ts
32387
33009
  import { execFileSync } from "child_process";
32388
33010
  import { randomBytes as randomBytes2 } from "crypto";
32389
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32390
- import { join as join12 } from "path";
33011
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33012
+ import { join as join14 } from "path";
32391
33013
 
32392
33014
  // ../../packages/persistence/src/vault/vault.ts
32393
33015
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32394
33016
 
32395
33017
  // ../../packages/persistence/src/warn-era-cap.ts
32396
33018
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
32397
- import { join as join13 } from "path";
33019
+ import { join as join15 } from "path";
32398
33020
 
32399
33021
  // ../../packages/plugin-sdk/src/config.ts
32400
33022
  import { existsSync as existsSync8 } from "fs";
32401
- import { join as join14 } from "path";
33023
+ import { join as join16 } from "path";
32402
33024
 
32403
33025
  // ../../packages/plugin-sdk/src/provider-env.ts
32404
33026
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -32452,7 +33074,7 @@ function resolveProvider() {
32452
33074
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
32453
33075
  try {
32454
33076
  ensureLayoutDirSync(base);
32455
- const settingsFile = join14(settingsDir(base), "settings.json");
33077
+ const settingsFile = join16(settingsDir(base), "settings.json");
32456
33078
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
32457
33079
  } catch {
32458
33080
  }
@@ -32476,9 +33098,9 @@ function resolveProviderSafe(resolveProviderFn) {
32476
33098
  }
32477
33099
 
32478
33100
  // ../../packages/plugin-sdk/src/config-inventory.ts
32479
- import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33101
+ import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
32480
33102
  import { homedir as homedir2 } from "os";
32481
- import { basename as basename3, join as join16 } from "path";
33103
+ import { basename as basename3, join as join18 } from "path";
32482
33104
 
32483
33105
  // ../../packages/detections/src/egress/registry.ts
32484
33106
  var EXTRACTOR_VERSION = "1";
@@ -35513,8 +36135,8 @@ function maskText(text) {
35513
36135
  }
35514
36136
 
35515
36137
  // ../../packages/plugin-sdk/src/repo.ts
35516
- import { existsSync as existsSync9, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
35517
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
36138
+ import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
36139
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
35518
36140
 
35519
36141
  // ../../packages/plugin-sdk/src/events.ts
35520
36142
  import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
@@ -35525,8 +36147,8 @@ import { fileURLToPath } from "url";
35525
36147
  import { Worker } from "worker_threads";
35526
36148
 
35527
36149
  // ../../packages/plugin-sdk/src/host-floor.ts
35528
- import { readFileSync as readFileSync11 } from "fs";
35529
- import { join as join18 } from "path";
36150
+ import { readFileSync as readFileSync13 } from "fs";
36151
+ import { join as join20 } from "path";
35530
36152
 
35531
36153
  // ../../packages/plugin-sdk/src/model-governance.ts
35532
36154
  import {
@@ -35534,11 +36156,11 @@ import {
35534
36156
  fstatSync,
35535
36157
  mkdirSync as mkdirSync2,
35536
36158
  openSync as openSync2,
35537
- readFileSync as readFileSync10,
36159
+ readFileSync as readFileSync12,
35538
36160
  readSync,
35539
36161
  writeFileSync as writeFileSync5
35540
36162
  } from "fs";
35541
- import { join as join17 } from "path";
36163
+ import { join as join19 } from "path";
35542
36164
  var TAIL_BYTES = 256 * 1024;
35543
36165
 
35544
36166
  // ../../packages/plugin-sdk/src/host-floor.ts
@@ -35561,15 +36183,15 @@ var HOST_FLOORS = {
35561
36183
 
35562
36184
  // ../../packages/plugin-sdk/src/ignore-layers.ts
35563
36185
  var import_ignore = __toESM(require_ignore(), 1);
35564
- import { readFileSync as readFileSync12 } from "fs";
35565
- import { join as join19 } from "path";
36186
+ import { readFileSync as readFileSync14 } from "fs";
36187
+ import { join as join21 } from "path";
35566
36188
 
35567
36189
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
35568
36190
  import { arch, hostname as hostname4, platform, release } from "os";
35569
36191
 
35570
36192
  // ../../packages/plugin-sdk/src/nudge.ts
35571
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
35572
- import { join as join20 } from "path";
36193
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync15, writeFileSync as writeFileSync6 } from "fs";
36194
+ import { join as join22 } from "path";
35573
36195
 
35574
36196
  // ../../packages/plugin-sdk/src/paths.ts
35575
36197
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -35587,7 +36209,7 @@ function applyCategoryPosture(posture, repo, mode = "fill-gaps") {
35587
36209
 
35588
36210
  // ../../packages/plugin-sdk/src/project-files.ts
35589
36211
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
35590
- import { basename as basename5, join as join21 } from "path";
36212
+ import { basename as basename5, join as join23 } from "path";
35591
36213
 
35592
36214
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
35593
36215
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -35705,11 +36327,11 @@ async function applySetupTriageSuppressions(entries, writer, opts) {
35705
36327
 
35706
36328
  // ../../packages/plugin-sdk/src/throttle.ts
35707
36329
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
35708
- import { join as join22 } from "path";
36330
+ import { join as join24 } from "path";
35709
36331
 
35710
36332
  // ../../packages/setup-wizard/src/remediation/rotation-checklist.ts
35711
36333
  import { writeFileSync as writeFileSync8 } from "fs";
35712
- import { join as join23 } from "path";
36334
+ import { join as join25 } from "path";
35713
36335
 
35714
36336
  // ../../packages/setup-wizard/src/triage/dedupe.ts
35715
36337
  function dedupeKey(hit) {
@@ -35764,12 +36386,12 @@ function deriveFalsePositivePatterns(hits, rec, plan) {
35764
36386
  }
35765
36387
 
35766
36388
  // ../../packages/setup-wizard/src/triage/gate-display.ts
35767
- function findContext(entry, join27) {
35768
- const byFingerprint = join27.find(
36389
+ function findContext(entry, join29) {
36390
+ const byFingerprint = join29.find(
35769
36391
  (j) => j.valueFingerprint !== void 0 && j.valueFingerprint === entry.valueFingerprint
35770
36392
  );
35771
36393
  if (byFingerprint) return byFingerprint.maskedContext;
35772
- const byRuleAndMask = join27.find(
36394
+ const byRuleAndMask = join29.find(
35773
36395
  (j) => j.ruleId === entry.ruleId && j.maskedMatch === entry.maskedValue
35774
36396
  );
35775
36397
  return byRuleAndMask?.maskedContext;
@@ -35840,13 +36462,13 @@ function renderShowcase(showcase) {
35840
36462
 
35841
36463
  ${blocks.join("\n\n")}`;
35842
36464
  }
35843
- function renderSuppressionGate(entries, join27) {
36465
+ function renderSuppressionGate(entries, join29) {
35844
36466
  if (entries.length === 0) {
35845
36467
  return "No false-positive suppressions to confirm \u2014 nothing will be written.";
35846
36468
  }
35847
36469
  const header = entries.length === 1 ? "This looks like a false positive \u2014 take a look before I suppress it:" : `These ${String(entries.length)} look like false positives \u2014 take a look before I suppress them:`;
35848
36470
  const blocks = entries.map((entry, i) => {
35849
- const context = findContext(entry, join27);
36471
+ const context = findContext(entry, join29);
35850
36472
  const lines = [
35851
36473
  `${String(i + 1)}. ${entry.ruleId} [${entry.category}]`,
35852
36474
  ` value: ${entry.maskedValue}`,
@@ -35932,9 +36554,9 @@ function mergeRecommendations(verdicts) {
35932
36554
  }
35933
36555
 
35934
36556
  // ../../packages/setup-wizard/src/triage/plan-file.ts
35935
- import { mkdtempSync, readFileSync as readFileSync14, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
36557
+ import { mkdtempSync, readFileSync as readFileSync16, rmdirSync, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "fs";
35936
36558
  import { tmpdir } from "os";
35937
- import { basename as basename6, dirname as dirname6, join as join24 } from "path";
36559
+ import { basename as basename6, dirname as dirname6, join as join26 } from "path";
35938
36560
  var SuppressionEntrySchema = external_exports.object({
35939
36561
  ruleId: external_exports.string(),
35940
36562
  category: DetectionCategory,
@@ -35989,13 +36611,13 @@ function serializePlan(plan, current) {
35989
36611
  function writePlanFile(plan, current, rawValues, deps = {}) {
35990
36612
  const serialized = serializePlan(plan, current);
35991
36613
  assertRawFree(serialized, rawValues);
35992
- const dir = (deps.mkTempDir ?? (() => mkdtempSync(join24(tmpdir(), "aka-plan-"))))();
35993
- const path = join24(dir, "setup-plan.json");
36614
+ const dir = (deps.mkTempDir ?? (() => mkdtempSync(join26(tmpdir(), "aka-plan-"))))();
36615
+ const path = join26(dir, "setup-plan.json");
35994
36616
  writeFileSync9(path, serialized, { encoding: "utf8", mode: 384 });
35995
36617
  return path;
35996
36618
  }
35997
36619
  function readPlanFile(path) {
35998
- const text = readFileSync14(path, "utf8");
36620
+ const text = readFileSync16(path, "utf8");
35999
36621
  const json2 = JSON.parse(text);
36000
36622
  return PersistedPlanSchema.parse(json2);
36001
36623
  }
@@ -36069,8 +36691,8 @@ function buildJoinEntries(hits) {
36069
36691
  }
36070
36692
 
36071
36693
  // ../../packages/setup-wizard/src/triage/resolve.ts
36072
- function resolveSuppressions(rec, join27) {
36073
- const byId = new Map(join27.map((e) => [e.id, e]));
36694
+ function resolveSuppressions(rec, join29) {
36695
+ const byId = new Map(join29.map((e) => [e.id, e]));
36074
36696
  const entries = [];
36075
36697
  const skipped = [];
36076
36698
  for (const cat of rec.perCategory) {
@@ -36172,7 +36794,7 @@ function parseTriageStream(text) {
36172
36794
  return { hits, status: "complete" };
36173
36795
  }
36174
36796
  function planTriageWriteback(hits, rec) {
36175
- const join27 = buildJoinEntries(hits);
36797
+ const join29 = buildJoinEntries(hits);
36176
36798
  const rawValues = hits.map((h) => h.rawMatch);
36177
36799
  const skipped = [];
36178
36800
  const posture = {};
@@ -36212,7 +36834,7 @@ function planTriageWriteback(hits, rec) {
36212
36834
  }
36213
36835
  const { entries, skipped: resolveSkips } = resolveSuppressions(
36214
36836
  { perCategory: safeCategories, notes: rec.notes },
36215
- join27
36837
+ join29
36216
36838
  );
36217
36839
  skipped.push(...resolveSkips);
36218
36840
  let notes = rec.notes;
@@ -36222,7 +36844,7 @@ function planTriageWriteback(hits, rec) {
36222
36844
  if (err instanceof RawEgressError) notes = SCRUBBED_NOTES;
36223
36845
  else throw err;
36224
36846
  }
36225
- return { entries, posture, showcase, join: join27, notes, skipped };
36847
+ return { entries, posture, showcase, join: join29, notes, skipped };
36226
36848
  }
36227
36849
  function recommendedPosture(evidence) {
36228
36850
  return { ...severityFloorPosture(), ...evidence };
@@ -36491,9 +37113,9 @@ function parseRecommendation(text) {
36491
37113
 
36492
37114
  // src/triage/judge.ts
36493
37115
  import { execFileSync as execFileSync2 } from "child_process";
36494
- import { mkdtempSync as mkdtempSync2, readFileSync as readFileSync15, rmSync as rmSync8 } from "fs";
37116
+ import { mkdtempSync as mkdtempSync2, readFileSync as readFileSync17, rmSync as rmSync8 } from "fs";
36495
37117
  import { tmpdir as tmpdir2 } from "os";
36496
- import { dirname as dirname7, join as join25 } from "path";
37118
+ import { dirname as dirname7, join as join27 } from "path";
36497
37119
  import { fileURLToPath as fileURLToPath2 } from "url";
36498
37120
 
36499
37121
  // ../../packages/plugin-sdk/src/bare-command.ts
@@ -36605,7 +37227,7 @@ function planBareCommand(command, args, deps = {}) {
36605
37227
 
36606
37228
  // src/triage/judge.ts
36607
37229
  var TRIAGE_DIR = dirname7(fileURLToPath2(import.meta.url));
36608
- var DEFAULT_RUBRIC_PATH = join25(
37230
+ var DEFAULT_RUBRIC_PATH = join27(
36609
37231
  TRIAGE_DIR,
36610
37232
  "..",
36611
37233
  "..",
@@ -36642,7 +37264,7 @@ function judgeEnv(platform2 = process.platform) {
36642
37264
  CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1"
36643
37265
  };
36644
37266
  if (platform2 === "darwin") {
36645
- env.CLAUDE_CONFIG_DIR = mkdtempSync2(join25(tmpdir2(), "aka-judge-cfg-"));
37267
+ env.CLAUDE_CONFIG_DIR = mkdtempSync2(join27(tmpdir2(), "aka-judge-cfg-"));
36646
37268
  }
36647
37269
  return env;
36648
37270
  }
@@ -36677,7 +37299,7 @@ function runJudge(hits, deps) {
36677
37299
  if (typeof deps.spawn !== "function") {
36678
37300
  throw new TypeError("runJudge requires deps.spawn \u2014 there is no live-spawn fallback");
36679
37301
  }
36680
- const rubric = deps.loadRubric?.() ?? readFileSync15(DEFAULT_RUBRIC_PATH, "utf8");
37302
+ const rubric = deps.loadRubric?.() ?? readFileSync17(DEFAULT_RUBRIC_PATH, "utf8");
36681
37303
  const hitsJsonl = hits.map((h) => JSON.stringify(toJudgePayload(h))).join("\n");
36682
37304
  const fullPrompt = `${rubric}
36683
37305
 
@@ -36947,10 +37569,10 @@ function resolveCreatedBy() {
36947
37569
  }
36948
37570
  function loadRubric() {
36949
37571
  const here = dirname8(fileURLToPath4(import.meta.url));
36950
- const shipped = join26(here, "triage-rubric.md");
36951
- if (existsSync12(shipped)) return readFileSync16(shipped, "utf8");
36952
- return readFileSync16(
36953
- join26(here, "..", "..", "..", "packages", "setup-wizard", "assets", "triage-rubric.md"),
37572
+ const shipped = join28(here, "triage-rubric.md");
37573
+ if (existsSync12(shipped)) return readFileSync18(shipped, "utf8");
37574
+ return readFileSync18(
37575
+ join28(here, "..", "..", "..", "packages", "setup-wizard", "assets", "triage-rubric.md"),
36954
37576
  "utf8"
36955
37577
  );
36956
37578
  }
@@ -36960,7 +37582,7 @@ async function main() {
36960
37582
  argv,
36961
37583
  // fd 0 = stdin; the wizard pipes `backfill.js --triage` into this on preview.
36962
37584
  // Called only on the preview path — the confirm path never reads a stream.
36963
- readStream: (streamPath) => streamPath !== void 0 ? readFileSync16(streamPath, "utf8") : readFileSync16(0, "utf8"),
37585
+ readStream: (streamPath) => streamPath !== void 0 ? readFileSync18(streamPath, "utf8") : readFileSync18(0, "utf8"),
36964
37586
  runJudge: (hits) => runJudge(hits, { spawn: spawnClaude, loadRubric }),
36965
37587
  // The distinct model-judge egress consent, read from settings.json. When it
36966
37588
  // is absent or stale the preview skips the judge instead of sending findings