@akasecurity/ai-tc-codex 0.9.11 → 0.9.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH2 = "/";
53
+ var SLASH3 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH2).filter(Boolean);
425
+ const slices = path.split(SLASH3).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH2) + SLASH2,
429
+ slices.join(SLASH3) + SLASH3,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH2).filter(Boolean);
445
+ slices = path.split(SLASH3).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH2) + SLASH2,
452
+ slices.join(SLASH3) + SLASH3,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -493,7 +493,7 @@ var require_ignore = __commonJS({
493
493
 
494
494
  // ../../packages/plugin-sdk/src/config.ts
495
495
  import { existsSync as existsSync8 } from "fs";
496
- import { join as join14 } from "path";
496
+ import { join as join16 } from "path";
497
497
 
498
498
  // ../../packages/persistence/src/attached-derived.ts
499
499
  import { rmSync } from "fs";
@@ -506,6 +506,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.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
 
@@ -20623,7 +20655,7 @@ var TOOL_TO_HARNESS = {
20623
20655
  [SOURCE_TOOL.ClaudeAi]: HARNESS.ClaudeAi
20624
20656
  };
20625
20657
  function harnessFromTool(tool) {
20626
- return TOOL_TO_HARNESS[tool] ?? tool;
20658
+ return (Object.hasOwn(TOOL_TO_HARNESS, tool) ? TOOL_TO_HARNESS[tool] : void 0) ?? tool;
20627
20659
  }
20628
20660
 
20629
20661
  // ../../packages/schema/src/zod/finding.ts
@@ -20673,6 +20705,15 @@ var FindingCategory = external_exports.enum([
20673
20705
  ]).meta({ id: "FindingCategory" });
20674
20706
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20675
20707
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20708
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20709
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20710
+ var FindingDelivery = external_exports.object({
20711
+ state: FindingDeliveryState,
20712
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20713
+ at: external_exports.iso.datetime().optional(),
20714
+ // Only on `not_sent`, and only when a known reason was recorded.
20715
+ reason: SyncFailureReason.optional()
20716
+ }).meta({ id: "FindingDelivery" });
20676
20717
  var ResolutionMethod = external_exports.enum([
20677
20718
  "enforced-in-flight",
20678
20719
  "fixed-at-source",
@@ -20729,7 +20770,10 @@ var FindingInstance = external_exports.object({
20729
20770
  // The session that event belongs to, when it has one — the seam a
20730
20771
  // per-instance "view session" link needs. Absent for events captured
20731
20772
  // outside a session.
20732
- sessionId: external_exports.string().optional()
20773
+ sessionId: external_exports.string().optional(),
20774
+ // The delivery state of the event above (see FindingDelivery). Optional so
20775
+ // readers that do not project it stay valid.
20776
+ delivery: FindingDelivery.optional()
20733
20777
  }).meta({ id: "FindingInstance" });
20734
20778
  var FindingGroup = external_exports.object({
20735
20779
  id: external_exports.string(),
@@ -20781,7 +20825,10 @@ var FindingFacets = external_exports.object({
20781
20825
  // Host tool (attributes.tool_name). Present only on the instance-level
20782
20826
  // reads, which can filter by it; the type-level read omits the dimension
20783
20827
  // because a group spans tools.
20784
- tool: external_exports.array(FindingFacetItem).optional()
20828
+ tool: external_exports.array(FindingFacetItem).optional(),
20829
+ // Delivery states (FindingDeliveryState). Present only on the
20830
+ // instance-level reads, like `tool`.
20831
+ deployment: external_exports.array(FindingFacetItem).optional()
20785
20832
  }).meta({ id: "FindingFacets" });
20786
20833
  var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20787
20834
  id: "FindingTypeSummary"
@@ -20892,6 +20939,8 @@ var ListFindingInstancesQuery = external_exports.object({
20892
20939
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20893
20940
  // where the free-text `q` can only match the rendered "via Bash" label.
20894
20941
  tool: external_exports.array(external_exports.string()).optional(),
20942
+ // The delivery state of each finding's event (see FindingDelivery).
20943
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20895
20944
  // Exact repository / file-path matches, for the drill-down out of the
20896
20945
  // locations view. A row whose event carries no repo/file matches neither.
20897
20946
  repo: external_exports.string().optional(),
@@ -20912,6 +20961,10 @@ var ListFindingInstancesResponse = external_exports.object({
20912
20961
  items: external_exports.array(FindingInstanceDetail),
20913
20962
  nextCursor: external_exports.string().nullable()
20914
20963
  }).meta({ id: "ListFindingInstancesResponse" });
20964
+ var ListFindingInstancesPage = external_exports.object({
20965
+ items: external_exports.array(FindingInstanceDetail),
20966
+ nextCursor: external_exports.string().nullable()
20967
+ }).meta({ id: "ListFindingInstancesPage" });
20915
20968
  var FindingLocationSummary = external_exports.object({
20916
20969
  // Opaque, stable, minted from the pair by encodeLocationId. It exists
20917
20970
  // because a location's identity is two values and a URL param carries one:
@@ -20954,6 +21007,8 @@ var ListFindingLocationsQuery = external_exports.object({
20954
21007
  // instances that match, and folds its status from those.
20955
21008
  status: external_exports.array(FindingStatus).optional(),
20956
21009
  tool: external_exports.array(external_exports.string()).optional(),
21010
+ // The delivery state of each finding's event (see FindingDelivery).
21011
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20957
21012
  q: external_exports.string().optional(),
20958
21013
  sessionId: external_exports.string().optional(),
20959
21014
  from: external_exports.iso.datetime().optional(),
@@ -21156,6 +21211,10 @@ var CaptureAttributes = external_exports.object({
21156
21211
  // to 'allow' — the enforcement audit trail's link back to the grant that
21157
21212
  // authorized the bypass.
21158
21213
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21214
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21215
+ // join back to the `llm_call` leaf for the same assistant turn.
21216
+ message_id: external_exports.string().optional(),
21217
+ conversation_id: external_exports.string().optional(),
21159
21218
  // Whole milliseconds this capture's inspection blocked its caller — the
21160
21219
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21161
21220
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21164,7 +21223,19 @@ var CaptureAttributes = external_exports.object({
21164
21223
  // inline json_extract and is not itself an optimization.
21165
21224
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21166
21225
  // before the measurement shipped — never present as a placeholder 0.
21167
- inspection_ms: external_exports.number().int().nonnegative().optional()
21226
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21227
+ // What a `redact` this capture could not carry out became instead (see
21228
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21229
+ // degrade actually happened, so absence is the ordinary case rather than a
21230
+ // reader having to distinguish it from a zero.
21231
+ //
21232
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21233
+ // so on a multi-finding row this does not say which finding degraded, and
21234
+ // its presence does not mean the fallback decided the capture's action. A
21235
+ // capture denied by another finding's own Block policy carries `block`
21236
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21237
+ // repeated rather than referenced because a store reader opens this file.
21238
+ redact_degraded_to: ActionTaken.optional()
21168
21239
  }).catchall(external_exports.unknown());
21169
21240
  var ToolCallInspection = external_exports.object({
21170
21241
  ruleId: external_exports.string().min(1),
@@ -21363,7 +21434,17 @@ var AuditEvent = external_exports.object({
21363
21434
  /** `share` to a first-party/internal destination. */
21364
21435
  internal: external_exports.boolean(),
21365
21436
  /** Event needs review (e.g. unverified egress). */
21366
- flagged: external_exports.boolean()
21437
+ flagged: external_exports.boolean(),
21438
+ /**
21439
+ * The body this event's `title` is drawn from was cleared by local body
21440
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21441
+ *
21442
+ * A separate flag rather than a sentinel written into `title`: the title is
21443
+ * rendered text, and a store-layer module that invented display copy for it
21444
+ * would be choosing words the view is supposed to choose. Additive and
21445
+ * defaulted, so an older producer still validates.
21446
+ */
21447
+ bodyExpired: external_exports.boolean().default(false)
21367
21448
  }).meta({ id: "ActivityAuditEvent" });
21368
21449
  var ActivitySessionSummary = external_exports.object({
21369
21450
  id: external_exports.string(),
@@ -22704,6 +22785,12 @@ var EventMetadata = external_exports.object({
22704
22785
  // to 'allow' — the enforcement audit trail's link back to the grant that
22705
22786
  // authorized the bypass. Absent on captures where no exception applied.
22706
22787
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22788
+ // The assistant message this capture belongs to, and the conversation it sits
22789
+ // in — set by the browser extension's network capture so a stored `response`
22790
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22791
+ // on every other capture path, which has no such id.
22792
+ messageId: external_exports.string().optional(),
22793
+ conversationId: external_exports.string().optional(),
22707
22794
  // How long THIS capture's inspection blocked its caller, in whole
22708
22795
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22709
22796
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22716,7 +22803,37 @@ var EventMetadata = external_exports.object({
22716
22803
  // Absent is also what every pre-measurement client writes, and what a
22717
22804
  // clock failure degrades to — a reader must treat absence as "not measured"
22718
22805
  // and never as a zero, which would read as "inspection is free".
22719
- inspectionMs: external_exports.number().int().nonnegative().optional()
22806
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22807
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22808
+ // workspace's `redactFallback`, applied because the field could not be
22809
+ // masked in place (a shell command, a URL, or any argument on a host whose
22810
+ // hook contract offers no rewrite channel).
22811
+ //
22812
+ // It exists because the action alone cannot say why. A finding recorded as
22813
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22814
+ // assigned Redact on a field that could not take one — and those are
22815
+ // different facts about the same row: the first is a policy the user chose,
22816
+ // the second is a masking the host could not perform. Absent means no
22817
+ // degrade happened, which is every ordinary capture.
22818
+ //
22819
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22820
+ // is the CAPTURE while `actionTaken` is per FINDING:
22821
+ //
22822
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22823
+ // `redact` alongside a finding ASSIGNED the same action stores both
22824
+ // identically and one reason for the pair; attributing it to both
22825
+ // describes the assigned one wrongly, and to neither loses the degrade.
22826
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22827
+ // became, not the reason the capture ended as it did — a capture denied
22828
+ // by some other finding's own Block policy still carries `block` here,
22829
+ // and clearing the workspace's fallback would not have let it through.
22830
+ // Gate on the value against what a fallback can produce; never read the
22831
+ // field's presence as "this was the fallback's doing".
22832
+ //
22833
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22834
+ // Closing either means moving the reason onto the finding row, which
22835
+ // already carries its own action.
22836
+ redactDegradedTo: ActionTaken.optional()
22720
22837
  }).meta({ id: "EventMetadata" });
22721
22838
  var Event = external_exports.object({
22722
22839
  id: external_exports.guid(),
@@ -22826,7 +22943,32 @@ var RotateKeyInput = external_exports.object({
22826
22943
  confirmation: external_exports.string()
22827
22944
  });
22828
22945
 
22946
+ // ../../packages/schema/src/zod/finding-delivery.ts
22947
+ var KNOWN_REASONS = SyncFailureReason.options;
22948
+ function knownReason(value) {
22949
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
22950
+ }
22951
+ function deriveFindingDelivery(row) {
22952
+ if (row.kind === "code_change") return { state: "local_scan" };
22953
+ if (row.syncedAt !== null && row.syncedAt > 0) {
22954
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
22955
+ }
22956
+ if (row.syncedAt !== null) {
22957
+ const reason = knownReason(row.syncFailure);
22958
+ return {
22959
+ state: "not_sent",
22960
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
22961
+ ...reason === void 0 ? {} : { reason }
22962
+ };
22963
+ }
22964
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
22965
+ return { state: "never_offered" };
22966
+ }
22967
+
22829
22968
  // ../../packages/schema/src/zod/findings-group-build.ts
22969
+ function lookupOwn(map2, key) {
22970
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
22971
+ }
22830
22972
  function toApiAction(dbVal) {
22831
22973
  const map2 = {
22832
22974
  log: "monitored",
@@ -22835,7 +22977,7 @@ function toApiAction(dbVal) {
22835
22977
  warn: "warned",
22836
22978
  allow: "allowed"
22837
22979
  };
22838
- return map2[dbVal] ?? "allowed";
22980
+ return lookupOwn(map2, dbVal) ?? "allowed";
22839
22981
  }
22840
22982
  function toApiCategory(dbVal) {
22841
22983
  if (dbVal === "code_context") return "source_code";
@@ -22843,13 +22985,18 @@ function toApiCategory(dbVal) {
22843
22985
  return parsed2.success ? parsed2.data : "custom";
22844
22986
  }
22845
22987
  function toApiProvider(sourceTool) {
22846
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
22988
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22847
22989
  }
22848
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
22990
+ var FINDING_STATUS_PRECEDENCE = [
22991
+ "open",
22992
+ "handled",
22993
+ "dismissed",
22994
+ "resolved"
22995
+ ];
22849
22996
  function foldGroupStatus(instanceStatuses) {
22850
22997
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22851
22998
  if (statuses.size === 0) return void 0;
22852
- for (const candidate of STATUS_PRECEDENCE) {
22999
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22853
23000
  if (statuses.has(candidate)) return candidate;
22854
23001
  }
22855
23002
  return void 0;
@@ -22956,11 +23103,16 @@ function applyFindingFilters(types, opts) {
22956
23103
  }
22957
23104
  return filtered;
22958
23105
  }
22959
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22960
- var SEVERITY_RANK = SEVERITY_ORDER;
23106
+ function rankByOrder(members2) {
23107
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23108
+ }
23109
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23110
+ function severityRank(severity) {
23111
+ return lookupOwn(SEVERITY_RANK, severity);
23112
+ }
22961
23113
  function compareFindingGroupOrder(a, b) {
22962
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22963
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23114
+ const rankA = severityRank(a.severity) ?? -1;
23115
+ const rankB = severityRank(b.severity) ?? -1;
22964
23116
  const severityDiff = rankA - rankB;
22965
23117
  if (severityDiff !== 0) return severityDiff;
22966
23118
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
@@ -23035,6 +23187,20 @@ function computeFindingFacets(allTypes, opts) {
23035
23187
  }
23036
23188
 
23037
23189
  // ../../packages/schema/src/zod/findings-flat-build.ts
23190
+ function compareCodePoints(a, b) {
23191
+ const aIter = a[Symbol.iterator]();
23192
+ const bIter = b[Symbol.iterator]();
23193
+ for (; ; ) {
23194
+ const aNext = aIter.next();
23195
+ const bNext = bIter.next();
23196
+ if (aNext.done && bNext.done) return 0;
23197
+ if (aNext.done) return -1;
23198
+ if (bNext.done) return 1;
23199
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23200
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23201
+ if (aPoint !== bPoint) return aPoint - bPoint;
23202
+ }
23203
+ }
23038
23204
  function rowHaystack(row) {
23039
23205
  return [
23040
23206
  row.ruleId,
@@ -23059,6 +23225,8 @@ function matchesDimension(row, opts, dimension) {
23059
23225
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23060
23226
  case "statuses":
23061
23227
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23228
+ case "deliveries":
23229
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23062
23230
  case "tools":
23063
23231
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23064
23232
  // An EMPTY value is a real filter here, not an absent one. The location
@@ -23085,6 +23253,7 @@ var DIMENSIONS = [
23085
23253
  "providers",
23086
23254
  "actions",
23087
23255
  "statuses",
23256
+ "deliveries",
23088
23257
  "tools",
23089
23258
  "repo",
23090
23259
  "file",
@@ -23098,10 +23267,19 @@ function matchesInstanceFilters(row, opts, except) {
23098
23267
  return true;
23099
23268
  }
23100
23269
  function toItems(counts) {
23101
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23270
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23271
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23272
+ // NFD spelling of the same text) as equal, so a count tie between
23273
+ // them would otherwise be ordered by whichever the Map iteration
23274
+ // produced. compareCodePoints breaks that tie deterministically, which
23275
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23276
+ // which it need not: foldFacetTuples runs this same sort over grouped
23277
+ // tuples, so both paths order facets identically by construction.
23278
+ compareCodePoints(a.value, b.value)
23279
+ );
23102
23280
  }
23103
- function bump(counts, value) {
23104
- counts.set(value, (counts.get(value) ?? 0) + 1);
23281
+ function bump(counts, value, by = 1) {
23282
+ counts.set(value, (counts.get(value) ?? 0) + by);
23105
23283
  }
23106
23284
  function createInstanceFacetAccumulator(opts) {
23107
23285
  const severity = /* @__PURE__ */ new Map();
@@ -23110,6 +23288,7 @@ function createInstanceFacetAccumulator(opts) {
23110
23288
  const action = /* @__PURE__ */ new Map();
23111
23289
  const status = /* @__PURE__ */ new Map();
23112
23290
  const tool = /* @__PURE__ */ new Map();
23291
+ const deployment = /* @__PURE__ */ new Map();
23113
23292
  return {
23114
23293
  add(row) {
23115
23294
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23124,6 +23303,9 @@ function createInstanceFacetAccumulator(opts) {
23124
23303
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23125
23304
  bump(tool, row.toolName);
23126
23305
  }
23306
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23307
+ bump(deployment, row.delivery.state);
23308
+ }
23127
23309
  },
23128
23310
  facets: () => ({
23129
23311
  severity: toItems(severity),
@@ -23131,7 +23313,8 @@ function createInstanceFacetAccumulator(opts) {
23131
23313
  provider: toItems(provider),
23132
23314
  action: toItems(action),
23133
23315
  status: toItems(status),
23134
- tool: toItems(tool)
23316
+ tool: toItems(tool),
23317
+ deployment: toItems(deployment)
23135
23318
  })
23136
23319
  };
23137
23320
  }
@@ -23145,6 +23328,7 @@ function toInstanceDetail(row) {
23145
23328
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23146
23329
  eventId: row.eventId,
23147
23330
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23331
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23148
23332
  ...row.user === void 0 ? {} : { user: row.user },
23149
23333
  action: toApiAction(row.actionTaken),
23150
23334
  detectedAt: row.occurredAt,
@@ -23159,12 +23343,6 @@ function toInstanceDetail(row) {
23159
23343
  policy: { id: `category:${category}`, name: category }
23160
23344
  };
23161
23345
  }
23162
- var SEVERITY_ORDER2 = {
23163
- critical: 0,
23164
- high: 1,
23165
- medium: 2,
23166
- low: 3
23167
- };
23168
23346
  function newLocationAccumulator() {
23169
23347
  return {
23170
23348
  instanceCount: 0,
@@ -23179,7 +23357,7 @@ function newLocationAccumulator() {
23179
23357
  }
23180
23358
  function addToLocation(acc, row) {
23181
23359
  acc.instanceCount += 1;
23182
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23360
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23183
23361
  if (rank < acc.maxSeverityRank) {
23184
23362
  acc.maxSeverityRank = rank;
23185
23363
  acc.maxSeverity = row.severity;
@@ -23189,15 +23367,15 @@ function addToLocation(acc, row) {
23189
23367
  acc.ruleIds.add(row.ruleId);
23190
23368
  }
23191
23369
  function compareLocationOrder(a, b) {
23192
- const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23193
- const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23370
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23371
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23194
23372
  if (rankA !== rankB) return rankA - rankB;
23195
23373
  if (a.latestDetectedAt !== b.latestDetectedAt) {
23196
23374
  return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23197
23375
  }
23198
- if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23199
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23200
- return 0;
23376
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23377
+ if (repoDiff !== 0) return repoDiff;
23378
+ return compareCodePoints(a.file, b.file);
23201
23379
  }
23202
23380
  function encodeLocationId(repo, file2) {
23203
23381
  return `${encodePart(repo)}/${encodePart(file2)}`;
@@ -23272,6 +23450,11 @@ var Policy = external_exports.object({
23272
23450
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23273
23451
  provenance: PolicyProvenance.optional()
23274
23452
  }).meta({ id: "Policy" });
23453
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23454
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23455
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23456
+ id: "RedactFallback"
23457
+ });
23275
23458
  var PolicyBundle = external_exports.object({
23276
23459
  version: external_exports.string(),
23277
23460
  policies: external_exports.array(Policy),
@@ -23319,6 +23502,16 @@ var PolicyBundle = external_exports.object({
23319
23502
  // control plane), so no name resolution stands between the decision and the
23320
23503
  // comparison.
23321
23504
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23505
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23506
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23507
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23508
+ // a control plane can tighten a machine and never loosen one — the same
23509
+ // direction `mergeRaiseOnly` enforces for policies.
23510
+ //
23511
+ // Optional so an older backend, and an older on-disk cache, still parses;
23512
+ // absent leaves the device's own setting in force, which is the behaviour
23513
+ // that predates the field and the safe direction to default.
23514
+ redactFallback: RedactFallback.optional(),
23322
23515
  customKeywords: external_exports.array(external_exports.string()),
23323
23516
  fetchedAt: external_exports.iso.datetime()
23324
23517
  }).meta({ id: "PolicyBundle" });
@@ -23348,11 +23541,6 @@ function severityFloorPolicy(category) {
23348
23541
  const peak = CATEGORY_PEAK_SEVERITY[category];
23349
23542
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23350
23543
  }
23351
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23352
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23353
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23354
- id: "RedactFallback"
23355
- });
23356
23544
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23357
23545
  var BUILTIN_POLICY_SPECS = {
23358
23546
  monitor: {
@@ -23648,7 +23836,7 @@ var VaultConsent = external_exports.object({
23648
23836
  });
23649
23837
 
23650
23838
  // ../../packages/schema/src/zod/local.ts
23651
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23839
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23652
23840
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23653
23841
  var RunMode = external_exports.enum(["standalone", "attached"]);
23654
23842
  var ControlPlaneConnection = external_exports.object({
@@ -23668,6 +23856,15 @@ var HistorySyncConsent = external_exports.object({
23668
23856
  payloadVersion: external_exports.number().int().positive(),
23669
23857
  endpoint: external_exports.string()
23670
23858
  });
23859
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23860
+ var BodyRetention = external_exports.object({
23861
+ enabled: external_exports.boolean().default(false),
23862
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23863
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23864
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23865
+ // candidate set that is already bounded by "delivered, or never owed".
23866
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23867
+ }).meta({ id: "BodyRetention" });
23671
23868
  var WorkspaceSettings = external_exports.object({
23672
23869
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23673
23870
  runMode: RunMode.default("standalone"),
@@ -23716,7 +23913,13 @@ var WorkspaceSettings = external_exports.object({
23716
23913
  // carry prompt/reply/tool-output text in `content`; the key name predates
23717
23914
  // both widenings. Absent until granted, and a grant for a different endpoint
23718
23915
  // or an older payload no longer counts.
23719
- historySyncConsent: HistorySyncConsent.optional()
23916
+ historySyncConsent: HistorySyncConsent.optional(),
23917
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23918
+ // body never removes the row or its findings.
23919
+ bodyRetention: BodyRetention.default({
23920
+ enabled: false,
23921
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23922
+ })
23720
23923
  });
23721
23924
  function defaultWorkspaceSettings() {
23722
23925
  return WorkspaceSettings.parse({});
@@ -23811,12 +24014,15 @@ function toCaptureAttributes(event) {
23811
24014
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23812
24015
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23813
24016
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24017
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23814
24018
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23815
24019
  // has ever populated either), but every legacy metadata key still rides
23816
24020
  // the bag rather than being silently dropped — CaptureAttributes'
23817
24021
  // `.catchall(z.unknown())` carries the long tail.
23818
24022
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23819
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24023
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24024
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24025
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23820
24026
  };
23821
24027
  }
23822
24028
  function captureDefinitionVersion(finding) {
@@ -23844,13 +24050,22 @@ var ManagedSettingKey = external_exports.enum([
23844
24050
  "vaultInlineReveal",
23845
24051
  "modelJudgeConsent",
23846
24052
  "dataSharesInPlace",
23847
- "redactFallback"
24053
+ "redactFallback",
24054
+ // Pins the toggle and the day count together — see BodyRetention on why the
24055
+ // two are one unit. An administrator mandating a window wants the count
24056
+ // enforced with it, not one a user can widen while the toggle stays on.
24057
+ "bodyRetention"
23848
24058
  ]).meta({ id: "ManagedSettingKey" });
23849
24059
  function isManagedSettingKey(value) {
23850
24060
  return ManagedSettingKey.safeParse(value).success;
23851
24061
  }
23852
24062
  var ManagedSettingsValues = external_exports.object({
23853
24063
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24064
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24065
+ // plain, non-strict objects: a key under either that this build does not know
24066
+ // is stripped and nothing reports it. The unknown-value split in
24067
+ // ManagedSettings below classifies top-level names only, so it stops at
24068
+ // these boundaries.
23854
24069
  controlPlane: external_exports.object({
23855
24070
  endpoint: external_exports.string().min(1),
23856
24071
  label: external_exports.string().min(1).optional()
@@ -23861,7 +24076,8 @@ var ManagedSettingsValues = external_exports.object({
23861
24076
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23862
24077
  modelJudgeConsent: external_exports.boolean().optional(),
23863
24078
  dataSharesInPlace: external_exports.boolean().optional(),
23864
- redactFallback: RedactFallback.optional()
24079
+ redactFallback: RedactFallback.optional(),
24080
+ bodyRetention: BodyRetention.optional()
23865
24081
  }).meta({ id: "ManagedSettingsValues" });
23866
24082
  var ManagedSettings = external_exports.object({
23867
24083
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23869,7 +24085,21 @@ var ManagedSettings = external_exports.object({
23869
24085
  // decision from a bug. Absent renders as a generic "your organization".
23870
24086
  organization: external_exports.string().min(1).optional(),
23871
24087
  // What the administrator pinned.
23872
- values: ManagedSettingsValues.default({}),
24088
+ //
24089
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24090
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24091
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24092
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24093
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24094
+ // exactly the file an administrator is most likely to write while a fleet
24095
+ // is mid-upgrade.
24096
+ //
24097
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24098
+ // file, which is the outcome the lock half already rejected — an older
24099
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24100
+ // value still fails, because the nested schema is re-run over the known
24101
+ // subset and its issues are re-raised on this parse.
24102
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23873
24103
  // Which of those the user may not change. A key here with no matching value
23874
24104
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23875
24105
  // the user may still override. The two are separable on purpose.
@@ -23882,17 +24112,31 @@ var ManagedSettings = external_exports.object({
23882
24112
  // the fleets most likely to carry a version skew. A name outside the enum
23883
24113
  // is still never HONOURED: the lockable set stays explicit above.
23884
24114
  lockedFields: external_exports.array(external_exports.string()).default([])
23885
- }).transform(({ lockedFields, ...rest }) => {
24115
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
23886
24116
  const known = [];
23887
24117
  const unknown2 = [];
23888
24118
  for (const name of lockedFields) {
23889
24119
  if (isManagedSettingKey(name)) known.push(name);
23890
24120
  else unknown2.push(name);
23891
24121
  }
24122
+ const knownValues = /* @__PURE__ */ Object.create(null);
24123
+ const unknownValues = [];
24124
+ for (const [name, value] of Object.entries(values)) {
24125
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24126
+ else unknownValues.push(name);
24127
+ }
24128
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24129
+ if (!pinned.success) {
24130
+ for (const issue2 of pinned.error.issues)
24131
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24132
+ return external_exports.NEVER;
24133
+ }
23892
24134
  return {
23893
24135
  ...rest,
24136
+ values: pinned.data,
23894
24137
  lockedFields: known,
23895
- ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
24138
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24139
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
23896
24140
  };
23897
24141
  }).meta({ id: "ManagedSettings" });
23898
24142
 
@@ -24156,7 +24400,23 @@ var SaveSettingsInput = external_exports.object({
24156
24400
  modelJudgeConsent: ModelJudgeConsentChoice,
24157
24401
  historySyncConsent: HistorySyncConsentChoice,
24158
24402
  vaultConsent: external_exports.string(),
24159
- vaultInlineReveal: external_exports.string()
24403
+ vaultInlineReveal: external_exports.string(),
24404
+ // Widened to `string` like its neighbours rather than typed as
24405
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24406
+ // the call site, so the domain check receives the type it was written for.
24407
+ //
24408
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24409
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24410
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24411
+ // trade against. The real cost runs the other way and is the part worth
24412
+ // knowing: a value this schema admits and the domain enum then rejects lands
24413
+ // on the action's shared refusal, which names NO field, where a shape
24414
+ // rejection reaches `malformedInput` and names the schema key.
24415
+ redactFallback: external_exports.string(),
24416
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24417
+ // `BodyRetention`'s and the action checks it there, so there is one place
24418
+ // that decides what a legal horizon is rather than two that can drift.
24419
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24160
24420
  });
24161
24421
  var AttachInput = external_exports.object({
24162
24422
  endpoint: external_exports.string(),
@@ -24328,6 +24588,52 @@ function reviewSeverityRank(reasons) {
24328
24588
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24329
24589
  }
24330
24590
 
24591
+ // ../../packages/schema/src/zod/web-capture.ts
24592
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24593
+ var WebUsage = external_exports.object({
24594
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24595
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24596
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24597
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24598
+ });
24599
+ var WebToolCall = external_exports.object({
24600
+ toolUseId: external_exports.string().min(1),
24601
+ toolName: external_exports.string().min(1),
24602
+ target: external_exports.string().optional(),
24603
+ isError: external_exports.boolean().optional(),
24604
+ inputSize: external_exports.number().int().nonnegative().optional(),
24605
+ outputSize: external_exports.number().int().nonnegative().optional()
24606
+ });
24607
+ var WebExchange = external_exports.object({
24608
+ messageId: external_exports.string().min(1),
24609
+ startedAt: external_exports.iso.datetime(),
24610
+ model: external_exports.string().optional(),
24611
+ usage: WebUsage.optional(),
24612
+ usageSource: WebUsageSource,
24613
+ stopReason: external_exports.string().optional(),
24614
+ conversationId: external_exports.string().optional(),
24615
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24616
+ toolCalls: external_exports.array(WebToolCall).default([]),
24617
+ // Absent when the adapter recovered no text. Capped by the caller at
24618
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24619
+ // short capture is never mistaken for a short reply.
24620
+ responseText: external_exports.string().optional(),
24621
+ truncated: external_exports.boolean().default(false)
24622
+ });
24623
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24624
+ var WebCaptureStatus = external_exports.object({
24625
+ patched: external_exports.boolean(),
24626
+ live: external_exports.boolean(),
24627
+ blind: external_exports.boolean(),
24628
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24629
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24630
+ parseFailures: external_exports.number().int().nonnegative(),
24631
+ unparsedBodies: external_exports.number().int().nonnegative(),
24632
+ // The adapter-declared JSON key paths that were absent from a real payload —
24633
+ // the earliest signal that a site's contract moved.
24634
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24635
+ });
24636
+
24331
24637
  // ../../packages/persistence/src/paths.ts
24332
24638
  import {
24333
24639
  chmodSync,
@@ -24658,6 +24964,22 @@ function discardStore(file2, backup) {
24658
24964
  }
24659
24965
  }
24660
24966
 
24967
+ // ../../packages/persistence/src/internal/sql-functions.ts
24968
+ var utf8 = new TextDecoder();
24969
+ function akaLower(value) {
24970
+ if (value === null) return null;
24971
+ if (typeof value === "string") return value.toLowerCase();
24972
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
24973
+ return utf8.decode(value).toLowerCase();
24974
+ }
24975
+ function registerSqlFunctions(db) {
24976
+ db.function(
24977
+ "aka_lower",
24978
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
24979
+ akaLower
24980
+ );
24981
+ }
24982
+
24661
24983
  // ../../packages/persistence/src/internal/sql-text.ts
24662
24984
  function escapeLikePattern(s) {
24663
24985
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24742,6 +25064,11 @@ function schemaObjectExists(db, kind, name) {
24742
25064
  function indexExists(db, name) {
24743
25065
  return schemaObjectExists(db, "index", name);
24744
25066
  }
25067
+ function indexColumns(db, name) {
25068
+ if (!indexExists(db, name)) return [];
25069
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25070
+ return columns.map((c) => c.name).filter((c) => c !== null);
25071
+ }
24745
25072
  function columnNames(db, table, opts) {
24746
25073
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24747
25074
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24803,177 +25130,819 @@ function mapRowsTolerant(rows, map2) {
24803
25130
  return out;
24804
25131
  }
24805
25132
 
24806
- // ../../packages/persistence/src/migrations.ts
24807
- function describeObject(object2) {
24808
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24809
- }
24810
- function splitStatements(sql) {
24811
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24812
- }
24813
- function createdIndexName(statement) {
24814
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24815
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25133
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25134
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25135
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25136
+
25137
+ // ../../packages/persistence/src/sync-failure.ts
25138
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25139
+ function syncFailureRejectCondition(column = "sync_failure") {
25140
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25141
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24816
25142
  }
24817
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24818
- function applyMigrations(db, file2) {
24819
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24820
- db.exec(
24821
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24822
- );
24823
- const applied = new Set(
24824
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24825
- );
24826
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24827
- const record2 = db.prepare(
24828
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24829
- );
24830
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24831
- if (applied.has(migration.tag)) continue;
24832
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24833
- const evidence = evidenceObjects(migration.sql);
24834
- const present = evidence.filter((o) => evidenceExists(db, o));
24835
- if (present.length > 0 && present.length < evidence.length) {
24836
- const missing = evidence.filter((o) => !present.includes(o));
24837
- 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.`;
24838
- akaWarn(message);
24839
- throw new Error(`[aka] ${message}`);
24840
- }
24841
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24842
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24843
- const statements = splitStatements(migration.sql);
24844
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24845
- try {
24846
- withTransaction(
24847
- db,
24848
- () => {
24849
- for (const statement of statements) {
24850
- const indexName = createdIndexName(statement);
24851
- if (indexName === void 0) {
24852
- if (alreadyApplied) continue;
24853
- } else if (indexExists(db, indexName)) {
24854
- continue;
24855
- }
24856
- db.exec(statement);
24857
- }
24858
- if (wantsFkOff && !alreadyApplied) {
24859
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24860
- if (violations.length > 0) {
24861
- throw new Error(
24862
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24863
- );
24864
- }
24865
- }
24866
- record2.run(migration.tag, Date.now());
24867
- },
24868
- "IMMEDIATE"
24869
- );
24870
- } finally {
24871
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24872
- }
25143
+
25144
+ // ../../packages/persistence/src/repositories/history-sync.ts
25145
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25146
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25147
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25148
+ var COUNTED_EVENT_TYPES = [
25149
+ ...STRUCTURAL_EVENT_TYPES,
25150
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25151
+ ];
25152
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25153
+ var PARTITION_BUCKETS = `
25154
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25155
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25156
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25157
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25158
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25159
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25160
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25161
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25162
+ -- added later lands in no bucket and fails the sum assertion, instead
25163
+ -- of silently joining this one.
25164
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25165
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25166
+ THEN 1 ELSE 0 END) AS failed,
25167
+ COUNT(*) AS total`;
25168
+ var COUNTED_SCOPE = `
25169
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25170
+ AND (
25171
+ event_type IN (${TYPE_LIST})
25172
+ OR synced_at IS NOT NULL
25173
+ OR outbox_owed = 1
25174
+ )`;
25175
+ var SKIPPED = -1;
25176
+ var ROW_COLUMNS = `id,
25177
+ parent_id AS parentId,
25178
+ root_session_id AS rootSessionId,
25179
+ event_type AS eventType,
25180
+ host_id AS hostId,
25181
+ harness_id AS harnessId,
25182
+ source_project_id AS sourceProjectId,
25183
+ started_at AS startedAt,
25184
+ ended_at AS endedAt,
25185
+ severity,
25186
+ priority,
25187
+ content,
25188
+ content_hash AS contentHash,
25189
+ attributes`;
25190
+ var SqliteHistorySyncRepository = class {
25191
+ constructor(db) {
25192
+ this.db = db;
25193
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25194
+ this.sessionsStmt = db.prepare(
25195
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25196
+ FROM audit_events
25197
+ WHERE synced_at IS NULL
25198
+ AND event_type IN (${TYPE_LIST})
25199
+ AND started_at < :before
25200
+ GROUP BY sessionId
25201
+ ORDER BY earliest
25202
+ LIMIT :limit`
25203
+ );
25204
+ this.rowsStmt = db.prepare(
25205
+ `SELECT ${ROW_COLUMNS}
25206
+ FROM audit_events
25207
+ WHERE synced_at IS NULL
25208
+ AND event_type IN (${TYPE_LIST})
25209
+ AND started_at < :before
25210
+ AND COALESCE(root_session_id, id) = :sessionId
25211
+ ORDER BY (event_type = 'session') DESC, started_at
25212
+ LIMIT :limit`
25213
+ );
25214
+ this.captureRowsStmt = db.prepare(
25215
+ `SELECT ${ROW_COLUMNS}
25216
+ FROM audit_events
25217
+ WHERE synced_at IS NULL
25218
+ AND sync_claimed_at IS NULL
25219
+ AND outbox_owed = 1
25220
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25221
+ AND started_at < :before
25222
+ ORDER BY started_at
25223
+ LIMIT :limit`
25224
+ );
25225
+ this.markOwedStmt = db.prepare(
25226
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25227
+ );
25228
+ this.markCaptureBacklogOwedStmt = db.prepare(
25229
+ `UPDATE audit_events SET outbox_owed = 1
25230
+ WHERE synced_at IS NULL
25231
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25232
+ AND started_at < :before`
25233
+ );
25234
+ this.stampStmt = db.prepare(
25235
+ `UPDATE audit_events
25236
+ SET synced_at = :at,
25237
+ sync_claimed_at = NULL,
25238
+ sync_failed_at = :failedAt,
25239
+ sync_failure = :failure
25240
+ WHERE id = :id`
25241
+ );
25242
+ this.claimRowStmt = db.prepare(
25243
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25244
+ );
25245
+ this.releaseRowStmt = db.prepare(
25246
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25247
+ );
25248
+ this.releaseStaleClaimsStmt = db.prepare(
25249
+ `UPDATE audit_events SET sync_claimed_at = NULL
25250
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25251
+ );
25252
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25253
+ FROM audit_events${COUNTED_SCOPE}`);
25254
+ this.partitionByKindStmt = db.prepare(
25255
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25256
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25257
+ GROUP BY event_type`
25258
+ );
25259
+ this.countsStmt = db.prepare(
25260
+ `SELECT
25261
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25262
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25263
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25264
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25265
+ THEN 1 ELSE 0 END) AS skipped,
25266
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25267
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25268
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25269
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25270
+ FROM audit_events
25271
+ WHERE event_type IN (${TYPE_LIST})`
25272
+ );
25273
+ this.captureSkipCountStmt = db.prepare(
25274
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25275
+ // way the structural totals are. The split exists because a refusal is
25276
+ // terminal only against the deployment that gave it, and the structural
25277
+ // re-arm frees it on a change of deployment. The capture lane has no such
25278
+ // escape: re-arming a capture would offer one deployment's undelivered
25279
+ // prompts, with their text, to a deployment that never saw them, which is
25280
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25281
+ // reasons mean the same thing — this row will not be sent — and splitting
25282
+ // them would put refused captures in a bucket nothing reads and nothing
25283
+ // frees.
25284
+ `SELECT COUNT(*) AS skipped
25285
+ FROM audit_events
25286
+ WHERE synced_at = ${String(SKIPPED)}
25287
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25288
+ );
25289
+ this.fingerprintStmt = db.prepare(
25290
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25291
+ FROM history_sync WHERE id = 1`
25292
+ );
25293
+ this.setFingerprintStmt = db.prepare(
25294
+ `UPDATE history_sync
25295
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25296
+ WHERE id = 1`
25297
+ );
25298
+ this.disownCapturesStmt = db.prepare(
25299
+ `UPDATE audit_events SET outbox_owed = NULL
25300
+ WHERE outbox_owed IS NOT NULL
25301
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25302
+ AND started_at < :attachedAt`
25303
+ );
25304
+ this.rearmStmt = db.prepare(
25305
+ `UPDATE audit_events
25306
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25307
+ WHERE (synced_at > 0
25308
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25309
+ AND event_type IN (${TYPE_LIST})`
25310
+ );
25311
+ this.claimStmt = db.prepare(
25312
+ `UPDATE history_sync
25313
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25314
+ WHERE id = 1
25315
+ AND (owner_pid IS NULL
25316
+ OR heartbeat_at IS NULL
25317
+ OR heartbeat_at < :staleBefore
25318
+ OR heartbeat_at > :now)`
25319
+ );
25320
+ this.heartbeatStmt = db.prepare(
25321
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25322
+ );
25323
+ this.releaseStmt = db.prepare(
25324
+ `UPDATE history_sync
25325
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25326
+ WHERE id = 1 AND owner_pid = :pid`
25327
+ );
25328
+ this.closeWindowStmt = db.prepare(
25329
+ `UPDATE audit_events
25330
+ SET synced_at = ${String(SKIPPED)},
25331
+ sync_failed_at = :at,
25332
+ sync_failure = 'detached_undelivered'
25333
+ WHERE synced_at IS NULL
25334
+ AND event_type IN (${TYPE_LIST})
25335
+ AND started_at >= :attachedAt`
25336
+ );
25337
+ this.releaseBoundaryStmt = db.prepare(
25338
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25339
+ );
25340
+ this.freezeBoundaryStmt = db.prepare(
25341
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25342
+ );
25343
+ this.leaseStmt = db.prepare(
25344
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25345
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25346
+ FROM history_sync WHERE id = 1`
25347
+ );
25348
+ this.inspectionsStmt = db.prepare(
25349
+ `SELECT d.rule_id AS ruleId,
25350
+ d.name AS ruleName,
25351
+ d.version AS ruleVersion,
25352
+ d.category AS category,
25353
+ d.severity AS severity,
25354
+ f.span_start AS spanStart,
25355
+ f.span_end AS spanEnd,
25356
+ f.masked_match AS maskedMatch,
25357
+ f.action_taken AS actionTaken,
25358
+ f.confidence AS confidence
25359
+ FROM inspection_findings f
25360
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25361
+ WHERE f.audit_event_id = :auditEventId
25362
+ ORDER BY f.span_start, f.id`
25363
+ );
24873
25364
  }
24874
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24875
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25365
+ db;
25366
+ ensureRowStmt;
25367
+ sessionsStmt;
25368
+ rowsStmt;
25369
+ stampStmt;
25370
+ countsStmt;
25371
+ fingerprintStmt;
25372
+ setFingerprintStmt;
25373
+ rearmStmt;
25374
+ claimStmt;
25375
+ heartbeatStmt;
25376
+ releaseStmt;
25377
+ leaseStmt;
25378
+ inspectionsStmt;
25379
+ closeWindowStmt;
25380
+ releaseBoundaryStmt;
25381
+ freezeBoundaryStmt;
25382
+ captureRowsStmt;
25383
+ markOwedStmt;
25384
+ markCaptureBacklogOwedStmt;
25385
+ captureSkipCountStmt;
25386
+ disownCapturesStmt;
25387
+ partitionStmt;
25388
+ partitionByKindStmt;
25389
+ claimRowStmt;
25390
+ releaseRowStmt;
25391
+ releaseStaleClaimsStmt;
25392
+ /**
25393
+ * The masked detections recorded against one tool call.
25394
+ *
25395
+ * These travel with the event because a tool call's target is not
25396
+ * re-inspectable from the event alone — unlike a capture, where the text
25397
+ * itself is re-scannable. What crosses is the masked match and the rule that
25398
+ * produced it, never the value.
25399
+ */
25400
+ inspectionsFor(auditEventId) {
25401
+ return allRows(this.inspectionsStmt, { auditEventId });
24876
25402
  }
24877
- ensureSyncedAtColumn(db, "audit_events");
24878
- ensureScanLedgerTable(db);
24879
- ensureHistorySyncTable(db);
24880
- ensureBlockedDetectionsTable(db);
24881
- ensureRuleProbeCacheTable(db);
24882
- ensureWriteGateTrigger(db);
24883
- ensureTokenUsageColumns(db);
24884
- reconcileSourceProjectIds(db);
24885
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24886
- const drained = runLegacyHistoryBackfill(db);
24887
- if (drained) applyLegacyDropMigration(db, file2);
25403
+ /**
25404
+ * Sessions with structural rows still to send, oldest first.
25405
+ *
25406
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25407
+ * read. Anything recorded after the machine attached is the live forward
25408
+ * path's to deliver; this drain exists for what was recorded before it, and a
25409
+ * row both paths send is at best a duplicate request and at worst — for a
25410
+ * session root — an overwrite of the inventory ids the live path resolved.
25411
+ */
25412
+ pendingSessions(limit, before) {
25413
+ return allRows(this.sessionsStmt, { limit, before }).map(
25414
+ (r) => r.sessionId
25415
+ );
24888
25416
  }
24889
- }
24890
- function readLegacyTables(db) {
24891
- let holdsRows = false;
24892
- const marks = [];
24893
- for (const table of ["events", "findings"]) {
24894
- try {
24895
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
24896
- if (row === void 0) {
24897
- holdsRows = true;
24898
- marks.push(`${table}:unreadable`);
24899
- continue;
24900
- }
24901
- if (row.n > 0) holdsRows = true;
24902
- marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
24903
- } catch {
24904
- holdsRows = true;
24905
- marks.push(`${table}:unreadable`);
24906
- }
25417
+ /** One session's undelivered structural rows within the backlog, root first. */
25418
+ pendingRows(sessionId, limit, before) {
25419
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24907
25420
  }
24908
- return { holdsRows, mark: marks.join("|") };
24909
- }
24910
- function applyLegacyDropMigration(db, file2) {
24911
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24912
- if (!migration) return;
24913
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24914
- if (file2 !== void 0 && before?.holdsRows === true) {
24915
- try {
24916
- backupBeforeLegacyDrop(db, file2);
24917
- } catch (error61) {
24918
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24919
- return;
24920
- }
25421
+ /**
25422
+ * Captures this machine still owes the deployment, oldest first.
25423
+ *
25424
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25425
+ * by a time window — see captureRowsStmt for why a window could not express
25426
+ * this. `before` is the grace window that leaves a just-recorded capture to
25427
+ * the live path.
25428
+ */
25429
+ pendingCaptureRows(limit, before) {
25430
+ return allRows(this.captureRowsStmt, { limit, before });
24921
25431
  }
24922
- try {
25432
+ /**
25433
+ * Record that a capture is OWED to the deployment.
25434
+ *
25435
+ * Written by the attached forward path when a live send did not confirm
25436
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25437
+ * a fact rather than an inference: the machine was attached, the send did not
25438
+ * land, so the row is owed — which no time window can state, because the same
25439
+ * window that holds the rows a past attachment left owed also holds every
25440
+ * capture recorded while the machine was DETACHED, and those were never
25441
+ * offered to anyone.
25442
+ *
25443
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25444
+ * out of the drain's read.
25445
+ */
25446
+ markCaptureOwed(id) {
25447
+ this.markOwedStmt.run({ id });
25448
+ }
25449
+ /**
25450
+ * Mark every capture already on disk as owed, as of `before`.
25451
+ *
25452
+ * The consent-time backfill, called once from `aka attach` when a human
25453
+ * grants existing-history consent — never from an ongoing drain pass, and
25454
+ * never inferred from a boundary that could later move. `before` is the
25455
+ * caller's own "now" at the moment consent was granted, so what this marks
25456
+ * is exactly the backlog the consent prompt already counted, not whatever a
25457
+ * later re-attach or key rotation might widen it to.
25458
+ *
25459
+ * Returns how many rows matched, for the caller to log or test against. Not a
25460
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25461
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25462
+ */
25463
+ markCaptureBacklogOwed(before) {
25464
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25465
+ }
25466
+ /**
25467
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25468
+ *
25469
+ * CLEARS any failure reason in the same statement. A row that failed against
25470
+ * one deployment and then landed is delivered, and leaving the reason behind
25471
+ * would leave the store holding two contradictory answers about one row —
25472
+ * with the surface free to render either.
25473
+ */
25474
+ markSynced(ids, atMs) {
25475
+ this.stampAll(ids, atMs, null);
25476
+ }
25477
+ /**
25478
+ * Record that THIS MACHINE cannot express the row on the wire.
25479
+ *
25480
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25481
+ * payload, or a body the client itself refused to send. It fails identically
25482
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25483
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25484
+ * is retried; marking those would turn one outage into permanent data loss.
25485
+ */
25486
+ markSkipped(ids, atMs) {
25487
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25488
+ }
25489
+ /**
25490
+ * Record that THIS DEPLOYMENT refused the row.
25491
+ *
25492
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25493
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25494
+ * row is outstanding rather than why. What separates them is the reason, and
25495
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25496
+ * on one body, so it is terminal only for as long as this machine points at
25497
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25498
+ *
25499
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25500
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25501
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25502
+ */
25503
+ markRefused(ids, atMs) {
25504
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25505
+ }
25506
+ eachInTransaction(ids, run) {
25507
+ if (ids.length === 0) return;
24923
25508
  withTransaction(
24924
- db,
25509
+ this.db,
24925
25510
  () => {
24926
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24927
- if (alreadyDropped) return;
24928
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24929
- akaWarn(
24930
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24931
- );
24932
- return;
24933
- }
24934
- for (const statement of splitStatements(migration.sql)) {
24935
- db.exec(statement);
24936
- }
24937
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
24938
- migration.tag,
24939
- Date.now()
24940
- );
25511
+ for (const id of ids) run(id);
24941
25512
  },
24942
25513
  "IMMEDIATE"
24943
25514
  );
24944
- } catch (error61) {
24945
- akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
24946
25515
  }
24947
- }
24948
- function backupBeforeLegacyDrop(db, file2) {
24949
- reapStalePartials(file2);
24950
- const backup = backupPath(file2, "pre-drop");
24951
- snapshotStore(db, backup);
24952
- return backup;
24953
- }
24954
- var TOKEN_USAGE_COLUMNS = [
24955
- {
24956
- name: "input_tokens",
24957
- ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
24958
- },
24959
- {
24960
- name: "output_tokens",
24961
- ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
24962
- },
24963
- {
24964
- name: "cache_creation_input_tokens",
24965
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
24966
- },
24967
- {
24968
- name: "cache_read_input_tokens",
24969
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
24970
- },
24971
- {
24972
- name: "model",
24973
- ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
24974
- },
24975
- {
24976
- name: "provider",
25516
+ stampAll(ids, value, failure, failedAtMs) {
25517
+ if (ids.length === 0) return;
25518
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25519
+ withTransaction(
25520
+ this.db,
25521
+ () => {
25522
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25523
+ },
25524
+ "IMMEDIATE"
25525
+ );
25526
+ }
25527
+ /**
25528
+ * Claim rows as in-flight.
25529
+ *
25530
+ * Advisory in exactly the sense the lease is: it records that a send is in
25531
+ * progress so a surface can say so, and a lost claim costs a row showing as
25532
+ * queued while it is actually being sent. It is not exclusion — the far side
25533
+ * settles a duplicate on the row id.
25534
+ */
25535
+ claimRows(ids, atMs) {
25536
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25537
+ }
25538
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25539
+ releaseRows(ids) {
25540
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25541
+ }
25542
+ /**
25543
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25544
+ *
25545
+ * A process killed between claiming and settling leaves rows claimed with
25546
+ * nothing left to settle them. Without this they read as "sending" for ever.
25547
+ */
25548
+ releaseStaleClaims(staleBefore) {
25549
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25550
+ }
25551
+ /**
25552
+ * Every tracked row in exactly one delivery state.
25553
+ *
25554
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25555
+ * pick up now", which is a different question from "what state is this row
25556
+ * in" — and a machine that has never attached has no boundary to pass, so
25557
+ * requiring one would force a caller to invent one and report the whole store
25558
+ * as queued.
25559
+ */
25560
+ /**
25561
+ * The same partition, one row per kind that a lane carries.
25562
+ *
25563
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25564
+ * scope decides which rows exist at all, so a kind that has never been
25565
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25566
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25567
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25568
+ * different things.
25569
+ */
25570
+ partitionByKind() {
25571
+ return allRows(
25572
+ this.partitionByKindStmt,
25573
+ {}
25574
+ ).map((row) => ({
25575
+ kind: row.kind,
25576
+ queued: row.queued ?? 0,
25577
+ inProgress: row.inProgress ?? 0,
25578
+ synced: row.synced ?? 0,
25579
+ failed: row.failed ?? 0,
25580
+ refused: row.refused ?? 0,
25581
+ detached: row.detached ?? 0,
25582
+ total: row.total ?? 0
25583
+ }));
25584
+ }
25585
+ partition() {
25586
+ const row = getRow(this.partitionStmt, {});
25587
+ return {
25588
+ queued: row?.queued ?? 0,
25589
+ inProgress: row?.inProgress ?? 0,
25590
+ synced: row?.synced ?? 0,
25591
+ failed: row?.failed ?? 0,
25592
+ refused: row?.refused ?? 0,
25593
+ detached: row?.detached ?? 0,
25594
+ total: row?.total ?? 0
25595
+ };
25596
+ }
25597
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25598
+ counts(before) {
25599
+ const row = getRow(this.countsStmt, { before });
25600
+ const captures = getRow(this.captureSkipCountStmt);
25601
+ return {
25602
+ pending: row?.pending ?? 0,
25603
+ sent: row?.sent ?? 0,
25604
+ skipped: row?.skipped ?? 0,
25605
+ refused: row?.refused ?? 0,
25606
+ detached: row?.detached ?? 0,
25607
+ capturesSkipped: captures?.skipped ?? 0
25608
+ };
25609
+ }
25610
+ /**
25611
+ * The deployment the current stamps were made against, and where its backlog
25612
+ * ends.
25613
+ *
25614
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25615
+ * machine that has never drained is — and every writer below seeds the row
25616
+ * before it needs one, so nothing depends on this creating it. Keeping the
25617
+ * write off the gate path matters because the gate runs on every pass while a
25618
+ * write has to take the database's write lock.
25619
+ */
25620
+ deployment() {
25621
+ const row = getRow(
25622
+ this.fingerprintStmt
25623
+ );
25624
+ return {
25625
+ fingerprint: row?.fingerprint ?? void 0,
25626
+ backlogBefore: row?.backlogBefore ?? void 0
25627
+ };
25628
+ }
25629
+ /**
25630
+ * Point the ledger at a different deployment, discarding what it recorded
25631
+ * about the previous one.
25632
+ *
25633
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25634
+ * machine has just left are undelivered as far as the new one is concerned.
25635
+ * All four in one transaction, so a crash between them cannot leave stamps
25636
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25637
+ * a disown with no re-mark to follow it.
25638
+ *
25639
+ * The boundary is written HERE and only here, which is what freezes it: a
25640
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25641
+ * unchanged, so this never runs and the backlog does not widen back over rows
25642
+ * the live path has since delivered.
25643
+ *
25644
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25645
+ * granted existing-history consent for the deployment this call is arming —
25646
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25647
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25648
+ * apart. Passed only when that grant is valid, since this method has no way
25649
+ * to check consent itself and must not mark a row owed for a machine that
25650
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25651
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25652
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25653
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25654
+ * on the cleared side of that bound — and the re-mark in the same
25655
+ * transaction is what puts those rows back. A crash between the two cannot
25656
+ * strand the ledger disowned with nothing re-marked — the transaction either
25657
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25658
+ * committed re-enters this method on the very next pass. Omit it (the
25659
+ * structural-only tests do) to exercise the disown in isolation.
25660
+ *
25661
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25662
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25663
+ * live path can mark a capture owed from the moment `aka attach` writes the
25664
+ * descriptor, before the drain's first pass ever reaches this method, and
25665
+ * such a row sits at or after the bound rather than below it. What keeps the
25666
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25667
+ * bound — disown runs first, re-mark second, both inside the one
25668
+ * transaction above.
25669
+ */
25670
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25671
+ this.ensureRowStmt.run();
25672
+ withTransaction(
25673
+ this.db,
25674
+ () => {
25675
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25676
+ this.rearmStmt.run();
25677
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25678
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25679
+ }
25680
+ if (backfillCapturesBefore !== void 0) {
25681
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25682
+ }
25683
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25684
+ },
25685
+ "IMMEDIATE"
25686
+ );
25687
+ }
25688
+ /**
25689
+ * End the attached period: hand its rows to the live path, and release the
25690
+ * boundary so the next attachment can freeze a new one.
25691
+ *
25692
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25693
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25694
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25695
+ * during the detached period, because the machine is not attached. Rows
25696
+ * recorded in that window sit after the boundary and before the re-attach, so
25697
+ * neither path takes them, and the pending count reports none outstanding.
25698
+ *
25699
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25700
+ * closing attachment's to deliver and are no longer outstanding — that is what
25701
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25702
+ * distinction is not academic: this used to write a delivery TIME, which every
25703
+ * read treats as delivery, so one detach turned a window of undelivered rows
25704
+ * into a window of delivered ones and no surface could tell. It writes the
25705
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25706
+ * "received" stop being the same fact.
25707
+ *
25708
+ * A change of deployment still frees them (see the re-arm), because the next
25709
+ * deployment has seen none of this machine's history — so the rows reach it
25710
+ * exactly as they did when this wrote a delivery time.
25711
+ *
25712
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25713
+ * window unstamped — that half-state would re-send the whole attached period
25714
+ * on the next attach, which is the failure the boundary exists to prevent.
25715
+ */
25716
+ closeAttachedWindow(attachedAtMs, atMs) {
25717
+ this.ensureRowStmt.run();
25718
+ withTransaction(
25719
+ this.db,
25720
+ () => {
25721
+ const row = getRow(this.fingerprintStmt);
25722
+ const from = row?.backlogBefore ?? attachedAtMs;
25723
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25724
+ this.releaseBoundaryStmt.run();
25725
+ },
25726
+ "IMMEDIATE"
25727
+ );
25728
+ }
25729
+ /**
25730
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25731
+ *
25732
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25733
+ * different deployment and therefore discards what was delivered to the old
25734
+ * one: here the recipient is the same, so everything already sent to it stays
25735
+ * sent.
25736
+ */
25737
+ freezeBoundary(backlogBefore) {
25738
+ this.ensureRowStmt.run();
25739
+ this.freezeBoundaryStmt.run({ backlogBefore });
25740
+ }
25741
+ /** Take the claim, or report that someone live already holds it. */
25742
+ claim(pid, host, nowMs, staleAfterMs) {
25743
+ this.ensureRowStmt.run();
25744
+ let taken = false;
25745
+ withTransaction(
25746
+ this.db,
25747
+ () => {
25748
+ const result = this.claimStmt.run({
25749
+ pid,
25750
+ host,
25751
+ now: nowMs,
25752
+ staleBefore: nowMs - staleAfterMs
25753
+ });
25754
+ taken = result.changes === 1;
25755
+ },
25756
+ "IMMEDIATE"
25757
+ );
25758
+ return taken;
25759
+ }
25760
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25761
+ heartbeat(pid, nowMs) {
25762
+ this.heartbeatStmt.run({ now: nowMs, pid });
25763
+ }
25764
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25765
+ release(pid) {
25766
+ this.releaseStmt.run({ pid });
25767
+ }
25768
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25769
+ lease() {
25770
+ return getRow(this.leaseStmt);
25771
+ }
25772
+ };
25773
+
25774
+ // ../../packages/persistence/src/migrations.ts
25775
+ function describeObject(object2) {
25776
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25777
+ }
25778
+ function splitStatements(sql) {
25779
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25780
+ }
25781
+ function createdIndexName(statement) {
25782
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25783
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25784
+ }
25785
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25786
+ function applyMigrations(db, file2, options = {}) {
25787
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25788
+ db.exec(
25789
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25790
+ );
25791
+ const applied = new Set(
25792
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25793
+ );
25794
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25795
+ const record2 = db.prepare(
25796
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25797
+ );
25798
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25799
+ if (applied.has(migration.tag)) continue;
25800
+ if (options.skipTags?.has(migration.tag) === true) continue;
25801
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25802
+ const evidence = evidenceObjects(migration.sql);
25803
+ const present = evidence.filter((o) => evidenceExists(db, o));
25804
+ if (present.length > 0 && present.length < evidence.length) {
25805
+ const missing = evidence.filter((o) => !present.includes(o));
25806
+ 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.`;
25807
+ akaWarn(message);
25808
+ throw new Error(`[aka] ${message}`);
25809
+ }
25810
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25811
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25812
+ const statements = splitStatements(migration.sql);
25813
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25814
+ try {
25815
+ withTransaction(
25816
+ db,
25817
+ () => {
25818
+ for (const statement of statements) {
25819
+ const indexName = createdIndexName(statement);
25820
+ if (indexName === void 0) {
25821
+ if (alreadyApplied) continue;
25822
+ } else if (indexExists(db, indexName)) {
25823
+ continue;
25824
+ }
25825
+ db.exec(statement);
25826
+ }
25827
+ if (wantsFkOff && !alreadyApplied) {
25828
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25829
+ if (violations.length > 0) {
25830
+ throw new Error(
25831
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25832
+ );
25833
+ }
25834
+ }
25835
+ record2.run(migration.tag, Date.now());
25836
+ },
25837
+ "IMMEDIATE"
25838
+ );
25839
+ } finally {
25840
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25841
+ }
25842
+ }
25843
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25844
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25845
+ }
25846
+ ensureSyncedAtColumn(db, "audit_events");
25847
+ ensureScanLedgerTable(db);
25848
+ ensureHistorySyncTable(db);
25849
+ ensureBlockedDetectionsTable(db);
25850
+ ensureRuleProbeCacheTable(db);
25851
+ ensureWriteGateTrigger(db);
25852
+ ensureTokenUsageColumns(db);
25853
+ reconcileSourceProjectIds(db);
25854
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25855
+ const drained = runLegacyHistoryBackfill(db);
25856
+ if (drained) applyLegacyDropMigration(db, file2);
25857
+ }
25858
+ }
25859
+ function readLegacyTables(db) {
25860
+ let holdsRows = false;
25861
+ const marks = [];
25862
+ for (const table of ["events", "findings"]) {
25863
+ try {
25864
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
25865
+ if (row === void 0) {
25866
+ holdsRows = true;
25867
+ marks.push(`${table}:unreadable`);
25868
+ continue;
25869
+ }
25870
+ if (row.n > 0) holdsRows = true;
25871
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
25872
+ } catch {
25873
+ holdsRows = true;
25874
+ marks.push(`${table}:unreadable`);
25875
+ }
25876
+ }
25877
+ return { holdsRows, mark: marks.join("|") };
25878
+ }
25879
+ function applyLegacyDropMigration(db, file2) {
25880
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25881
+ if (!migration) return;
25882
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25883
+ if (file2 !== void 0 && before?.holdsRows === true) {
25884
+ try {
25885
+ backupBeforeLegacyDrop(db, file2);
25886
+ } catch (error61) {
25887
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25888
+ return;
25889
+ }
25890
+ }
25891
+ try {
25892
+ withTransaction(
25893
+ db,
25894
+ () => {
25895
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25896
+ if (alreadyDropped) return;
25897
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25898
+ akaWarn(
25899
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25900
+ );
25901
+ return;
25902
+ }
25903
+ for (const statement of splitStatements(migration.sql)) {
25904
+ db.exec(statement);
25905
+ }
25906
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25907
+ migration.tag,
25908
+ Date.now()
25909
+ );
25910
+ },
25911
+ "IMMEDIATE"
25912
+ );
25913
+ } catch (error61) {
25914
+ akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
25915
+ }
25916
+ }
25917
+ function backupBeforeLegacyDrop(db, file2) {
25918
+ reapStalePartials(file2);
25919
+ const backup = backupPath(file2, "pre-drop");
25920
+ snapshotStore(db, backup);
25921
+ return backup;
25922
+ }
25923
+ var TOKEN_USAGE_COLUMNS = [
25924
+ {
25925
+ name: "input_tokens",
25926
+ ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
25927
+ },
25928
+ {
25929
+ name: "output_tokens",
25930
+ ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
25931
+ },
25932
+ {
25933
+ name: "cache_creation_input_tokens",
25934
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
25935
+ },
25936
+ {
25937
+ name: "cache_read_input_tokens",
25938
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
25939
+ },
25940
+ {
25941
+ name: "model",
25942
+ ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25943
+ },
25944
+ {
25945
+ name: "provider",
24977
25946
  ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
24978
25947
  }
24979
25948
  ];
@@ -25235,10 +26204,62 @@ function ensureSyncedAtColumn(db, table) {
25235
26204
  if (!columns.includes("outbox_owed")) {
25236
26205
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25237
26206
  }
26207
+ if (!columns.includes("sync_failed_at")) {
26208
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26209
+ }
26210
+ if (!columns.includes("sync_failure")) {
26211
+ withTransaction(
26212
+ db,
26213
+ () => {
26214
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26215
+ db.exec(
26216
+ `UPDATE ${table} SET synced_at = NULL
26217
+ WHERE synced_at = -1
26218
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26219
+ );
26220
+ },
26221
+ "IMMEDIATE"
26222
+ );
26223
+ }
25238
26224
  db.exec(
25239
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25240
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26225
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26226
+ BEFORE UPDATE OF sync_failure ON ${table}
26227
+ WHEN ${syncFailureRejectCondition()}
26228
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25241
26229
  );
26230
+ const syncIndexColumns = [
26231
+ "event_type",
26232
+ "synced_at",
26233
+ "sync_claimed_at",
26234
+ "started_at",
26235
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26236
+ // has to be in the index for the read to stay covered — but putting it
26237
+ // ahead of `started_at` would reorder the prefix the structural drain's
26238
+ // reads match on.
26239
+ "sync_failure"
26240
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26241
+ //
26242
+ // The delivery-state read tests it — a capture's state depends on whether a
26243
+ // live forward marked it owed — so carrying it here makes that read covering
26244
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26245
+ // But a sixth column changes what the planner charges for this index, and
26246
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26247
+ // then stops choosing the per-session index for the token rollup and walks
26248
+ // every `llm_call` in the store through the event-type index instead. That
26249
+ // read grows with the store; this one does not.
26250
+ //
26251
+ // 40 ms on the largest store measured, once per render, is a cost worth
26252
+ // paying to leave every other read's plan where it was.
26253
+ ];
26254
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26255
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26256
+ if (!syncIndexMatches) {
26257
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26258
+ db.exec(
26259
+ `CREATE INDEX idx_audit_events_sync
26260
+ ON audit_events (${syncIndexColumns.join(", ")})`
26261
+ );
26262
+ }
25242
26263
  db.exec(
25243
26264
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25244
26265
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25460,7 +26481,11 @@ function buildAuditEvent(row) {
25460
26481
  link: linkParsed?.success ? linkParsed.data : null,
25461
26482
  targetId: row.target_id,
25462
26483
  internal: intToBool(row.internal),
25463
- flagged: intToBool(row.flagged)
26484
+ flagged: intToBool(row.flagged),
26485
+ // Only meaningful when the title came out empty — a row whose body was
26486
+ // expired but whose title fell back to `tool_name` still has something to
26487
+ // render, and flagging it would make the view apologise for nothing.
26488
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25464
26489
  };
25465
26490
  }
25466
26491
  var TIMELINE_COLUMNS = `
@@ -25468,6 +26493,7 @@ var TIMELINE_COLUMNS = `
25468
26493
  event_type,
25469
26494
  started_at,
25470
26495
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26496
+ content_expired_at,
25471
26497
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25472
26498
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25473
26499
  json_extract(attributes, '$.severity') AS severity,
@@ -26133,6 +27159,88 @@ var SqliteAuditEventsRepository = class {
26133
27159
  }
26134
27160
  };
26135
27161
 
27162
+ // ../../packages/persistence/src/repositories/body-retention.ts
27163
+ var DEFAULT_BATCH_SIZE = 500;
27164
+ var DEFAULT_MAX_ROWS = 5e4;
27165
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27166
+ var SqliteBodyRetentionRepository = class {
27167
+ constructor(db) {
27168
+ this.db = db;
27169
+ const select = (laneClause) => `
27170
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27171
+ FROM audit_events
27172
+ WHERE content IS NOT NULL
27173
+ AND started_at < :cutoff
27174
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27175
+ ${laneClause}
27176
+ ORDER BY started_at
27177
+ LIMIT :limit`;
27178
+ this.candidatesStmt = this.db.prepare(select(""));
27179
+ this.candidatesSyncSafeStmt = this.db.prepare(
27180
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27181
+ );
27182
+ this.heldBySyncStmt = this.db.prepare(`
27183
+ SELECT COUNT(*) AS n
27184
+ FROM audit_events
27185
+ WHERE content IS NOT NULL
27186
+ AND started_at < :cutoff
27187
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27188
+ AND synced_at IS NULL`);
27189
+ this.expireStmt = this.db.prepare(
27190
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27191
+ );
27192
+ }
27193
+ db;
27194
+ candidatesStmt;
27195
+ candidatesSyncSafeStmt;
27196
+ heldBySyncStmt;
27197
+ expireStmt;
27198
+ /** How many bytes a pass with these options would free, changing nothing. */
27199
+ preview(opts) {
27200
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27201
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27202
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27203
+ return {
27204
+ rowsExpired: rows.length,
27205
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27206
+ rowsHeldBySync: this.countHeldBySync(opts)
27207
+ };
27208
+ }
27209
+ /** Clear eligible bodies, in bounded batches. */
27210
+ expire(opts) {
27211
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27212
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27213
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27214
+ let rowsExpired = 0;
27215
+ let bytesFreed = 0;
27216
+ let done = true;
27217
+ while (rowsExpired < maxRows) {
27218
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27219
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27220
+ if (batch.length === 0) break;
27221
+ withTransaction(
27222
+ this.db,
27223
+ () => {
27224
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27225
+ },
27226
+ "IMMEDIATE"
27227
+ );
27228
+ rowsExpired += batch.length;
27229
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27230
+ if (batch.length < remaining) break;
27231
+ if (rowsExpired >= maxRows) {
27232
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27233
+ }
27234
+ }
27235
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27236
+ }
27237
+ countHeldBySync(opts) {
27238
+ if (opts.sweepSyncLane) return 0;
27239
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27240
+ return row.n;
27241
+ }
27242
+ };
27243
+
26136
27244
  // ../../packages/persistence/src/repositories/classified-data.ts
26137
27245
  var SqliteClassifiedDataRepository = class {
26138
27246
  constructor(db) {
@@ -26961,7 +28069,15 @@ function toFlatFindingRow(r) {
26961
28069
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26962
28070
  eventId: r.event_id,
26963
28071
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26964
- status: deriveInstanceStatus(r)
28072
+ status: deriveInstanceStatus(r),
28073
+ delivery: deriveFindingDelivery({
28074
+ kind: r.kind,
28075
+ syncedAt: r.synced_at,
28076
+ syncClaimedAt: r.sync_claimed_at,
28077
+ syncFailedAt: r.sync_failed_at,
28078
+ syncFailure: r.sync_failure,
28079
+ outboxOwed: r.outbox_owed
28080
+ })
26965
28081
  };
26966
28082
  }
26967
28083
  function encodeGroupCursor(group) {
@@ -27025,7 +28141,10 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
27025
28141
  e.tool_name AS tool_name,
27026
28142
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
27027
28143
  e.event_type AS kind, f.finding_key AS finding_key,
27028
- ${latestResolutionStatusSql("f")} AS latest_status`;
28144
+ ${latestResolutionStatusSql("f")} AS latest_status,
28145
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28146
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28147
+ e.outbox_owed AS outbox_owed`;
27029
28148
  var DAY_MS3 = 864e5;
27030
28149
  var SqliteFindingsRepository = class {
27031
28150
  constructor(db) {
@@ -27270,6 +28389,7 @@ var SqliteFindingsRepository = class {
27270
28389
  providers: query.provider,
27271
28390
  actions: query.action,
27272
28391
  statuses: query.status,
28392
+ deliveries: query.deployment,
27273
28393
  tools: query.tool,
27274
28394
  repo: query.repo,
27275
28395
  file: query.file,
@@ -27337,6 +28457,7 @@ var SqliteFindingsRepository = class {
27337
28457
  providers: query.provider,
27338
28458
  actions: query.action,
27339
28459
  statuses: query.status,
28460
+ deliveries: query.deployment,
27340
28461
  tools: query.tool,
27341
28462
  q: query.q
27342
28463
  };
@@ -27600,7 +28721,9 @@ var SqliteFindingsRepository = class {
27600
28721
  )
27601
28722
  );
27602
28723
  for (const row of grouped) {
27603
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28724
+ if (Object.hasOwn(byAction, row.action_taken)) {
28725
+ byAction[row.action_taken] = row.c;
28726
+ }
27604
28727
  }
27605
28728
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27606
28729
  const sevRows = allRows(
@@ -27617,7 +28740,9 @@ var SqliteFindingsRepository = class {
27617
28740
  )
27618
28741
  );
27619
28742
  for (const row of sevRows) {
27620
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28743
+ if (Object.hasOwn(bySeverity, row.severity)) {
28744
+ bySeverity[row.severity] = row.c;
28745
+ }
27621
28746
  }
27622
28747
  const categories = ENFORCEABLE_CATEGORIES;
27623
28748
  const enabledRows = allRows(
@@ -27666,525 +28791,6 @@ function isoDay(ms) {
27666
28791
  return new Date(ms).toISOString().slice(0, 10);
27667
28792
  }
27668
28793
 
27669
- // ../../packages/persistence/src/repositories/history-sync.ts
27670
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27671
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27672
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27673
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27674
- var SKIPPED = -1;
27675
- var ROW_COLUMNS = `id,
27676
- parent_id AS parentId,
27677
- root_session_id AS rootSessionId,
27678
- event_type AS eventType,
27679
- host_id AS hostId,
27680
- harness_id AS harnessId,
27681
- source_project_id AS sourceProjectId,
27682
- started_at AS startedAt,
27683
- ended_at AS endedAt,
27684
- severity,
27685
- priority,
27686
- content,
27687
- content_hash AS contentHash,
27688
- attributes`;
27689
- var SqliteHistorySyncRepository = class {
27690
- constructor(db) {
27691
- this.db = db;
27692
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27693
- this.sessionsStmt = db.prepare(
27694
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27695
- FROM audit_events
27696
- WHERE synced_at IS NULL
27697
- AND event_type IN (${TYPE_LIST})
27698
- AND started_at < :before
27699
- GROUP BY sessionId
27700
- ORDER BY earliest
27701
- LIMIT :limit`
27702
- );
27703
- this.rowsStmt = db.prepare(
27704
- `SELECT ${ROW_COLUMNS}
27705
- FROM audit_events
27706
- WHERE synced_at IS NULL
27707
- AND event_type IN (${TYPE_LIST})
27708
- AND started_at < :before
27709
- AND COALESCE(root_session_id, id) = :sessionId
27710
- ORDER BY (event_type = 'session') DESC, started_at
27711
- LIMIT :limit`
27712
- );
27713
- this.captureRowsStmt = db.prepare(
27714
- `SELECT ${ROW_COLUMNS}
27715
- FROM audit_events
27716
- WHERE synced_at IS NULL
27717
- AND sync_claimed_at IS NULL
27718
- AND outbox_owed = 1
27719
- AND event_type IN (${CAPTURE_TYPE_LIST})
27720
- AND started_at < :before
27721
- ORDER BY started_at
27722
- LIMIT :limit`
27723
- );
27724
- this.markOwedStmt = db.prepare(
27725
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27726
- );
27727
- this.markCaptureBacklogOwedStmt = db.prepare(
27728
- `UPDATE audit_events SET outbox_owed = 1
27729
- WHERE synced_at IS NULL
27730
- AND event_type IN (${CAPTURE_TYPE_LIST})
27731
- AND started_at < :before`
27732
- );
27733
- this.stampStmt = db.prepare(
27734
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27735
- );
27736
- this.claimRowStmt = db.prepare(
27737
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27738
- );
27739
- this.releaseRowStmt = db.prepare(
27740
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27741
- );
27742
- this.releaseStaleClaimsStmt = db.prepare(
27743
- `UPDATE audit_events SET sync_claimed_at = NULL
27744
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27745
- );
27746
- this.partitionStmt = db.prepare(
27747
- `SELECT
27748
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27749
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27750
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27751
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27752
- COUNT(*) AS total
27753
- FROM audit_events
27754
- WHERE event_type IN (${TYPE_LIST})`
27755
- );
27756
- this.countsStmt = db.prepare(
27757
- `SELECT
27758
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27759
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27760
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27761
- FROM audit_events
27762
- WHERE event_type IN (${TYPE_LIST})`
27763
- );
27764
- this.captureSkipCountStmt = db.prepare(
27765
- `SELECT COUNT(*) AS skipped
27766
- FROM audit_events
27767
- WHERE synced_at = ${String(SKIPPED)}
27768
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27769
- );
27770
- this.fingerprintStmt = db.prepare(
27771
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27772
- FROM history_sync WHERE id = 1`
27773
- );
27774
- this.setFingerprintStmt = db.prepare(
27775
- `UPDATE history_sync
27776
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27777
- WHERE id = 1`
27778
- );
27779
- this.disownCapturesStmt = db.prepare(
27780
- `UPDATE audit_events SET outbox_owed = NULL
27781
- WHERE outbox_owed IS NOT NULL
27782
- AND event_type IN (${CAPTURE_TYPE_LIST})
27783
- AND started_at < :attachedAt`
27784
- );
27785
- this.rearmStmt = db.prepare(
27786
- `UPDATE audit_events SET synced_at = NULL
27787
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27788
- );
27789
- this.claimStmt = db.prepare(
27790
- `UPDATE history_sync
27791
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27792
- WHERE id = 1
27793
- AND (owner_pid IS NULL
27794
- OR heartbeat_at IS NULL
27795
- OR heartbeat_at < :staleBefore
27796
- OR heartbeat_at > :now)`
27797
- );
27798
- this.heartbeatStmt = db.prepare(
27799
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27800
- );
27801
- this.releaseStmt = db.prepare(
27802
- `UPDATE history_sync
27803
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27804
- WHERE id = 1 AND owner_pid = :pid`
27805
- );
27806
- this.closeWindowStmt = db.prepare(
27807
- `UPDATE audit_events SET synced_at = :at
27808
- WHERE synced_at IS NULL
27809
- AND event_type IN (${TYPE_LIST})
27810
- AND started_at >= :attachedAt`
27811
- );
27812
- this.releaseBoundaryStmt = db.prepare(
27813
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27814
- );
27815
- this.freezeBoundaryStmt = db.prepare(
27816
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27817
- );
27818
- this.leaseStmt = db.prepare(
27819
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27820
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27821
- FROM history_sync WHERE id = 1`
27822
- );
27823
- this.inspectionsStmt = db.prepare(
27824
- `SELECT d.rule_id AS ruleId,
27825
- d.name AS ruleName,
27826
- d.version AS ruleVersion,
27827
- d.category AS category,
27828
- d.severity AS severity,
27829
- f.span_start AS spanStart,
27830
- f.span_end AS spanEnd,
27831
- f.masked_match AS maskedMatch,
27832
- f.action_taken AS actionTaken,
27833
- f.confidence AS confidence
27834
- FROM inspection_findings f
27835
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27836
- WHERE f.audit_event_id = :auditEventId
27837
- ORDER BY f.span_start, f.id`
27838
- );
27839
- }
27840
- db;
27841
- ensureRowStmt;
27842
- sessionsStmt;
27843
- rowsStmt;
27844
- stampStmt;
27845
- countsStmt;
27846
- fingerprintStmt;
27847
- setFingerprintStmt;
27848
- rearmStmt;
27849
- claimStmt;
27850
- heartbeatStmt;
27851
- releaseStmt;
27852
- leaseStmt;
27853
- inspectionsStmt;
27854
- closeWindowStmt;
27855
- releaseBoundaryStmt;
27856
- freezeBoundaryStmt;
27857
- captureRowsStmt;
27858
- markOwedStmt;
27859
- markCaptureBacklogOwedStmt;
27860
- captureSkipCountStmt;
27861
- disownCapturesStmt;
27862
- partitionStmt;
27863
- claimRowStmt;
27864
- releaseRowStmt;
27865
- releaseStaleClaimsStmt;
27866
- /**
27867
- * The masked detections recorded against one tool call.
27868
- *
27869
- * These travel with the event because a tool call's target is not
27870
- * re-inspectable from the event alone — unlike a capture, where the text
27871
- * itself is re-scannable. What crosses is the masked match and the rule that
27872
- * produced it, never the value.
27873
- */
27874
- inspectionsFor(auditEventId) {
27875
- return allRows(this.inspectionsStmt, { auditEventId });
27876
- }
27877
- /**
27878
- * Sessions with structural rows still to send, oldest first.
27879
- *
27880
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27881
- * read. Anything recorded after the machine attached is the live forward
27882
- * path's to deliver; this drain exists for what was recorded before it, and a
27883
- * row both paths send is at best a duplicate request and at worst — for a
27884
- * session root — an overwrite of the inventory ids the live path resolved.
27885
- */
27886
- pendingSessions(limit, before) {
27887
- return allRows(this.sessionsStmt, { limit, before }).map(
27888
- (r) => r.sessionId
27889
- );
27890
- }
27891
- /** One session's undelivered structural rows within the backlog, root first. */
27892
- pendingRows(sessionId, limit, before) {
27893
- return allRows(this.rowsStmt, { sessionId, limit, before });
27894
- }
27895
- /**
27896
- * Captures this machine still owes the deployment, oldest first.
27897
- *
27898
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27899
- * by a time window — see captureRowsStmt for why a window could not express
27900
- * this. `before` is the grace window that leaves a just-recorded capture to
27901
- * the live path.
27902
- */
27903
- pendingCaptureRows(limit, before) {
27904
- return allRows(this.captureRowsStmt, { limit, before });
27905
- }
27906
- /**
27907
- * Record that a capture is OWED to the deployment.
27908
- *
27909
- * Written by the attached forward path when a live send did not confirm
27910
- * delivery, and read by the drain as the whole of its eligibility test. It is
27911
- * a fact rather than an inference: the machine was attached, the send did not
27912
- * land, so the row is owed — which no time window can state, because the same
27913
- * window that holds the rows a past attachment left owed also holds every
27914
- * capture recorded while the machine was DETACHED, and those were never
27915
- * offered to anyone.
27916
- *
27917
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27918
- * out of the drain's read.
27919
- */
27920
- markCaptureOwed(id) {
27921
- this.markOwedStmt.run({ id });
27922
- }
27923
- /**
27924
- * Mark every capture already on disk as owed, as of `before`.
27925
- *
27926
- * The consent-time backfill, called once from `aka attach` when a human
27927
- * grants existing-history consent — never from an ongoing drain pass, and
27928
- * never inferred from a boundary that could later move. `before` is the
27929
- * caller's own "now" at the moment consent was granted, so what this marks
27930
- * is exactly the backlog the consent prompt already counted, not whatever a
27931
- * later re-attach or key rotation might widen it to.
27932
- *
27933
- * Returns how many rows matched, for the caller to log or test against. Not a
27934
- * count of NEWLY marked rows — a row still unsynced from an earlier call
27935
- * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27936
- */
27937
- markCaptureBacklogOwed(before) {
27938
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27939
- }
27940
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27941
- markSynced(ids, atMs) {
27942
- this.stampAll(ids, atMs);
27943
- }
27944
- /**
27945
- * Record that a row will never be sent.
27946
- *
27947
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27948
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27949
- * is retried; marking those would turn one outage into permanent data loss.
27950
- */
27951
- markSkipped(ids) {
27952
- this.stampAll(ids, SKIPPED);
27953
- }
27954
- eachInTransaction(ids, run) {
27955
- if (ids.length === 0) return;
27956
- withTransaction(
27957
- this.db,
27958
- () => {
27959
- for (const id of ids) run(id);
27960
- },
27961
- "IMMEDIATE"
27962
- );
27963
- }
27964
- stampAll(ids, value) {
27965
- if (ids.length === 0) return;
27966
- withTransaction(
27967
- this.db,
27968
- () => {
27969
- for (const id of ids) this.stampStmt.run({ at: value, id });
27970
- },
27971
- "IMMEDIATE"
27972
- );
27973
- }
27974
- /**
27975
- * Claim rows as in-flight.
27976
- *
27977
- * Advisory in exactly the sense the lease is: it records that a send is in
27978
- * progress so a surface can say so, and a lost claim costs a row showing as
27979
- * queued while it is actually being sent. It is not exclusion — the far side
27980
- * settles a duplicate on the row id.
27981
- */
27982
- claimRows(ids, atMs) {
27983
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
27984
- }
27985
- /** Give back a claim without settling — the send failed, the row is queued again. */
27986
- releaseRows(ids) {
27987
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
27988
- }
27989
- /**
27990
- * Clear claims older than `staleBefore`, and report how many were cleared.
27991
- *
27992
- * A process killed between claiming and settling leaves rows claimed with
27993
- * nothing left to settle them. Without this they read as "sending" for ever.
27994
- */
27995
- releaseStaleClaims(staleBefore) {
27996
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
27997
- }
27998
- /**
27999
- * Every tracked row in exactly one delivery state.
28000
- *
28001
- * Takes no boundary on purpose. The boundary answers "what should the drain
28002
- * pick up now", which is a different question from "what state is this row
28003
- * in" — and a machine that has never attached has no boundary to pass, so
28004
- * requiring one would force a caller to invent one and report the whole store
28005
- * as queued.
28006
- */
28007
- partition() {
28008
- const row = getRow(this.partitionStmt, {});
28009
- return {
28010
- queued: row?.queued ?? 0,
28011
- inProgress: row?.inProgress ?? 0,
28012
- synced: row?.synced ?? 0,
28013
- failed: row?.failed ?? 0,
28014
- total: row?.total ?? 0
28015
- };
28016
- }
28017
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
28018
- counts(before) {
28019
- const row = getRow(
28020
- this.countsStmt,
28021
- { before }
28022
- );
28023
- const captures = getRow(this.captureSkipCountStmt);
28024
- return {
28025
- pending: row?.pending ?? 0,
28026
- sent: row?.sent ?? 0,
28027
- skipped: row?.skipped ?? 0,
28028
- capturesSkipped: captures?.skipped ?? 0
28029
- };
28030
- }
28031
- /**
28032
- * The deployment the current stamps were made against, and where its backlog
28033
- * ends.
28034
- *
28035
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
28036
- * machine that has never drained is — and every writer below seeds the row
28037
- * before it needs one, so nothing depends on this creating it. Keeping the
28038
- * write off the gate path matters because the gate runs on every pass while a
28039
- * write has to take the database's write lock.
28040
- */
28041
- deployment() {
28042
- const row = getRow(
28043
- this.fingerprintStmt
28044
- );
28045
- return {
28046
- fingerprint: row?.fingerprint ?? void 0,
28047
- backlogBefore: row?.backlogBefore ?? void 0
28048
- };
28049
- }
28050
- /**
28051
- * Point the ledger at a different deployment, discarding what it recorded
28052
- * about the previous one.
28053
- *
28054
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28055
- * machine has just left are undelivered as far as the new one is concerned.
28056
- * All four in one transaction, so a crash between them cannot leave stamps
28057
- * attributed to the wrong deployment, a boundary that belongs to another, or
28058
- * a disown with no re-mark to follow it.
28059
- *
28060
- * The boundary is written HERE and only here, which is what freezes it: a
28061
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28062
- * unchanged, so this never runs and the backlog does not widen back over rows
28063
- * the live path has since delivered.
28064
- *
28065
- * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28066
- * granted existing-history consent for the deployment this call is arming —
28067
- * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28068
- * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28069
- * apart. Passed only when that grant is valid, since this method has no way
28070
- * to check consent itself and must not mark a row owed for a machine that
28071
- * never agreed to it. Applied AFTER the disown above, in the SAME
28072
- * transaction: what the disown clears is every marker below `backlogBefore`,
28073
- * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28074
- * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28075
- * on the cleared side of that bound — and the re-mark in the same
28076
- * transaction is what puts those rows back. A crash between the two cannot
28077
- * strand the ledger disowned with nothing re-marked — the transaction either
28078
- * lands whole or not at all, and a fingerprint mismatch that has not yet
28079
- * committed re-enters this method on the very next pass. Omit it (the
28080
- * structural-only tests do) to exercise the disown in isolation.
28081
- *
28082
- * The disown is bounded by `backlogBefore`, which is what keeps it from
28083
- * touching a marker the NEW deployment's OWN live path has already set: B's
28084
- * live path can mark a capture owed from the moment `aka attach` writes the
28085
- * descriptor, before the drain's first pass ever reaches this method, and
28086
- * such a row sits at or after the bound rather than below it. What keeps the
28087
- * disown from eating THIS SAME CALL's own re-mark is the order, not the
28088
- * bound — disown runs first, re-mark second, both inside the one
28089
- * transaction above.
28090
- */
28091
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28092
- this.ensureRowStmt.run();
28093
- withTransaction(
28094
- this.db,
28095
- () => {
28096
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28097
- this.rearmStmt.run();
28098
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28099
- this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28100
- }
28101
- if (backfillCapturesBefore !== void 0) {
28102
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28103
- }
28104
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28105
- },
28106
- "IMMEDIATE"
28107
- );
28108
- }
28109
- /**
28110
- * End the attached period: hand its rows to the live path, and release the
28111
- * boundary so the next attachment can freeze a new one.
28112
- *
28113
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28114
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28115
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28116
- * during the detached period, because the machine is not attached. Rows
28117
- * recorded in that window sit after the boundary and before the re-attach, so
28118
- * neither path takes them, and the pending count reports none outstanding.
28119
- *
28120
- * Stamping the attached window is not a claim that every one of those rows
28121
- * reached the deployment — the live path drops on failure and says so
28122
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28123
- * status quo: they sit outside the frozen boundary today and are equally never
28124
- * re-sent. Making it explicit is what lets the boundary move.
28125
- *
28126
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28127
- * window unstamped — that half-state would re-send the whole attached period
28128
- * on the next attach, which is the failure the boundary exists to prevent.
28129
- */
28130
- closeAttachedWindow(attachedAtMs, atMs) {
28131
- this.ensureRowStmt.run();
28132
- withTransaction(
28133
- this.db,
28134
- () => {
28135
- const row = getRow(this.fingerprintStmt);
28136
- const from = row?.backlogBefore ?? attachedAtMs;
28137
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28138
- this.releaseBoundaryStmt.run();
28139
- },
28140
- "IMMEDIATE"
28141
- );
28142
- }
28143
- /**
28144
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28145
- *
28146
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28147
- * different deployment and therefore discards what was delivered to the old
28148
- * one: here the recipient is the same, so everything already sent to it stays
28149
- * sent.
28150
- */
28151
- freezeBoundary(backlogBefore) {
28152
- this.ensureRowStmt.run();
28153
- this.freezeBoundaryStmt.run({ backlogBefore });
28154
- }
28155
- /** Take the claim, or report that someone live already holds it. */
28156
- claim(pid, host, nowMs, staleAfterMs) {
28157
- this.ensureRowStmt.run();
28158
- let taken = false;
28159
- withTransaction(
28160
- this.db,
28161
- () => {
28162
- const result = this.claimStmt.run({
28163
- pid,
28164
- host,
28165
- now: nowMs,
28166
- staleBefore: nowMs - staleAfterMs
28167
- });
28168
- taken = result.changes === 1;
28169
- },
28170
- "IMMEDIATE"
28171
- );
28172
- return taken;
28173
- }
28174
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28175
- heartbeat(pid, nowMs) {
28176
- this.heartbeatStmt.run({ now: nowMs, pid });
28177
- }
28178
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28179
- release(pid) {
28180
- this.releaseStmt.run({ pid });
28181
- }
28182
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28183
- lease() {
28184
- return getRow(this.leaseStmt);
28185
- }
28186
- };
28187
-
28188
28794
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28189
28795
  var SqliteInspectionDefinitionsRepository = class {
28190
28796
  constructor(db) {
@@ -28412,6 +29018,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28412
29018
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28413
29019
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28414
29020
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29021
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28415
29022
  if (values.vaultConsent !== void 0) {
28416
29023
  merged.vaultConsent = values.vaultConsent ? (
28417
29024
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30919,7 +31526,7 @@ var SqliteSecurityRepository = class {
30919
31526
  ELSE 0
30920
31527
  END) AS open_at_rest
30921
31528
  FROM inspection_findings f
30922
- JOIN audit_events e ON e.id = f.audit_event_id
31529
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30923
31530
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30924
31531
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30925
31532
  ON latest.finding_key = f.finding_key
@@ -31145,7 +31752,7 @@ var SqliteSecurityRepository = class {
31145
31752
  this.db.prepare(
31146
31753
  `SELECT e.repo AS repo, count(*) AS c
31147
31754
  FROM inspection_findings f
31148
- JOIN audit_events e ON e.id = f.audit_event_id
31755
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31149
31756
  WHERE e.started_at >= :from AND e.started_at < :to
31150
31757
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31151
31758
  AND e.repo IS NOT NULL
@@ -31269,7 +31876,7 @@ var SqliteSecurityRepository = class {
31269
31876
  d.severity AS severity,
31270
31877
  COUNT(*) AS count
31271
31878
  FROM inspection_findings f
31272
- JOIN audit_events e ON e.id = f.audit_event_id
31879
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31273
31880
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31274
31881
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31275
31882
  ON latest.finding_key = f.finding_key
@@ -31304,7 +31911,7 @@ var SqliteSecurityRepository = class {
31304
31911
  `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31305
31912
  d.rule_id AS rule_id, d.category AS category
31306
31913
  FROM inspection_findings f
31307
- JOIN audit_events e ON e.id = f.audit_event_id
31914
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31308
31915
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31309
31916
  WHERE e.started_at >= :from AND e.started_at < :to
31310
31917
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -32145,6 +32752,7 @@ function openWithPragmas(file2) {
32145
32752
  db.exec("PRAGMA journal_mode = WAL");
32146
32753
  db.exec("PRAGMA busy_timeout = 2000");
32147
32754
  db.exec("PRAGMA foreign_keys = ON");
32755
+ registerSqlFunctions(db);
32148
32756
  } catch (err) {
32149
32757
  closeQuietly(db);
32150
32758
  throw err;
@@ -32174,7 +32782,7 @@ function backupLegacyStore(db, file2) {
32174
32782
  discardStore(file2, backup);
32175
32783
  return backup;
32176
32784
  }
32177
- function openAndInitialize(file2, base) {
32785
+ function openAndInitialize(file2, base, skipTags) {
32178
32786
  let db = openWithPragmas(file2);
32179
32787
  try {
32180
32788
  if (isForeignSqliteLineage(db)) {
@@ -32184,7 +32792,7 @@ function openAndInitialize(file2, base) {
32184
32792
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32185
32793
  );
32186
32794
  }
32187
- applyMigrations(db, file2);
32795
+ applyMigrations(db, file2, { skipTags });
32188
32796
  tightenPerms(file2);
32189
32797
  const policies = new SqlitePoliciesRepository(db);
32190
32798
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32199,6 +32807,7 @@ function openAndInitialize(file2, base) {
32199
32807
  exceptions: new SqliteExceptionsRepository(db),
32200
32808
  resolutions: new SqliteResolutionsRepository(db),
32201
32809
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32810
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32202
32811
  security: new SqliteSecurityRepository(db),
32203
32812
  detections: new SqliteDetectionsRepository(db),
32204
32813
  shares: new SqliteSharesRepository(db),
@@ -32221,7 +32830,8 @@ function openAndInitialize(file2, base) {
32221
32830
  throw err;
32222
32831
  }
32223
32832
  }
32224
- function openLocalDatabase(dir) {
32833
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32834
+ function openLocalDatabase(dir, options = {}) {
32225
32835
  ensureDataDirSync(dir);
32226
32836
  const file2 = join7(dir, DB_FILENAME);
32227
32837
  reapStalePartials(file2);
@@ -32233,6 +32843,7 @@ function openLocalDatabase(dir) {
32233
32843
  installedPacks,
32234
32844
  scanLedger,
32235
32845
  historySync,
32846
+ bodyRetention,
32236
32847
  secretVault,
32237
32848
  exceptions,
32238
32849
  resolutions,
@@ -32256,7 +32867,8 @@ function openLocalDatabase(dir) {
32256
32867
  // `dir` is always `<base>/data` — every caller resolves it through
32257
32868
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32258
32869
  // settings/ and data/, and the pack-policy floor needs both halves.
32259
- dirname2(dir)
32870
+ dirname2(dir),
32871
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32260
32872
  );
32261
32873
  function captureRowId(event) {
32262
32874
  return captureId(
@@ -32449,6 +33061,7 @@ function openLocalDatabase(dir) {
32449
33061
  installedPacks,
32450
33062
  scanLedger,
32451
33063
  historySync,
33064
+ bodyRetention,
32452
33065
  secretVault,
32453
33066
  exceptions,
32454
33067
  resolutions,
@@ -32489,8 +33102,35 @@ function openLocalDatabase(dir) {
32489
33102
 
32490
33103
  // ../../packages/persistence/src/egress-wire.ts
32491
33104
  import { createHash as createHash3 } from "crypto";
33105
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33106
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33107
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33108
+ var FILE_URL = /^file:\/\//i;
33109
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33110
+ var SLASH = "/".charCodeAt(0);
33111
+ var GIT_SUFFIX = ".git";
33112
+ function trimSlashes(path) {
33113
+ let start = 0;
33114
+ let end = path.length;
33115
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33116
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33117
+ return path.slice(start, end);
33118
+ }
33119
+ function canonicalGitUrl(url2) {
33120
+ const trimmed = url2.trim();
33121
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33122
+ const scheme = SCHEME_FORM.exec(trimmed);
33123
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33124
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33125
+ if (host === void 0) return trimmed;
33126
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33127
+ const bare = trimSlashes(path);
33128
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33129
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33130
+ }
32492
33131
  function hashProjectKey(projectKey) {
32493
- return createHash3("sha256").update(projectKey, "utf8").digest("hex");
33132
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33133
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
32494
33134
  }
32495
33135
  function toIngestHit(hit) {
32496
33136
  return {
@@ -32566,18 +33206,50 @@ function readFingerprintKey(dataDir2) {
32566
33206
  return parseKeyFile(raw);
32567
33207
  }
32568
33208
 
33209
+ // ../../packages/persistence/src/forward-health.ts
33210
+ import { readFileSync as readFileSync7 } from "fs";
33211
+ import { join as join9 } from "path";
33212
+ var FAILURES = /* @__PURE__ */ new Set([
33213
+ "unauthorized",
33214
+ "forbidden",
33215
+ "unreachable"
33216
+ ]);
33217
+ var BREAKER_COOLDOWN_MS = 3e4;
33218
+ function parseForwardHealth(raw, nowMs) {
33219
+ try {
33220
+ const parsed2 = JSON.parse(raw);
33221
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33222
+ const record2 = parsed2;
33223
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33224
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33225
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33226
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33227
+ } catch {
33228
+ return null;
33229
+ }
33230
+ }
33231
+ function isForwardPaused(health, nowMs) {
33232
+ const openedAtMs = health?.openedAtMs ?? null;
33233
+ if (openedAtMs === null) return false;
33234
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33235
+ }
33236
+
32569
33237
  // ../../packages/persistence/src/history-backfill.ts
32570
33238
  import { existsSync as existsSync4 } from "fs";
32571
- import { join as join9 } from "path";
33239
+ import { join as join10 } from "path";
32572
33240
 
32573
33241
  // ../../packages/persistence/src/history-preview.ts
32574
33242
  import { existsSync as existsSync5 } from "fs";
32575
- import { join as join10 } from "path";
33243
+ import { join as join11 } from "path";
32576
33244
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32577
33245
 
33246
+ // ../../packages/persistence/src/history-sync-state.ts
33247
+ import { readFileSync as readFileSync8 } from "fs";
33248
+ import { join as join12 } from "path";
33249
+
32578
33250
  // ../../packages/persistence/src/store-symlinks.ts
32579
33251
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32580
- import { dirname as dirname3, join as join11, resolve } from "path";
33252
+ import { dirname as dirname3, join as join13, resolve } from "path";
32581
33253
 
32582
33254
  // ../../packages/persistence/src/vault/crypto.ts
32583
33255
  import {
@@ -32591,19 +33263,19 @@ import {
32591
33263
  // ../../packages/persistence/src/vault/key-provider.ts
32592
33264
  import { execFileSync } from "child_process";
32593
33265
  import { randomBytes as randomBytes2 } from "crypto";
32594
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32595
- import { join as join12 } from "path";
33266
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33267
+ import { join as join14 } from "path";
32596
33268
 
32597
33269
  // ../../packages/persistence/src/vault/vault.ts
32598
33270
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32599
33271
 
32600
33272
  // ../../packages/persistence/src/warn-era-cap.ts
32601
33273
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
32602
- import { join as join13 } from "path";
33274
+ import { join as join15 } from "path";
32603
33275
  var MARKER = "warn-era-capped";
32604
33276
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
32605
33277
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
32606
- const marker = join13(dataDir2, MARKER);
33278
+ const marker = join15(dataDir2, MARKER);
32607
33279
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
32608
33280
  const capped = db.policies.capCategoryActions();
32609
33281
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -32663,7 +33335,7 @@ function resolveProvider() {
32663
33335
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
32664
33336
  try {
32665
33337
  ensureLayoutDirSync(base);
32666
- const settingsFile = join14(settingsDir(base), "settings.json");
33338
+ const settingsFile = join16(settingsDir(base), "settings.json");
32667
33339
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
32668
33340
  } catch {
32669
33341
  }
@@ -32687,9 +33359,9 @@ function resolveProviderSafe(resolveProviderFn) {
32687
33359
  }
32688
33360
 
32689
33361
  // ../../packages/plugin-sdk/src/config-inventory.ts
32690
- import { readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33362
+ import { readdirSync as readdirSync2, readFileSync as readFileSync11, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
32691
33363
  import { homedir as homedir2 } from "os";
32692
- import { basename as basename3, join as join16 } from "path";
33364
+ import { basename as basename3, join as join18 } from "path";
32693
33365
 
32694
33366
  // ../../packages/detections/src/egress/registry.ts
32695
33367
  var EXTRACTOR_VERSION = "1";
@@ -35733,8 +36405,8 @@ function scanText(text, ruleVersions) {
35733
36405
  }
35734
36406
 
35735
36407
  // ../../packages/plugin-sdk/src/repo.ts
35736
- import { existsSync as existsSync9, readFileSync as readFileSync8, statSync as statSync6 } from "fs";
35737
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
36408
+ import { existsSync as existsSync9, readFileSync as readFileSync10, statSync as statSync6 } from "fs";
36409
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join17, sep as sep2 } from "path";
35738
36410
  function resolveRepoIdentity(cwd) {
35739
36411
  try {
35740
36412
  const root = findGitRoot(cwd);
@@ -35756,36 +36428,36 @@ function resolveRepoIdentity(cwd) {
35756
36428
  function findGitRoot(start) {
35757
36429
  let dir = start;
35758
36430
  for (; ; ) {
35759
- if (existsSync9(join15(dir, ".git"))) return dir;
36431
+ if (existsSync9(join17(dir, ".git"))) return dir;
35760
36432
  const parent = dirname4(dir);
35761
36433
  if (parent === dir) return void 0;
35762
36434
  dir = parent;
35763
36435
  }
35764
36436
  }
35765
36437
  function resolveGitContext(root) {
35766
- const dotGit = join15(root, ".git");
36438
+ const dotGit = join17(root, ".git");
35767
36439
  try {
35768
36440
  if (statSync6(dotGit).isDirectory()) {
35769
- return { configPath: join15(dotGit, "config"), headRoot: root };
36441
+ return { configPath: join17(dotGit, "config"), headRoot: root };
35770
36442
  }
35771
36443
  } catch {
35772
36444
  return void 0;
35773
36445
  }
35774
36446
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
35775
36447
  if (!target) return void 0;
35776
- const gitdir = isAbsolute(target) ? target : join15(root, target);
35777
- if (existsSync9(join15(gitdir, "config"))) {
35778
- return { configPath: join15(gitdir, "config"), headRoot: root };
36448
+ const gitdir = isAbsolute(target) ? target : join17(root, target);
36449
+ if (existsSync9(join17(gitdir, "config"))) {
36450
+ return { configPath: join17(gitdir, "config"), headRoot: root };
35779
36451
  }
35780
- const commonRaw = safeRead(join15(gitdir, "commondir"))?.trim();
36452
+ const commonRaw = safeRead(join17(gitdir, "commondir"))?.trim();
35781
36453
  if (!commonRaw) return void 0;
35782
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join15(gitdir, commonRaw);
36454
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join17(gitdir, commonRaw);
35783
36455
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
35784
- return { configPath: join15(commonGitDir, "config"), headRoot };
36456
+ return { configPath: join17(commonGitDir, "config"), headRoot };
35785
36457
  }
35786
36458
  function safeRead(path) {
35787
36459
  try {
35788
- return readFileSync8(path, "utf8");
36460
+ return readFileSync10(path, "utf8");
35789
36461
  } catch {
35790
36462
  return void 0;
35791
36463
  }
@@ -35831,8 +36503,8 @@ import { fileURLToPath } from "url";
35831
36503
  import { Worker } from "worker_threads";
35832
36504
 
35833
36505
  // ../../packages/plugin-sdk/src/host-floor.ts
35834
- import { readFileSync as readFileSync11 } from "fs";
35835
- import { join as join18 } from "path";
36506
+ import { readFileSync as readFileSync13 } from "fs";
36507
+ import { join as join20 } from "path";
35836
36508
 
35837
36509
  // ../../packages/plugin-sdk/src/model-governance.ts
35838
36510
  import {
@@ -35840,11 +36512,11 @@ import {
35840
36512
  fstatSync,
35841
36513
  mkdirSync as mkdirSync2,
35842
36514
  openSync as openSync2,
35843
- readFileSync as readFileSync10,
36515
+ readFileSync as readFileSync12,
35844
36516
  readSync,
35845
36517
  writeFileSync as writeFileSync5
35846
36518
  } from "fs";
35847
- import { join as join17 } from "path";
36519
+ import { join as join19 } from "path";
35848
36520
  var TAIL_BYTES = 256 * 1024;
35849
36521
 
35850
36522
  // ../../packages/plugin-sdk/src/host-floor.ts
@@ -35867,8 +36539,8 @@ var HOST_FLOORS = {
35867
36539
 
35868
36540
  // ../../packages/plugin-sdk/src/ignore-layers.ts
35869
36541
  var import_ignore = __toESM(require_ignore(), 1);
35870
- import { readFileSync as readFileSync12 } from "fs";
35871
- import { join as join19 } from "path";
36542
+ import { readFileSync as readFileSync14 } from "fs";
36543
+ import { join as join21 } from "path";
35872
36544
 
35873
36545
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
35874
36546
  import { arch, hostname as hostname4, platform, release } from "os";
@@ -35900,8 +36572,8 @@ function resolveInventoryContext(input2) {
35900
36572
  }
35901
36573
 
35902
36574
  // ../../packages/plugin-sdk/src/nudge.ts
35903
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
35904
- import { join as join20 } from "path";
36575
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync15, writeFileSync as writeFileSync6 } from "fs";
36576
+ import { join as join22 } from "path";
35905
36577
 
35906
36578
  // ../../packages/plugin-sdk/src/paths.ts
35907
36579
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -35909,7 +36581,7 @@ import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
35909
36581
 
35910
36582
  // ../../packages/plugin-sdk/src/project-files.ts
35911
36583
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
35912
- import { basename as basename5, join as join21 } from "path";
36584
+ import { basename as basename5, join as join23 } from "path";
35913
36585
 
35914
36586
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
35915
36587
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -35955,7 +36627,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
35955
36627
 
35956
36628
  // ../../packages/plugin-sdk/src/throttle.ts
35957
36629
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
35958
- import { join as join22 } from "path";
36630
+ import { join as join24 } from "path";
35959
36631
 
35960
36632
  // ../../packages/remote/src/http.ts
35961
36633
  import { request as httpRequest } from "http";
@@ -36140,10 +36812,10 @@ function parsed(schema, body, route) {
36140
36812
  }
36141
36813
  function withoutTrailingSlashes(endpoint) {
36142
36814
  let end = endpoint.length;
36143
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
36815
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
36144
36816
  return endpoint.slice(0, end);
36145
36817
  }
36146
- var SLASH = "/".charCodeAt(0);
36818
+ var SLASH2 = "/".charCodeAt(0);
36147
36819
  function createRemoteClient(options) {
36148
36820
  const base = withoutTrailingSlashes(options.endpoint);
36149
36821
  const url2 = (route) => `${base}${route}`;
@@ -36325,11 +36997,11 @@ function withTimeout(promise2, ms) {
36325
36997
  }
36326
36998
 
36327
36999
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
36328
- import { readFileSync as readFileSync14 } from "fs";
36329
- import { join as join23 } from "path";
37000
+ import { readFileSync as readFileSync16 } from "fs";
37001
+ import { join as join25 } from "path";
36330
37002
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
36331
37003
  function forwardDropsPath(dataDir2) {
36332
- return join23(dataDir2, FORWARD_DROPS_FILENAME);
37004
+ return join25(dataDir2, FORWARD_DROPS_FILENAME);
36333
37005
  }
36334
37006
  function recordForwardDrops(dataDir2, count, nowMs) {
36335
37007
  if (count <= 0) return;
@@ -36347,7 +37019,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
36347
37019
  }
36348
37020
  function readForwardDrops(dataDir2) {
36349
37021
  try {
36350
- const parsed2 = JSON.parse(readFileSync14(forwardDropsPath(dataDir2), "utf8"));
37022
+ const parsed2 = JSON.parse(readFileSync16(forwardDropsPath(dataDir2), "utf8"));
36351
37023
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
36352
37024
  const record2 = parsed2;
36353
37025
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -36365,9 +37037,8 @@ function readForwardDrops(dataDir2) {
36365
37037
 
36366
37038
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
36367
37039
  import { randomUUID as randomUUID15 } from "crypto";
36368
- import { readFileSync as readFileSync15 } from "fs";
36369
37040
  import { readFile, rename, writeFile } from "fs/promises";
36370
- import { join as join24 } from "path";
37041
+ import { join as join26 } from "path";
36371
37042
  function isInvalidRequest(err) {
36372
37043
  return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
36373
37044
  }
@@ -36381,31 +37052,12 @@ function isServerRejection(err) {
36381
37052
  var FORWARD_BUDGET_MS = 1500;
36382
37053
  var DECISION_PATH_BUDGET_MS = 800;
36383
37054
  var BREAKER_FAILURE_THRESHOLD = 3;
36384
- var BREAKER_COOLDOWN_MS = 3e4;
36385
37055
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
36386
- var FAILURES = /* @__PURE__ */ new Set([
36387
- "unauthorized",
36388
- "forbidden",
36389
- "unreachable"
36390
- ]);
36391
37056
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
36392
37057
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
36393
- function parseBreakerState(raw, nowMs) {
36394
- try {
36395
- const parsed2 = JSON.parse(raw);
36396
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
36397
- const record2 = parsed2;
36398
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
36399
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
36400
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
36401
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
36402
- } catch {
36403
- return null;
36404
- }
36405
- }
36406
37058
  function createForwardPolicy(deps) {
36407
37059
  const now = deps.now ?? (() => Date.now());
36408
- const file2 = join24(deps.dir, STATE_FILENAME);
37060
+ const file2 = join26(deps.dir, STATE_FILENAME);
36409
37061
  let state = null;
36410
37062
  let loading = null;
36411
37063
  async function readState() {
@@ -36415,7 +37067,7 @@ function createForwardPolicy(deps) {
36415
37067
  } catch {
36416
37068
  return { ...CLOSED };
36417
37069
  }
36418
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
37070
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
36419
37071
  }
36420
37072
  async function load() {
36421
37073
  if (state !== null) return state;
@@ -36461,7 +37113,7 @@ function createForwardPolicy(deps) {
36461
37113
  };
36462
37114
  const at = now();
36463
37115
  if (current.openedAtMs !== null) {
36464
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
37116
+ if (isForwardPaused(current, at)) {
36465
37117
  return { ok: false, reason: "breaker-open" };
36466
37118
  }
36467
37119
  await persist({
@@ -36998,7 +37650,18 @@ var AttachedDataGateway = class {
36998
37650
  // and the spread above would otherwise drop the field silently — which is
36999
37651
  // exactly what it did, leaving the whole control inert on every device
37000
37652
  // while every test around it stayed green.
37001
- prohibitedModels: cached2.prohibitedModels
37653
+ prohibitedModels: cached2.prohibitedModels,
37654
+ // NAMED for the same reason as the line above, and it is the same defect
37655
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
37656
+ // only the cache carries is dropped in silence. That is what left
37657
+ // `prohibitedModels` inert on every attached device with every test
37658
+ // around it green.
37659
+ //
37660
+ // Taken from the cache rather than merged here, because merging it needs
37661
+ // the device's own SETTING — which is not a bundle field and is not in
37662
+ // scope at this seam. The runtime does that merge, raise-only, where both
37663
+ // values are in hand (createPluginRuntime's ensureInitialized).
37664
+ redactFallback: cached2.redactFallback
37002
37665
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
37003
37666
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
37004
37667
  // it emits, so an 'authored' policy arriving from the control plane
@@ -37126,10 +37789,6 @@ function toolAuditEvent(input2) {
37126
37789
  };
37127
37790
  }
37128
37791
 
37129
- // ../../packages/plugin-runtime/src/attached/history-state.ts
37130
- import { readFileSync as readFileSync16 } from "fs";
37131
- import { join as join25 } from "path";
37132
-
37133
37792
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
37134
37793
  import { createHash as createHash6 } from "crypto";
37135
37794
  import { hostname as hostname5 } from "os";
@@ -37138,6 +37797,10 @@ import { hostname as hostname5 } from "os";
37138
37797
  var CORRELATION_ID = EventMetadata.shape.correlationId;
37139
37798
  var TRACE_ID = EventMetadata.shape.traceId;
37140
37799
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
37800
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
37801
+
37802
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
37803
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
37141
37804
 
37142
37805
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
37143
37806
  import { spawn } from "child_process";
@@ -37179,7 +37842,7 @@ function createPluginBlock(build, policyStore) {
37179
37842
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
37180
37843
  import { randomUUID as randomUUID16 } from "crypto";
37181
37844
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
37182
- import { join as join26 } from "path";
37845
+ import { join as join27 } from "path";
37183
37846
 
37184
37847
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
37185
37848
  import { rename as rename2 } from "fs/promises";
@@ -37203,7 +37866,7 @@ async function publishByRename(tmp, file2, move = rename2) {
37203
37866
 
37204
37867
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
37205
37868
  function createPolicyStore(dir = dataDir()) {
37206
- const file2 = join26(dir, "policy-cache.json");
37869
+ const file2 = join27(dir, "policy-cache.json");
37207
37870
  async function read() {
37208
37871
  try {
37209
37872
  const raw = await readFile2(file2, "utf8");
@@ -37434,11 +38097,11 @@ function readStorePosture(dbPath2) {
37434
38097
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
37435
38098
  import { randomUUID as randomUUID17 } from "crypto";
37436
38099
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
37437
- import { join as join27 } from "path";
38100
+ import { join as join28 } from "path";
37438
38101
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
37439
38102
  function createPostureStore(dir = settingsDir(), legacyDir) {
37440
- const file2 = join27(dir, "posture-state.json");
37441
- const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
38103
+ const file2 = join28(dir, "posture-state.json");
38104
+ const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
37442
38105
  async function persist(state) {
37443
38106
  await ensureDataDir(dir);
37444
38107
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -37507,7 +38170,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
37507
38170
 
37508
38171
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
37509
38172
  import { readFileSync as readFileSync18 } from "fs";
37510
- import { join as join28 } from "path";
38173
+ import { join as join29 } from "path";
37511
38174
 
37512
38175
  // ../../packages/plugin-runtime/src/attached/status.ts
37513
38176
  var REFUSAL_LINES = {
@@ -37528,6 +38191,14 @@ import { spawn as spawn2 } from "child_process";
37528
38191
  import { fileURLToPath as fileURLToPath3 } from "url";
37529
38192
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
37530
38193
 
38194
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
38195
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
38196
+
38197
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
38198
+ import { spawn as spawn3 } from "child_process";
38199
+ import { fileURLToPath as fileURLToPath4 } from "url";
38200
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
38201
+
37531
38202
  // ../../packages/plugin-runtime/src/attached/factory.ts
37532
38203
  import { hostname as hostname6 } from "os";
37533
38204
 
@@ -37995,9 +38666,9 @@ import {
37995
38666
  readSync as readSync2,
37996
38667
  writeFileSync as writeFileSync8
37997
38668
  } from "fs";
37998
- import { join as join29 } from "path";
38669
+ import { join as join30 } from "path";
37999
38670
  function offsetsDir(dataDir2) {
38000
- return join29(dataDir2, "usage-offsets");
38671
+ return join30(dataDir2, "usage-offsets");
38001
38672
  }
38002
38673
  var SAFE_SESSION_ID = /^[A-Za-z0-9._-]+$/;
38003
38674
  function safeSessionId(sessionId) {
@@ -38007,7 +38678,7 @@ function safeSessionId(sessionId) {
38007
38678
  return createHash7("sha256").update(sessionId).digest("hex");
38008
38679
  }
38009
38680
  function offsetPath(dataDir2, sessionId) {
38010
- return join29(offsetsDir(dataDir2), safeSessionId(sessionId));
38681
+ return join30(offsetsDir(dataDir2), safeSessionId(sessionId));
38011
38682
  }
38012
38683
  function readOffset(dataDir2, sessionId) {
38013
38684
  try {
@@ -38071,7 +38742,7 @@ function readTail(transcriptPath, startOffset) {
38071
38742
  // src/history/transcripts.ts
38072
38743
  import { closeSync as closeSync4, openSync as openSync4, readdirSync as readdirSync5, readFileSync as readFileSync20, readSync as readSync3, statSync as statSync10 } from "fs";
38073
38744
  import { homedir as homedir3 } from "os";
38074
- import { join as join30 } from "path";
38745
+ import { join as join31 } from "path";
38075
38746
  function isRecord(value) {
38076
38747
  return typeof value === "object" && value !== null;
38077
38748
  }