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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH2 = "/";
53
+ var SLASH3 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH2).filter(Boolean);
425
+ const slices = path.split(SLASH3).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH2) + SLASH2,
429
+ slices.join(SLASH3) + SLASH3,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH2).filter(Boolean);
445
+ slices = path.split(SLASH3).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH2) + SLASH2,
452
+ slices.join(SLASH3) + SLASH3,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -502,6 +502,14 @@ var ATTACHED_HISTORY_SYNC_STATE_FILENAME = "attached-history-sync.json";
502
502
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
503
503
  import { join as join2 } from "path";
504
504
 
505
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
506
+ var DEFERRED_MIGRATION_TAGS = [
507
+ "0031_audit_capture_by_time_index",
508
+ "0032_audit_capture_by_id_index",
509
+ "0033_audit_capture_location_index",
510
+ "0034_findings_read_indexes"
511
+ ];
512
+
505
513
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
506
514
  var SQLITE_MIGRATIONS = [
507
515
  {
@@ -619,6 +627,30 @@ var SQLITE_MIGRATIONS = [
619
627
  {
620
628
  tag: "0028_activity_session_probe_indexes",
621
629
  sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"
630
+ },
631
+ {
632
+ tag: "0029_audit_capture_rollup_index",
633
+ sql: "CREATE INDEX `idx_audit_capture_rollup` ON `audit_events` (`event_type`,`started_at`,`repo`,`id`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
634
+ },
635
+ {
636
+ tag: "0030_audit_content_expiry",
637
+ sql: "ALTER TABLE `audit_events` ADD `content_expired_at` integer;--> statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"
638
+ },
639
+ {
640
+ tag: "0031_audit_capture_by_time_index",
641
+ sql: "CREATE INDEX `idx_audit_capture_by_time` ON `audit_events` (`started_at`,`id`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
642
+ },
643
+ {
644
+ tag: "0032_audit_capture_by_id_index",
645
+ sql: "CREATE INDEX `idx_audit_capture_by_id` ON `audit_events` (`id`,`started_at`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
646
+ },
647
+ {
648
+ tag: "0033_audit_capture_location_index",
649
+ sql: "CREATE INDEX `idx_audit_capture_location` ON `audit_events` (`repo`,`file_path`,`started_at`,`id`,`event_type`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
650
+ },
651
+ {
652
+ tag: "0034_findings_read_indexes",
653
+ sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
622
654
  }
623
655
  ];
624
656
 
@@ -20666,6 +20698,15 @@ var FindingCategory = external_exports.enum([
20666
20698
  ]).meta({ id: "FindingCategory" });
20667
20699
  var FindingOrigin = external_exports.enum(["in-flight", "at-rest"]).meta({ id: "FindingOrigin" });
20668
20700
  var FindingStatus = external_exports.enum(["open", "handled", "resolved", "dismissed"]).meta({ id: "FindingStatus" });
20701
+ var SyncFailureReason = external_exports.enum(["deployment_refused", "payload_invalid", "detached_undelivered"]).meta({ id: "SyncFailureReason" });
20702
+ var FindingDeliveryState = external_exports.enum(["sent", "queued", "not_sent", "never_offered", "local_scan"]).meta({ id: "FindingDeliveryState" });
20703
+ var FindingDelivery = external_exports.object({
20704
+ state: FindingDeliveryState,
20705
+ // The delivery time for `sent`; the failure time for `not_sent` when recorded.
20706
+ at: external_exports.iso.datetime().optional(),
20707
+ // Only on `not_sent`, and only when a known reason was recorded.
20708
+ reason: SyncFailureReason.optional()
20709
+ }).meta({ id: "FindingDelivery" });
20669
20710
  var ResolutionMethod = external_exports.enum([
20670
20711
  "enforced-in-flight",
20671
20712
  "fixed-at-source",
@@ -20722,7 +20763,10 @@ var FindingInstance = external_exports.object({
20722
20763
  // The session that event belongs to, when it has one — the seam a
20723
20764
  // per-instance "view session" link needs. Absent for events captured
20724
20765
  // outside a session.
20725
- sessionId: external_exports.string().optional()
20766
+ sessionId: external_exports.string().optional(),
20767
+ // The delivery state of the event above (see FindingDelivery). Optional so
20768
+ // readers that do not project it stay valid.
20769
+ delivery: FindingDelivery.optional()
20726
20770
  }).meta({ id: "FindingInstance" });
20727
20771
  var FindingGroup = external_exports.object({
20728
20772
  id: external_exports.string(),
@@ -20774,7 +20818,10 @@ var FindingFacets = external_exports.object({
20774
20818
  // Host tool (attributes.tool_name). Present only on the instance-level
20775
20819
  // reads, which can filter by it; the type-level read omits the dimension
20776
20820
  // because a group spans tools.
20777
- tool: external_exports.array(FindingFacetItem).optional()
20821
+ tool: external_exports.array(FindingFacetItem).optional(),
20822
+ // Delivery states (FindingDeliveryState). Present only on the
20823
+ // instance-level reads, like `tool`.
20824
+ deployment: external_exports.array(FindingFacetItem).optional()
20778
20825
  }).meta({ id: "FindingFacets" });
20779
20826
  var FindingTypeSummary = FindingGroup.omit({ instances: true, match: true }).meta({
20780
20827
  id: "FindingTypeSummary"
@@ -20885,6 +20932,8 @@ var ListFindingInstancesQuery = external_exports.object({
20885
20932
  // Exact host-tool names (attributes.tool_name, e.g. 'Bash'). A real filter,
20886
20933
  // where the free-text `q` can only match the rendered "via Bash" label.
20887
20934
  tool: external_exports.array(external_exports.string()).optional(),
20935
+ // The delivery state of each finding's event (see FindingDelivery).
20936
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20888
20937
  // Exact repository / file-path matches, for the drill-down out of the
20889
20938
  // locations view. A row whose event carries no repo/file matches neither.
20890
20939
  repo: external_exports.string().optional(),
@@ -20905,6 +20954,10 @@ var ListFindingInstancesResponse = external_exports.object({
20905
20954
  items: external_exports.array(FindingInstanceDetail),
20906
20955
  nextCursor: external_exports.string().nullable()
20907
20956
  }).meta({ id: "ListFindingInstancesResponse" });
20957
+ var ListFindingInstancesPage = external_exports.object({
20958
+ items: external_exports.array(FindingInstanceDetail),
20959
+ nextCursor: external_exports.string().nullable()
20960
+ }).meta({ id: "ListFindingInstancesPage" });
20908
20961
  var FindingLocationSummary = external_exports.object({
20909
20962
  // Opaque, stable, minted from the pair by encodeLocationId. It exists
20910
20963
  // because a location's identity is two values and a URL param carries one:
@@ -20947,6 +21000,8 @@ var ListFindingLocationsQuery = external_exports.object({
20947
21000
  // instances that match, and folds its status from those.
20948
21001
  status: external_exports.array(FindingStatus).optional(),
20949
21002
  tool: external_exports.array(external_exports.string()).optional(),
21003
+ // The delivery state of each finding's event (see FindingDelivery).
21004
+ deployment: external_exports.array(FindingDeliveryState).optional(),
20950
21005
  q: external_exports.string().optional(),
20951
21006
  sessionId: external_exports.string().optional(),
20952
21007
  from: external_exports.iso.datetime().optional(),
@@ -21149,6 +21204,10 @@ var CaptureAttributes = external_exports.object({
21149
21204
  // to 'allow' — the enforcement audit trail's link back to the grant that
21150
21205
  // authorized the bypass.
21151
21206
  exception_ids: external_exports.array(external_exports.guid()).optional(),
21207
+ // The persisted spellings of EventMetadata's messageId/conversationId — the
21208
+ // join back to the `llm_call` leaf for the same assistant turn.
21209
+ message_id: external_exports.string().optional(),
21210
+ conversation_id: external_exports.string().optional(),
21152
21211
  // Whole milliseconds this capture's inspection blocked its caller — the
21153
21212
  // plugin's own added latency (see EventMetadata.inspectionMs, whose value
21154
21213
  // this is). Promoted to the `inspection_ms` generated column so the facet is
@@ -21157,7 +21216,19 @@ var CaptureAttributes = external_exports.object({
21157
21216
  // inline json_extract and is not itself an optimization.
21158
21217
  // ABSENT on replayed captures (backfill / worktree scan) and on rows written
21159
21218
  // before the measurement shipped — never present as a placeholder 0.
21160
- inspection_ms: external_exports.number().int().nonnegative().optional()
21219
+ inspection_ms: external_exports.number().int().nonnegative().optional(),
21220
+ // What a `redact` this capture could not carry out became instead (see
21221
+ // EventMetadata.redactDegradedTo, whose value this is). Present only when a
21222
+ // degrade actually happened, so absence is the ordinary case rather than a
21223
+ // reader having to distinguish it from a zero.
21224
+ //
21225
+ // PER CAPTURE, while `inspection_findings.action_taken` is per finding —
21226
+ // so on a multi-finding row this does not say which finding degraded, and
21227
+ // its presence does not mean the fallback decided the capture's action. A
21228
+ // capture denied by another finding's own Block policy carries `block`
21229
+ // here too. The full statement is on EventMetadata.redactDegradedTo; it is
21230
+ // repeated rather than referenced because a store reader opens this file.
21231
+ redact_degraded_to: ActionTaken.optional()
21161
21232
  }).catchall(external_exports.unknown());
21162
21233
  var ToolCallInspection = external_exports.object({
21163
21234
  ruleId: external_exports.string().min(1),
@@ -21356,7 +21427,17 @@ var AuditEvent = external_exports.object({
21356
21427
  /** `share` to a first-party/internal destination. */
21357
21428
  internal: external_exports.boolean(),
21358
21429
  /** Event needs review (e.g. unverified egress). */
21359
- flagged: external_exports.boolean()
21430
+ flagged: external_exports.boolean(),
21431
+ /**
21432
+ * The body this event's `title` is drawn from was cleared by local body
21433
+ * expiry, so an EMPTY title here means "gone", not "never had one".
21434
+ *
21435
+ * A separate flag rather than a sentinel written into `title`: the title is
21436
+ * rendered text, and a store-layer module that invented display copy for it
21437
+ * would be choosing words the view is supposed to choose. Additive and
21438
+ * defaulted, so an older producer still validates.
21439
+ */
21440
+ bodyExpired: external_exports.boolean().default(false)
21360
21441
  }).meta({ id: "ActivityAuditEvent" });
21361
21442
  var ActivitySessionSummary = external_exports.object({
21362
21443
  id: external_exports.string(),
@@ -22697,6 +22778,12 @@ var EventMetadata = external_exports.object({
22697
22778
  // to 'allow' — the enforcement audit trail's link back to the grant that
22698
22779
  // authorized the bypass. Absent on captures where no exception applied.
22699
22780
  exceptionIds: external_exports.array(external_exports.guid()).optional(),
22781
+ // The assistant message this capture belongs to, and the conversation it sits
22782
+ // in — set by the browser extension's network capture so a stored `response`
22783
+ // row can be joined to the `llm_call` leaf describing the same turn. Absent
22784
+ // on every other capture path, which has no such id.
22785
+ messageId: external_exports.string().optional(),
22786
+ conversationId: external_exports.string().optional(),
22700
22787
  // How long THIS capture's inspection blocked its caller, in whole
22701
22788
  // milliseconds — the plugin's own added latency, NOT the LLM call it sat in
22702
22789
  // front of. Measured inside `capture()` (@akasecurity/plugin-sdk) across
@@ -22709,7 +22796,37 @@ var EventMetadata = external_exports.object({
22709
22796
  // Absent is also what every pre-measurement client writes, and what a
22710
22797
  // clock failure degrades to — a reader must treat absence as "not measured"
22711
22798
  // and never as a zero, which would read as "inspection is free".
22712
- inspectionMs: external_exports.number().int().nonnegative().optional()
22799
+ inspectionMs: external_exports.number().int().nonnegative().optional(),
22800
+ // What a `redact` this capture COULD NOT CARRY OUT became instead — the
22801
+ // workspace's `redactFallback`, applied because the field could not be
22802
+ // masked in place (a shell command, a URL, or any argument on a host whose
22803
+ // hook contract offers no rewrite channel).
22804
+ //
22805
+ // It exists because the action alone cannot say why. A finding recorded as
22806
+ // `warn` reads identically whether its detection was ASSIGNED Warn or was
22807
+ // assigned Redact on a field that could not take one — and those are
22808
+ // different facts about the same row: the first is a policy the user chose,
22809
+ // the second is a masking the host could not perform. Absent means no
22810
+ // degrade happened, which is every ordinary capture.
22811
+ //
22812
+ // TWO LIMITS a reader of a stored row has to know, because the grain here
22813
+ // is the CAPTURE while `actionTaken` is per FINDING:
22814
+ //
22815
+ // - It does not say WHICH finding degraded. A capture carrying a degraded
22816
+ // `redact` alongside a finding ASSIGNED the same action stores both
22817
+ // identically and one reason for the pair; attributing it to both
22818
+ // describes the assigned one wrongly, and to neither loses the degrade.
22819
+ // - PRESENCE IS NOT CAUSATION. The value is the action the lost redact
22820
+ // became, not the reason the capture ended as it did — a capture denied
22821
+ // by some other finding's own Block policy still carries `block` here,
22822
+ // and clearing the workspace's fallback would not have let it through.
22823
+ // Gate on the value against what a fallback can produce; never read the
22824
+ // field's presence as "this was the fallback's doing".
22825
+ //
22826
+ // Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
22827
+ // Closing either means moving the reason onto the finding row, which
22828
+ // already carries its own action.
22829
+ redactDegradedTo: ActionTaken.optional()
22713
22830
  }).meta({ id: "EventMetadata" });
22714
22831
  var Event = external_exports.object({
22715
22832
  id: external_exports.guid(),
@@ -22819,7 +22936,32 @@ var RotateKeyInput = external_exports.object({
22819
22936
  confirmation: external_exports.string()
22820
22937
  });
22821
22938
 
22939
+ // ../../packages/schema/src/zod/finding-delivery.ts
22940
+ var KNOWN_REASONS = SyncFailureReason.options;
22941
+ function knownReason(value) {
22942
+ return value !== null && KNOWN_REASONS.includes(value) ? value : void 0;
22943
+ }
22944
+ function deriveFindingDelivery(row) {
22945
+ if (row.kind === "code_change") return { state: "local_scan" };
22946
+ if (row.syncedAt !== null && row.syncedAt > 0) {
22947
+ return { state: "sent", at: epochMillisToIso(row.syncedAt) };
22948
+ }
22949
+ if (row.syncedAt !== null) {
22950
+ const reason = knownReason(row.syncFailure);
22951
+ return {
22952
+ state: "not_sent",
22953
+ ...row.syncFailedAt === null ? {} : { at: epochMillisToIso(row.syncFailedAt) },
22954
+ ...reason === void 0 ? {} : { reason }
22955
+ };
22956
+ }
22957
+ if (row.outboxOwed === 1 || row.syncClaimedAt !== null) return { state: "queued" };
22958
+ return { state: "never_offered" };
22959
+ }
22960
+
22822
22961
  // ../../packages/schema/src/zod/findings-group-build.ts
22962
+ function lookupOwn(map2, key) {
22963
+ return Object.hasOwn(map2, key) ? map2[key] : void 0;
22964
+ }
22823
22965
  function toApiAction(dbVal) {
22824
22966
  const map2 = {
22825
22967
  log: "monitored",
@@ -22828,7 +22970,7 @@ function toApiAction(dbVal) {
22828
22970
  warn: "warned",
22829
22971
  allow: "allowed"
22830
22972
  };
22831
- return map2[dbVal] ?? "allowed";
22973
+ return lookupOwn(map2, dbVal) ?? "allowed";
22832
22974
  }
22833
22975
  function toApiCategory(dbVal) {
22834
22976
  if (dbVal === "code_context") return "source_code";
@@ -22836,13 +22978,18 @@ function toApiCategory(dbVal) {
22836
22978
  return parsed2.success ? parsed2.data : "custom";
22837
22979
  }
22838
22980
  function toApiProvider(sourceTool) {
22839
- return TOOL_TO_HARNESS[sourceTool] ?? HARNESS.Api;
22981
+ return lookupOwn(TOOL_TO_HARNESS, sourceTool) ?? HARNESS.Api;
22840
22982
  }
22841
- var STATUS_PRECEDENCE = ["open", "handled", "dismissed", "resolved"];
22983
+ var FINDING_STATUS_PRECEDENCE = [
22984
+ "open",
22985
+ "handled",
22986
+ "dismissed",
22987
+ "resolved"
22988
+ ];
22842
22989
  function foldGroupStatus(instanceStatuses) {
22843
22990
  const statuses = new Set(instanceStatuses.filter((s) => s !== void 0));
22844
22991
  if (statuses.size === 0) return void 0;
22845
- for (const candidate of STATUS_PRECEDENCE) {
22992
+ for (const candidate of FINDING_STATUS_PRECEDENCE) {
22846
22993
  if (statuses.has(candidate)) return candidate;
22847
22994
  }
22848
22995
  return void 0;
@@ -22949,11 +23096,16 @@ function applyFindingFilters(types, opts) {
22949
23096
  }
22950
23097
  return filtered;
22951
23098
  }
22952
- var SEVERITY_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
22953
- var SEVERITY_RANK = SEVERITY_ORDER;
23099
+ function rankByOrder(members2) {
23100
+ return Object.fromEntries(members2.map((member, index) => [member, index]));
23101
+ }
23102
+ var SEVERITY_RANK = rankByOrder(Severity.options);
23103
+ function severityRank(severity) {
23104
+ return lookupOwn(SEVERITY_RANK, severity);
23105
+ }
22954
23106
  function compareFindingGroupOrder(a, b) {
22955
- const rankA = SEVERITY_RANK[a.severity] ?? -1;
22956
- const rankB = SEVERITY_RANK[b.severity] ?? -1;
23107
+ const rankA = severityRank(a.severity) ?? -1;
23108
+ const rankB = severityRank(b.severity) ?? -1;
22957
23109
  const severityDiff = rankA - rankB;
22958
23110
  if (severityDiff !== 0) return severityDiff;
22959
23111
  const recencyDiff = b.latestDetectedAt.localeCompare(a.latestDetectedAt);
@@ -23028,6 +23180,20 @@ function computeFindingFacets(allTypes, opts) {
23028
23180
  }
23029
23181
 
23030
23182
  // ../../packages/schema/src/zod/findings-flat-build.ts
23183
+ function compareCodePoints(a, b) {
23184
+ const aIter = a[Symbol.iterator]();
23185
+ const bIter = b[Symbol.iterator]();
23186
+ for (; ; ) {
23187
+ const aNext = aIter.next();
23188
+ const bNext = bIter.next();
23189
+ if (aNext.done && bNext.done) return 0;
23190
+ if (aNext.done) return -1;
23191
+ if (bNext.done) return 1;
23192
+ const aPoint = aNext.value.codePointAt(0) ?? 0;
23193
+ const bPoint = bNext.value.codePointAt(0) ?? 0;
23194
+ if (aPoint !== bPoint) return aPoint - bPoint;
23195
+ }
23196
+ }
23031
23197
  function rowHaystack(row) {
23032
23198
  return [
23033
23199
  row.ruleId,
@@ -23052,6 +23218,8 @@ function matchesDimension(row, opts, dimension) {
23052
23218
  return !opts.actions?.length || opts.actions.includes(toApiAction(row.actionTaken));
23053
23219
  case "statuses":
23054
23220
  return !opts.statuses?.length || row.status !== void 0 && opts.statuses.includes(row.status);
23221
+ case "deliveries":
23222
+ return !opts.deliveries?.length || row.delivery !== void 0 && opts.deliveries.includes(row.delivery.state);
23055
23223
  case "tools":
23056
23224
  return !opts.tools?.length || row.toolName !== void 0 && opts.tools.includes(row.toolName);
23057
23225
  // An EMPTY value is a real filter here, not an absent one. The location
@@ -23078,6 +23246,7 @@ var DIMENSIONS = [
23078
23246
  "providers",
23079
23247
  "actions",
23080
23248
  "statuses",
23249
+ "deliveries",
23081
23250
  "tools",
23082
23251
  "repo",
23083
23252
  "file",
@@ -23091,10 +23260,19 @@ function matchesInstanceFilters(row, opts, except) {
23091
23260
  return true;
23092
23261
  }
23093
23262
  function toItems(counts) {
23094
- return [...counts.entries()].map(([value, count]) => ({ value, count })).sort((a, b) => b.count - a.count || a.value.localeCompare(b.value));
23263
+ return [...counts.entries()].map(([value, count]) => ({ value, count })).sort(
23264
+ (a, b) => b.count - a.count || a.value.localeCompare(b.value) || // localeCompare reports canonically-equivalent strings (an NFC and an
23265
+ // NFD spelling of the same text) as equal, so a count tie between
23266
+ // them would otherwise be ordered by whichever the Map iteration
23267
+ // produced. compareCodePoints breaks that tie deterministically, which
23268
+ // makes this a TOTAL order — not one that agrees with SQL collation,
23269
+ // which it need not: foldFacetTuples runs this same sort over grouped
23270
+ // tuples, so both paths order facets identically by construction.
23271
+ compareCodePoints(a.value, b.value)
23272
+ );
23095
23273
  }
23096
- function bump(counts, value) {
23097
- counts.set(value, (counts.get(value) ?? 0) + 1);
23274
+ function bump(counts, value, by = 1) {
23275
+ counts.set(value, (counts.get(value) ?? 0) + by);
23098
23276
  }
23099
23277
  function createInstanceFacetAccumulator(opts) {
23100
23278
  const severity = /* @__PURE__ */ new Map();
@@ -23103,6 +23281,7 @@ function createInstanceFacetAccumulator(opts) {
23103
23281
  const action = /* @__PURE__ */ new Map();
23104
23282
  const status = /* @__PURE__ */ new Map();
23105
23283
  const tool = /* @__PURE__ */ new Map();
23284
+ const deployment = /* @__PURE__ */ new Map();
23106
23285
  return {
23107
23286
  add(row) {
23108
23287
  if (matchesInstanceFilters(row, opts, "severity")) bump(severity, row.severity);
@@ -23117,6 +23296,9 @@ function createInstanceFacetAccumulator(opts) {
23117
23296
  if (row.toolName !== void 0 && matchesInstanceFilters(row, opts, "tools")) {
23118
23297
  bump(tool, row.toolName);
23119
23298
  }
23299
+ if (row.delivery !== void 0 && matchesInstanceFilters(row, opts, "deliveries")) {
23300
+ bump(deployment, row.delivery.state);
23301
+ }
23120
23302
  },
23121
23303
  facets: () => ({
23122
23304
  severity: toItems(severity),
@@ -23124,7 +23306,8 @@ function createInstanceFacetAccumulator(opts) {
23124
23306
  provider: toItems(provider),
23125
23307
  action: toItems(action),
23126
23308
  status: toItems(status),
23127
- tool: toItems(tool)
23309
+ tool: toItems(tool),
23310
+ deployment: toItems(deployment)
23128
23311
  })
23129
23312
  };
23130
23313
  }
@@ -23138,6 +23321,7 @@ function toInstanceDetail(row) {
23138
23321
  ...row.toolName === void 0 ? {} : { toolName: row.toolName },
23139
23322
  eventId: row.eventId,
23140
23323
  ...row.sessionId === void 0 ? {} : { sessionId: row.sessionId },
23324
+ ...row.delivery === void 0 ? {} : { delivery: row.delivery },
23141
23325
  ...row.user === void 0 ? {} : { user: row.user },
23142
23326
  action: toApiAction(row.actionTaken),
23143
23327
  detectedAt: row.occurredAt,
@@ -23152,12 +23336,6 @@ function toInstanceDetail(row) {
23152
23336
  policy: { id: `category:${category}`, name: category }
23153
23337
  };
23154
23338
  }
23155
- var SEVERITY_ORDER2 = {
23156
- critical: 0,
23157
- high: 1,
23158
- medium: 2,
23159
- low: 3
23160
- };
23161
23339
  function newLocationAccumulator() {
23162
23340
  return {
23163
23341
  instanceCount: 0,
@@ -23172,7 +23350,7 @@ function newLocationAccumulator() {
23172
23350
  }
23173
23351
  function addToLocation(acc, row) {
23174
23352
  acc.instanceCount += 1;
23175
- const rank = SEVERITY_ORDER2[row.severity] ?? Number.MAX_SAFE_INTEGER - 1;
23353
+ const rank = severityRank(row.severity) ?? Number.MAX_SAFE_INTEGER - 1;
23176
23354
  if (rank < acc.maxSeverityRank) {
23177
23355
  acc.maxSeverityRank = rank;
23178
23356
  acc.maxSeverity = row.severity;
@@ -23182,15 +23360,15 @@ function addToLocation(acc, row) {
23182
23360
  acc.ruleIds.add(row.ruleId);
23183
23361
  }
23184
23362
  function compareLocationOrder(a, b) {
23185
- const rankA = SEVERITY_ORDER2[a.maxSeverity] ?? -1;
23186
- const rankB = SEVERITY_ORDER2[b.maxSeverity] ?? -1;
23363
+ const rankA = severityRank(a.maxSeverity) ?? -1;
23364
+ const rankB = severityRank(b.maxSeverity) ?? -1;
23187
23365
  if (rankA !== rankB) return rankA - rankB;
23188
23366
  if (a.latestDetectedAt !== b.latestDetectedAt) {
23189
23367
  return a.latestDetectedAt < b.latestDetectedAt ? 1 : -1;
23190
23368
  }
23191
- if (a.repo !== b.repo) return a.repo < b.repo ? -1 : 1;
23192
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
23193
- return 0;
23369
+ const repoDiff = compareCodePoints(a.repo, b.repo);
23370
+ if (repoDiff !== 0) return repoDiff;
23371
+ return compareCodePoints(a.file, b.file);
23194
23372
  }
23195
23373
  function encodeLocationId(repo, file2) {
23196
23374
  return `${encodePart(repo)}/${encodePart(file2)}`;
@@ -23265,6 +23443,11 @@ var Policy = external_exports.object({
23265
23443
  // test `prohibitedModels` passes and `reversibleRuleIds` fails.
23266
23444
  provenance: PolicyProvenance.optional()
23267
23445
  }).meta({ id: "Policy" });
23446
+ var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23447
+ var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23448
+ var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23449
+ id: "RedactFallback"
23450
+ });
23268
23451
  var PolicyBundle = external_exports.object({
23269
23452
  version: external_exports.string(),
23270
23453
  policies: external_exports.array(Policy),
@@ -23312,6 +23495,16 @@ var PolicyBundle = external_exports.object({
23312
23495
  // control plane), so no name resolution stands between the decision and the
23313
23496
  // comparison.
23314
23497
  prohibitedModels: external_exports.array(external_exports.string()).optional(),
23498
+ // What a resolved `redact` becomes on a field the host cannot rewrite, as
23499
+ // the ORGANIZATION would have it. Merged raise-only against the device's own
23500
+ // `WorkspaceSettings.redactFallback` (see strongerRedactFallback below), so
23501
+ // a control plane can tighten a machine and never loosen one — the same
23502
+ // direction `mergeRaiseOnly` enforces for policies.
23503
+ //
23504
+ // Optional so an older backend, and an older on-disk cache, still parses;
23505
+ // absent leaves the device's own setting in force, which is the behaviour
23506
+ // that predates the field and the safe direction to default.
23507
+ redactFallback: RedactFallback.optional(),
23315
23508
  customKeywords: external_exports.array(external_exports.string()),
23316
23509
  fetchedAt: external_exports.iso.datetime()
23317
23510
  }).meta({ id: "PolicyBundle" });
@@ -23341,11 +23534,6 @@ function severityFloorPolicy(category) {
23341
23534
  const peak = CATEGORY_PEAK_SEVERITY[category];
23342
23535
  return peak === "critical" || peak === "high" ? "warn" : "monitor";
23343
23536
  }
23344
- var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
23345
- var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
23346
- var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
23347
- id: "RedactFallback"
23348
- });
23349
23537
  var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
23350
23538
  var BUILTIN_POLICY_SPECS = {
23351
23539
  monitor: {
@@ -23638,7 +23826,7 @@ var VaultConsent = external_exports.object({
23638
23826
  });
23639
23827
 
23640
23828
  // ../../packages/schema/src/zod/local.ts
23641
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23829
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23642
23830
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23643
23831
  var HISTORY_SYNC_PAYLOAD_VERSION = 3;
23644
23832
  var RunMode = external_exports.enum(["standalone", "attached"]);
@@ -23663,6 +23851,15 @@ function isHistorySyncConsentValid(consent, endpoint) {
23663
23851
  if (consent === void 0 || endpoint === void 0) return false;
23664
23852
  return consent.payloadVersion === HISTORY_SYNC_PAYLOAD_VERSION && consent.endpoint === endpoint;
23665
23853
  }
23854
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23855
+ var BodyRetention = external_exports.object({
23856
+ enabled: external_exports.boolean().default(false),
23857
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23858
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23859
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23860
+ // candidate set that is already bounded by "delivered, or never owed".
23861
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23862
+ }).meta({ id: "BodyRetention" });
23666
23863
  var WorkspaceSettings = external_exports.object({
23667
23864
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23668
23865
  runMode: RunMode.default("standalone"),
@@ -23711,7 +23908,13 @@ var WorkspaceSettings = external_exports.object({
23711
23908
  // carry prompt/reply/tool-output text in `content`; the key name predates
23712
23909
  // both widenings. Absent until granted, and a grant for a different endpoint
23713
23910
  // or an older payload no longer counts.
23714
- historySyncConsent: HistorySyncConsent.optional()
23911
+ historySyncConsent: HistorySyncConsent.optional(),
23912
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23913
+ // body never removes the row or its findings.
23914
+ bodyRetention: BodyRetention.default({
23915
+ enabled: false,
23916
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23917
+ })
23715
23918
  });
23716
23919
  function defaultWorkspaceSettings() {
23717
23920
  return WorkspaceSettings.parse({});
@@ -23806,12 +24009,15 @@ function toCaptureAttributes(event) {
23806
24009
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23807
24010
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23808
24011
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24012
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23809
24013
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23810
24014
  // has ever populated either), but every legacy metadata key still rides
23811
24015
  // the bag rather than being silently dropped — CaptureAttributes'
23812
24016
  // `.catchall(z.unknown())` carries the long tail.
23813
24017
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23814
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24018
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24019
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24020
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23815
24021
  };
23816
24022
  }
23817
24023
  function captureDefinitionVersion(finding) {
@@ -23839,13 +24045,22 @@ var ManagedSettingKey = external_exports.enum([
23839
24045
  "vaultInlineReveal",
23840
24046
  "modelJudgeConsent",
23841
24047
  "dataSharesInPlace",
23842
- "redactFallback"
24048
+ "redactFallback",
24049
+ // Pins the toggle and the day count together — see BodyRetention on why the
24050
+ // two are one unit. An administrator mandating a window wants the count
24051
+ // enforced with it, not one a user can widen while the toggle stays on.
24052
+ "bodyRetention"
23843
24053
  ]).meta({ id: "ManagedSettingKey" });
23844
24054
  function isManagedSettingKey(value) {
23845
24055
  return ManagedSettingKey.safeParse(value).success;
23846
24056
  }
23847
24057
  var ManagedSettingsValues = external_exports.object({
23848
24058
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24059
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24060
+ // plain, non-strict objects: a key under either that this build does not know
24061
+ // is stripped and nothing reports it. The unknown-value split in
24062
+ // ManagedSettings below classifies top-level names only, so it stops at
24063
+ // these boundaries.
23849
24064
  controlPlane: external_exports.object({
23850
24065
  endpoint: external_exports.string().min(1),
23851
24066
  label: external_exports.string().min(1).optional()
@@ -23856,7 +24071,8 @@ var ManagedSettingsValues = external_exports.object({
23856
24071
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23857
24072
  modelJudgeConsent: external_exports.boolean().optional(),
23858
24073
  dataSharesInPlace: external_exports.boolean().optional(),
23859
- redactFallback: RedactFallback.optional()
24074
+ redactFallback: RedactFallback.optional(),
24075
+ bodyRetention: BodyRetention.optional()
23860
24076
  }).meta({ id: "ManagedSettingsValues" });
23861
24077
  var ManagedSettings = external_exports.object({
23862
24078
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23864,7 +24080,21 @@ var ManagedSettings = external_exports.object({
23864
24080
  // decision from a bug. Absent renders as a generic "your organization".
23865
24081
  organization: external_exports.string().min(1).optional(),
23866
24082
  // What the administrator pinned.
23867
- values: ManagedSettingsValues.default({}),
24083
+ //
24084
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24085
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24086
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24087
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24088
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24089
+ // exactly the file an administrator is most likely to write while a fleet
24090
+ // is mid-upgrade.
24091
+ //
24092
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24093
+ // file, which is the outcome the lock half already rejected — an older
24094
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24095
+ // value still fails, because the nested schema is re-run over the known
24096
+ // subset and its issues are re-raised on this parse.
24097
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23868
24098
  // Which of those the user may not change. A key here with no matching value
23869
24099
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23870
24100
  // the user may still override. The two are separable on purpose.
@@ -23877,17 +24107,31 @@ var ManagedSettings = external_exports.object({
23877
24107
  // the fleets most likely to carry a version skew. A name outside the enum
23878
24108
  // is still never HONOURED: the lockable set stays explicit above.
23879
24109
  lockedFields: external_exports.array(external_exports.string()).default([])
23880
- }).transform(({ lockedFields, ...rest }) => {
24110
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
23881
24111
  const known = [];
23882
24112
  const unknown2 = [];
23883
24113
  for (const name of lockedFields) {
23884
24114
  if (isManagedSettingKey(name)) known.push(name);
23885
24115
  else unknown2.push(name);
23886
24116
  }
24117
+ const knownValues = /* @__PURE__ */ Object.create(null);
24118
+ const unknownValues = [];
24119
+ for (const [name, value] of Object.entries(values)) {
24120
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24121
+ else unknownValues.push(name);
24122
+ }
24123
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24124
+ if (!pinned.success) {
24125
+ for (const issue2 of pinned.error.issues)
24126
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24127
+ return external_exports.NEVER;
24128
+ }
23887
24129
  return {
23888
24130
  ...rest,
24131
+ values: pinned.data,
23889
24132
  lockedFields: known,
23890
- ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
24133
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24134
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
23891
24135
  };
23892
24136
  }).meta({ id: "ManagedSettings" });
23893
24137
 
@@ -24151,7 +24395,23 @@ var SaveSettingsInput = external_exports.object({
24151
24395
  modelJudgeConsent: ModelJudgeConsentChoice,
24152
24396
  historySyncConsent: HistorySyncConsentChoice,
24153
24397
  vaultConsent: external_exports.string(),
24154
- vaultInlineReveal: external_exports.string()
24398
+ vaultInlineReveal: external_exports.string(),
24399
+ // Widened to `string` like its neighbours rather than typed as
24400
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24401
+ // the call site, so the domain check receives the type it was written for.
24402
+ //
24403
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24404
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24405
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24406
+ // trade against. The real cost runs the other way and is the part worth
24407
+ // knowing: a value this schema admits and the domain enum then rejects lands
24408
+ // on the action's shared refusal, which names NO field, where a shape
24409
+ // rejection reaches `malformedInput` and names the schema key.
24410
+ redactFallback: external_exports.string(),
24411
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24412
+ // `BodyRetention`'s and the action checks it there, so there is one place
24413
+ // that decides what a legal horizon is rather than two that can drift.
24414
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24155
24415
  });
24156
24416
  var AttachInput = external_exports.object({
24157
24417
  endpoint: external_exports.string(),
@@ -24323,6 +24583,52 @@ function reviewSeverityRank(reasons) {
24323
24583
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24324
24584
  }
24325
24585
 
24586
+ // ../../packages/schema/src/zod/web-capture.ts
24587
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24588
+ var WebUsage = external_exports.object({
24589
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24590
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24591
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24592
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24593
+ });
24594
+ var WebToolCall = external_exports.object({
24595
+ toolUseId: external_exports.string().min(1),
24596
+ toolName: external_exports.string().min(1),
24597
+ target: external_exports.string().optional(),
24598
+ isError: external_exports.boolean().optional(),
24599
+ inputSize: external_exports.number().int().nonnegative().optional(),
24600
+ outputSize: external_exports.number().int().nonnegative().optional()
24601
+ });
24602
+ var WebExchange = external_exports.object({
24603
+ messageId: external_exports.string().min(1),
24604
+ startedAt: external_exports.iso.datetime(),
24605
+ model: external_exports.string().optional(),
24606
+ usage: WebUsage.optional(),
24607
+ usageSource: WebUsageSource,
24608
+ stopReason: external_exports.string().optional(),
24609
+ conversationId: external_exports.string().optional(),
24610
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24611
+ toolCalls: external_exports.array(WebToolCall).default([]),
24612
+ // Absent when the adapter recovered no text. Capped by the caller at
24613
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24614
+ // short capture is never mistaken for a short reply.
24615
+ responseText: external_exports.string().optional(),
24616
+ truncated: external_exports.boolean().default(false)
24617
+ });
24618
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24619
+ var WebCaptureStatus = external_exports.object({
24620
+ patched: external_exports.boolean(),
24621
+ live: external_exports.boolean(),
24622
+ blind: external_exports.boolean(),
24623
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24624
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24625
+ parseFailures: external_exports.number().int().nonnegative(),
24626
+ unparsedBodies: external_exports.number().int().nonnegative(),
24627
+ // The adapter-declared JSON key paths that were absent from a real payload —
24628
+ // the earliest signal that a site's contract moved.
24629
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24630
+ });
24631
+
24326
24632
  // ../../packages/persistence/src/paths.ts
24327
24633
  import {
24328
24634
  chmodSync,
@@ -24611,6 +24917,22 @@ function discardStore(file2, backup) {
24611
24917
  }
24612
24918
  }
24613
24919
 
24920
+ // ../../packages/persistence/src/internal/sql-functions.ts
24921
+ var utf8 = new TextDecoder();
24922
+ function akaLower(value) {
24923
+ if (value === null) return null;
24924
+ if (typeof value === "string") return value.toLowerCase();
24925
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
24926
+ return utf8.decode(value).toLowerCase();
24927
+ }
24928
+ function registerSqlFunctions(db) {
24929
+ db.function(
24930
+ "aka_lower",
24931
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
24932
+ akaLower
24933
+ );
24934
+ }
24935
+
24614
24936
  // ../../packages/persistence/src/internal/sql-text.ts
24615
24937
  function escapeLikePattern(s) {
24616
24938
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24695,6 +25017,11 @@ function schemaObjectExists(db, kind, name) {
24695
25017
  function indexExists(db, name) {
24696
25018
  return schemaObjectExists(db, "index", name);
24697
25019
  }
25020
+ function indexColumns(db, name) {
25021
+ if (!indexExists(db, name)) return [];
25022
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25023
+ return columns.map((c) => c.name).filter((c) => c !== null);
25024
+ }
24698
25025
  function columnNames(db, table, opts) {
24699
25026
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24700
25027
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24756,178 +25083,821 @@ function mapRowsTolerant(rows, map2) {
24756
25083
  return out;
24757
25084
  }
24758
25085
 
24759
- // ../../packages/persistence/src/migrations.ts
24760
- function describeObject(object2) {
24761
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24762
- }
24763
- function splitStatements(sql) {
24764
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24765
- }
24766
- function createdIndexName(statement) {
24767
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24768
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25086
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25087
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25088
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25089
+
25090
+ // ../../packages/persistence/src/sync-failure.ts
25091
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25092
+ function syncFailureRejectCondition(column = "sync_failure") {
25093
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25094
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24769
25095
  }
24770
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24771
- function applyMigrations(db, file2) {
24772
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24773
- db.exec(
24774
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24775
- );
24776
- const applied = new Set(
24777
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24778
- );
24779
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24780
- const record2 = db.prepare(
24781
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24782
- );
24783
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24784
- if (applied.has(migration.tag)) continue;
24785
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24786
- const evidence = evidenceObjects(migration.sql);
24787
- const present = evidence.filter((o) => evidenceExists(db, o));
24788
- if (present.length > 0 && present.length < evidence.length) {
24789
- const missing = evidence.filter((o) => !present.includes(o));
24790
- 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.`;
24791
- akaWarn(message);
24792
- throw new Error(`[aka] ${message}`);
24793
- }
24794
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24795
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24796
- const statements = splitStatements(migration.sql);
24797
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24798
- try {
24799
- withTransaction(
24800
- db,
24801
- () => {
24802
- for (const statement of statements) {
24803
- const indexName = createdIndexName(statement);
24804
- if (indexName === void 0) {
24805
- if (alreadyApplied) continue;
24806
- } else if (indexExists(db, indexName)) {
24807
- continue;
24808
- }
24809
- db.exec(statement);
24810
- }
24811
- if (wantsFkOff && !alreadyApplied) {
24812
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24813
- if (violations.length > 0) {
24814
- throw new Error(
24815
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24816
- );
24817
- }
24818
- }
24819
- record2.run(migration.tag, Date.now());
24820
- },
24821
- "IMMEDIATE"
24822
- );
24823
- } finally {
24824
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24825
- }
25096
+
25097
+ // ../../packages/persistence/src/repositories/history-sync.ts
25098
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25099
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25100
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25101
+ var COUNTED_EVENT_TYPES = [
25102
+ ...STRUCTURAL_EVENT_TYPES,
25103
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25104
+ ];
25105
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25106
+ var PARTITION_BUCKETS = `
25107
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25108
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25109
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25110
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25111
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25112
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25113
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25114
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25115
+ -- added later lands in no bucket and fails the sum assertion, instead
25116
+ -- of silently joining this one.
25117
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25118
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25119
+ THEN 1 ELSE 0 END) AS failed,
25120
+ COUNT(*) AS total`;
25121
+ var COUNTED_SCOPE = `
25122
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25123
+ AND (
25124
+ event_type IN (${TYPE_LIST})
25125
+ OR synced_at IS NOT NULL
25126
+ OR outbox_owed = 1
25127
+ )`;
25128
+ var SKIPPED = -1;
25129
+ var HISTORY_SYNC_LEASE_STALE_MS = 6e4;
25130
+ var ROW_COLUMNS = `id,
25131
+ parent_id AS parentId,
25132
+ root_session_id AS rootSessionId,
25133
+ event_type AS eventType,
25134
+ host_id AS hostId,
25135
+ harness_id AS harnessId,
25136
+ source_project_id AS sourceProjectId,
25137
+ started_at AS startedAt,
25138
+ ended_at AS endedAt,
25139
+ severity,
25140
+ priority,
25141
+ content,
25142
+ content_hash AS contentHash,
25143
+ attributes`;
25144
+ var SqliteHistorySyncRepository = class {
25145
+ constructor(db) {
25146
+ this.db = db;
25147
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25148
+ this.sessionsStmt = db.prepare(
25149
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25150
+ FROM audit_events
25151
+ WHERE synced_at IS NULL
25152
+ AND event_type IN (${TYPE_LIST})
25153
+ AND started_at < :before
25154
+ GROUP BY sessionId
25155
+ ORDER BY earliest
25156
+ LIMIT :limit`
25157
+ );
25158
+ this.rowsStmt = db.prepare(
25159
+ `SELECT ${ROW_COLUMNS}
25160
+ FROM audit_events
25161
+ WHERE synced_at IS NULL
25162
+ AND event_type IN (${TYPE_LIST})
25163
+ AND started_at < :before
25164
+ AND COALESCE(root_session_id, id) = :sessionId
25165
+ ORDER BY (event_type = 'session') DESC, started_at
25166
+ LIMIT :limit`
25167
+ );
25168
+ this.captureRowsStmt = db.prepare(
25169
+ `SELECT ${ROW_COLUMNS}
25170
+ FROM audit_events
25171
+ WHERE synced_at IS NULL
25172
+ AND sync_claimed_at IS NULL
25173
+ AND outbox_owed = 1
25174
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25175
+ AND started_at < :before
25176
+ ORDER BY started_at
25177
+ LIMIT :limit`
25178
+ );
25179
+ this.markOwedStmt = db.prepare(
25180
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25181
+ );
25182
+ this.markCaptureBacklogOwedStmt = db.prepare(
25183
+ `UPDATE audit_events SET outbox_owed = 1
25184
+ WHERE synced_at IS NULL
25185
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25186
+ AND started_at < :before`
25187
+ );
25188
+ this.stampStmt = db.prepare(
25189
+ `UPDATE audit_events
25190
+ SET synced_at = :at,
25191
+ sync_claimed_at = NULL,
25192
+ sync_failed_at = :failedAt,
25193
+ sync_failure = :failure
25194
+ WHERE id = :id`
25195
+ );
25196
+ this.claimRowStmt = db.prepare(
25197
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25198
+ );
25199
+ this.releaseRowStmt = db.prepare(
25200
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25201
+ );
25202
+ this.releaseStaleClaimsStmt = db.prepare(
25203
+ `UPDATE audit_events SET sync_claimed_at = NULL
25204
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25205
+ );
25206
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25207
+ FROM audit_events${COUNTED_SCOPE}`);
25208
+ this.partitionByKindStmt = db.prepare(
25209
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25210
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25211
+ GROUP BY event_type`
25212
+ );
25213
+ this.countsStmt = db.prepare(
25214
+ `SELECT
25215
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25216
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25217
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25218
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25219
+ THEN 1 ELSE 0 END) AS skipped,
25220
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25221
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25222
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25223
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25224
+ FROM audit_events
25225
+ WHERE event_type IN (${TYPE_LIST})`
25226
+ );
25227
+ this.captureSkipCountStmt = db.prepare(
25228
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25229
+ // way the structural totals are. The split exists because a refusal is
25230
+ // terminal only against the deployment that gave it, and the structural
25231
+ // re-arm frees it on a change of deployment. The capture lane has no such
25232
+ // escape: re-arming a capture would offer one deployment's undelivered
25233
+ // prompts, with their text, to a deployment that never saw them, which is
25234
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25235
+ // reasons mean the same thing — this row will not be sent — and splitting
25236
+ // them would put refused captures in a bucket nothing reads and nothing
25237
+ // frees.
25238
+ `SELECT COUNT(*) AS skipped
25239
+ FROM audit_events
25240
+ WHERE synced_at = ${String(SKIPPED)}
25241
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25242
+ );
25243
+ this.fingerprintStmt = db.prepare(
25244
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25245
+ FROM history_sync WHERE id = 1`
25246
+ );
25247
+ this.setFingerprintStmt = db.prepare(
25248
+ `UPDATE history_sync
25249
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25250
+ WHERE id = 1`
25251
+ );
25252
+ this.disownCapturesStmt = db.prepare(
25253
+ `UPDATE audit_events SET outbox_owed = NULL
25254
+ WHERE outbox_owed IS NOT NULL
25255
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25256
+ AND started_at < :attachedAt`
25257
+ );
25258
+ this.rearmStmt = db.prepare(
25259
+ `UPDATE audit_events
25260
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25261
+ WHERE (synced_at > 0
25262
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25263
+ AND event_type IN (${TYPE_LIST})`
25264
+ );
25265
+ this.claimStmt = db.prepare(
25266
+ `UPDATE history_sync
25267
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25268
+ WHERE id = 1
25269
+ AND (owner_pid IS NULL
25270
+ OR heartbeat_at IS NULL
25271
+ OR heartbeat_at < :staleBefore
25272
+ OR heartbeat_at > :now)`
25273
+ );
25274
+ this.heartbeatStmt = db.prepare(
25275
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25276
+ );
25277
+ this.releaseStmt = db.prepare(
25278
+ `UPDATE history_sync
25279
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25280
+ WHERE id = 1 AND owner_pid = :pid`
25281
+ );
25282
+ this.closeWindowStmt = db.prepare(
25283
+ `UPDATE audit_events
25284
+ SET synced_at = ${String(SKIPPED)},
25285
+ sync_failed_at = :at,
25286
+ sync_failure = 'detached_undelivered'
25287
+ WHERE synced_at IS NULL
25288
+ AND event_type IN (${TYPE_LIST})
25289
+ AND started_at >= :attachedAt`
25290
+ );
25291
+ this.releaseBoundaryStmt = db.prepare(
25292
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25293
+ );
25294
+ this.freezeBoundaryStmt = db.prepare(
25295
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25296
+ );
25297
+ this.leaseStmt = db.prepare(
25298
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25299
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25300
+ FROM history_sync WHERE id = 1`
25301
+ );
25302
+ this.inspectionsStmt = db.prepare(
25303
+ `SELECT d.rule_id AS ruleId,
25304
+ d.name AS ruleName,
25305
+ d.version AS ruleVersion,
25306
+ d.category AS category,
25307
+ d.severity AS severity,
25308
+ f.span_start AS spanStart,
25309
+ f.span_end AS spanEnd,
25310
+ f.masked_match AS maskedMatch,
25311
+ f.action_taken AS actionTaken,
25312
+ f.confidence AS confidence
25313
+ FROM inspection_findings f
25314
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25315
+ WHERE f.audit_event_id = :auditEventId
25316
+ ORDER BY f.span_start, f.id`
25317
+ );
24826
25318
  }
24827
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24828
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25319
+ db;
25320
+ ensureRowStmt;
25321
+ sessionsStmt;
25322
+ rowsStmt;
25323
+ stampStmt;
25324
+ countsStmt;
25325
+ fingerprintStmt;
25326
+ setFingerprintStmt;
25327
+ rearmStmt;
25328
+ claimStmt;
25329
+ heartbeatStmt;
25330
+ releaseStmt;
25331
+ leaseStmt;
25332
+ inspectionsStmt;
25333
+ closeWindowStmt;
25334
+ releaseBoundaryStmt;
25335
+ freezeBoundaryStmt;
25336
+ captureRowsStmt;
25337
+ markOwedStmt;
25338
+ markCaptureBacklogOwedStmt;
25339
+ captureSkipCountStmt;
25340
+ disownCapturesStmt;
25341
+ partitionStmt;
25342
+ partitionByKindStmt;
25343
+ claimRowStmt;
25344
+ releaseRowStmt;
25345
+ releaseStaleClaimsStmt;
25346
+ /**
25347
+ * The masked detections recorded against one tool call.
25348
+ *
25349
+ * These travel with the event because a tool call's target is not
25350
+ * re-inspectable from the event alone — unlike a capture, where the text
25351
+ * itself is re-scannable. What crosses is the masked match and the rule that
25352
+ * produced it, never the value.
25353
+ */
25354
+ inspectionsFor(auditEventId) {
25355
+ return allRows(this.inspectionsStmt, { auditEventId });
24829
25356
  }
24830
- ensureSyncedAtColumn(db, "audit_events");
24831
- ensureScanLedgerTable(db);
24832
- ensureHistorySyncTable(db);
24833
- ensureBlockedDetectionsTable(db);
24834
- ensureRuleProbeCacheTable(db);
24835
- ensureWriteGateTrigger(db);
24836
- ensureTokenUsageColumns(db);
24837
- reconcileSourceProjectIds(db);
24838
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24839
- const drained = runLegacyHistoryBackfill(db);
24840
- if (drained) applyLegacyDropMigration(db, file2);
25357
+ /**
25358
+ * Sessions with structural rows still to send, oldest first.
25359
+ *
25360
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25361
+ * read. Anything recorded after the machine attached is the live forward
25362
+ * path's to deliver; this drain exists for what was recorded before it, and a
25363
+ * row both paths send is at best a duplicate request and at worst — for a
25364
+ * session root — an overwrite of the inventory ids the live path resolved.
25365
+ */
25366
+ pendingSessions(limit, before) {
25367
+ return allRows(this.sessionsStmt, { limit, before }).map(
25368
+ (r) => r.sessionId
25369
+ );
24841
25370
  }
24842
- }
24843
- function readLegacyTables(db) {
24844
- let holdsRows = false;
24845
- const marks = [];
24846
- for (const table of ["events", "findings"]) {
24847
- try {
24848
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
24849
- if (row === void 0) {
24850
- holdsRows = true;
24851
- marks.push(`${table}:unreadable`);
24852
- continue;
24853
- }
24854
- if (row.n > 0) holdsRows = true;
24855
- marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
24856
- } catch {
24857
- holdsRows = true;
24858
- marks.push(`${table}:unreadable`);
24859
- }
25371
+ /** One session's undelivered structural rows within the backlog, root first. */
25372
+ pendingRows(sessionId, limit, before) {
25373
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24860
25374
  }
24861
- return { holdsRows, mark: marks.join("|") };
24862
- }
24863
- function applyLegacyDropMigration(db, file2) {
24864
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24865
- if (!migration) return;
24866
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24867
- if (file2 !== void 0 && before?.holdsRows === true) {
24868
- try {
24869
- backupBeforeLegacyDrop(db, file2);
24870
- } catch (error61) {
24871
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24872
- return;
24873
- }
25375
+ /**
25376
+ * Captures this machine still owes the deployment, oldest first.
25377
+ *
25378
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25379
+ * by a time window — see captureRowsStmt for why a window could not express
25380
+ * this. `before` is the grace window that leaves a just-recorded capture to
25381
+ * the live path.
25382
+ */
25383
+ pendingCaptureRows(limit, before) {
25384
+ return allRows(this.captureRowsStmt, { limit, before });
24874
25385
  }
24875
- try {
25386
+ /**
25387
+ * Record that a capture is OWED to the deployment.
25388
+ *
25389
+ * Written by the attached forward path when a live send did not confirm
25390
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25391
+ * a fact rather than an inference: the machine was attached, the send did not
25392
+ * land, so the row is owed — which no time window can state, because the same
25393
+ * window that holds the rows a past attachment left owed also holds every
25394
+ * capture recorded while the machine was DETACHED, and those were never
25395
+ * offered to anyone.
25396
+ *
25397
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25398
+ * out of the drain's read.
25399
+ */
25400
+ markCaptureOwed(id) {
25401
+ this.markOwedStmt.run({ id });
25402
+ }
25403
+ /**
25404
+ * Mark every capture already on disk as owed, as of `before`.
25405
+ *
25406
+ * The consent-time backfill, called once from `aka attach` when a human
25407
+ * grants existing-history consent — never from an ongoing drain pass, and
25408
+ * never inferred from a boundary that could later move. `before` is the
25409
+ * caller's own "now" at the moment consent was granted, so what this marks
25410
+ * is exactly the backlog the consent prompt already counted, not whatever a
25411
+ * later re-attach or key rotation might widen it to.
25412
+ *
25413
+ * Returns how many rows matched, for the caller to log or test against. Not a
25414
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25415
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25416
+ */
25417
+ markCaptureBacklogOwed(before) {
25418
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25419
+ }
25420
+ /**
25421
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25422
+ *
25423
+ * CLEARS any failure reason in the same statement. A row that failed against
25424
+ * one deployment and then landed is delivered, and leaving the reason behind
25425
+ * would leave the store holding two contradictory answers about one row —
25426
+ * with the surface free to render either.
25427
+ */
25428
+ markSynced(ids, atMs) {
25429
+ this.stampAll(ids, atMs, null);
25430
+ }
25431
+ /**
25432
+ * Record that THIS MACHINE cannot express the row on the wire.
25433
+ *
25434
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25435
+ * payload, or a body the client itself refused to send. It fails identically
25436
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25437
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25438
+ * is retried; marking those would turn one outage into permanent data loss.
25439
+ */
25440
+ markSkipped(ids, atMs) {
25441
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25442
+ }
25443
+ /**
25444
+ * Record that THIS DEPLOYMENT refused the row.
25445
+ *
25446
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25447
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25448
+ * row is outstanding rather than why. What separates them is the reason, and
25449
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25450
+ * on one body, so it is terminal only for as long as this machine points at
25451
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25452
+ *
25453
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25454
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25455
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25456
+ */
25457
+ markRefused(ids, atMs) {
25458
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25459
+ }
25460
+ eachInTransaction(ids, run) {
25461
+ if (ids.length === 0) return;
24876
25462
  withTransaction(
24877
- db,
25463
+ this.db,
24878
25464
  () => {
24879
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24880
- if (alreadyDropped) return;
24881
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24882
- akaWarn(
24883
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24884
- );
24885
- return;
24886
- }
24887
- for (const statement of splitStatements(migration.sql)) {
24888
- db.exec(statement);
24889
- }
24890
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
24891
- migration.tag,
24892
- Date.now()
24893
- );
25465
+ for (const id of ids) run(id);
24894
25466
  },
24895
25467
  "IMMEDIATE"
24896
25468
  );
24897
- } catch (error61) {
24898
- akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
24899
25469
  }
24900
- }
24901
- function backupBeforeLegacyDrop(db, file2) {
24902
- reapStalePartials(file2);
24903
- const backup = backupPath(file2, "pre-drop");
24904
- snapshotStore(db, backup);
24905
- return backup;
24906
- }
24907
- var TOKEN_USAGE_COLUMNS = [
24908
- {
24909
- name: "input_tokens",
24910
- ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
24911
- },
24912
- {
24913
- name: "output_tokens",
24914
- ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
24915
- },
24916
- {
24917
- name: "cache_creation_input_tokens",
24918
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
24919
- },
24920
- {
24921
- name: "cache_read_input_tokens",
24922
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
24923
- },
24924
- {
24925
- name: "model",
24926
- ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
24927
- },
24928
- {
24929
- name: "provider",
24930
- ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
25470
+ stampAll(ids, value, failure, failedAtMs) {
25471
+ if (ids.length === 0) return;
25472
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25473
+ withTransaction(
25474
+ this.db,
25475
+ () => {
25476
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25477
+ },
25478
+ "IMMEDIATE"
25479
+ );
25480
+ }
25481
+ /**
25482
+ * Claim rows as in-flight.
25483
+ *
25484
+ * Advisory in exactly the sense the lease is: it records that a send is in
25485
+ * progress so a surface can say so, and a lost claim costs a row showing as
25486
+ * queued while it is actually being sent. It is not exclusion — the far side
25487
+ * settles a duplicate on the row id.
25488
+ */
25489
+ claimRows(ids, atMs) {
25490
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25491
+ }
25492
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25493
+ releaseRows(ids) {
25494
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25495
+ }
25496
+ /**
25497
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25498
+ *
25499
+ * A process killed between claiming and settling leaves rows claimed with
25500
+ * nothing left to settle them. Without this they read as "sending" for ever.
25501
+ */
25502
+ releaseStaleClaims(staleBefore) {
25503
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25504
+ }
25505
+ /**
25506
+ * Every tracked row in exactly one delivery state.
25507
+ *
25508
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25509
+ * pick up now", which is a different question from "what state is this row
25510
+ * in" — and a machine that has never attached has no boundary to pass, so
25511
+ * requiring one would force a caller to invent one and report the whole store
25512
+ * as queued.
25513
+ */
25514
+ /**
25515
+ * The same partition, one row per kind that a lane carries.
25516
+ *
25517
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25518
+ * scope decides which rows exist at all, so a kind that has never been
25519
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25520
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25521
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25522
+ * different things.
25523
+ */
25524
+ partitionByKind() {
25525
+ return allRows(
25526
+ this.partitionByKindStmt,
25527
+ {}
25528
+ ).map((row) => ({
25529
+ kind: row.kind,
25530
+ queued: row.queued ?? 0,
25531
+ inProgress: row.inProgress ?? 0,
25532
+ synced: row.synced ?? 0,
25533
+ failed: row.failed ?? 0,
25534
+ refused: row.refused ?? 0,
25535
+ detached: row.detached ?? 0,
25536
+ total: row.total ?? 0
25537
+ }));
25538
+ }
25539
+ partition() {
25540
+ const row = getRow(this.partitionStmt, {});
25541
+ return {
25542
+ queued: row?.queued ?? 0,
25543
+ inProgress: row?.inProgress ?? 0,
25544
+ synced: row?.synced ?? 0,
25545
+ failed: row?.failed ?? 0,
25546
+ refused: row?.refused ?? 0,
25547
+ detached: row?.detached ?? 0,
25548
+ total: row?.total ?? 0
25549
+ };
25550
+ }
25551
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25552
+ counts(before) {
25553
+ const row = getRow(this.countsStmt, { before });
25554
+ const captures = getRow(this.captureSkipCountStmt);
25555
+ return {
25556
+ pending: row?.pending ?? 0,
25557
+ sent: row?.sent ?? 0,
25558
+ skipped: row?.skipped ?? 0,
25559
+ refused: row?.refused ?? 0,
25560
+ detached: row?.detached ?? 0,
25561
+ capturesSkipped: captures?.skipped ?? 0
25562
+ };
25563
+ }
25564
+ /**
25565
+ * The deployment the current stamps were made against, and where its backlog
25566
+ * ends.
25567
+ *
25568
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25569
+ * machine that has never drained is — and every writer below seeds the row
25570
+ * before it needs one, so nothing depends on this creating it. Keeping the
25571
+ * write off the gate path matters because the gate runs on every pass while a
25572
+ * write has to take the database's write lock.
25573
+ */
25574
+ deployment() {
25575
+ const row = getRow(
25576
+ this.fingerprintStmt
25577
+ );
25578
+ return {
25579
+ fingerprint: row?.fingerprint ?? void 0,
25580
+ backlogBefore: row?.backlogBefore ?? void 0
25581
+ };
25582
+ }
25583
+ /**
25584
+ * Point the ledger at a different deployment, discarding what it recorded
25585
+ * about the previous one.
25586
+ *
25587
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25588
+ * machine has just left are undelivered as far as the new one is concerned.
25589
+ * All four in one transaction, so a crash between them cannot leave stamps
25590
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25591
+ * a disown with no re-mark to follow it.
25592
+ *
25593
+ * The boundary is written HERE and only here, which is what freezes it: a
25594
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25595
+ * unchanged, so this never runs and the backlog does not widen back over rows
25596
+ * the live path has since delivered.
25597
+ *
25598
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25599
+ * granted existing-history consent for the deployment this call is arming —
25600
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25601
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25602
+ * apart. Passed only when that grant is valid, since this method has no way
25603
+ * to check consent itself and must not mark a row owed for a machine that
25604
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25605
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25606
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25607
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25608
+ * on the cleared side of that bound — and the re-mark in the same
25609
+ * transaction is what puts those rows back. A crash between the two cannot
25610
+ * strand the ledger disowned with nothing re-marked — the transaction either
25611
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25612
+ * committed re-enters this method on the very next pass. Omit it (the
25613
+ * structural-only tests do) to exercise the disown in isolation.
25614
+ *
25615
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25616
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25617
+ * live path can mark a capture owed from the moment `aka attach` writes the
25618
+ * descriptor, before the drain's first pass ever reaches this method, and
25619
+ * such a row sits at or after the bound rather than below it. What keeps the
25620
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25621
+ * bound — disown runs first, re-mark second, both inside the one
25622
+ * transaction above.
25623
+ */
25624
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25625
+ this.ensureRowStmt.run();
25626
+ withTransaction(
25627
+ this.db,
25628
+ () => {
25629
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25630
+ this.rearmStmt.run();
25631
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25632
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25633
+ }
25634
+ if (backfillCapturesBefore !== void 0) {
25635
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25636
+ }
25637
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25638
+ },
25639
+ "IMMEDIATE"
25640
+ );
25641
+ }
25642
+ /**
25643
+ * End the attached period: hand its rows to the live path, and release the
25644
+ * boundary so the next attachment can freeze a new one.
25645
+ *
25646
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25647
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25648
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25649
+ * during the detached period, because the machine is not attached. Rows
25650
+ * recorded in that window sit after the boundary and before the re-attach, so
25651
+ * neither path takes them, and the pending count reports none outstanding.
25652
+ *
25653
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25654
+ * closing attachment's to deliver and are no longer outstanding — that is what
25655
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25656
+ * distinction is not academic: this used to write a delivery TIME, which every
25657
+ * read treats as delivery, so one detach turned a window of undelivered rows
25658
+ * into a window of delivered ones and no surface could tell. It writes the
25659
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25660
+ * "received" stop being the same fact.
25661
+ *
25662
+ * A change of deployment still frees them (see the re-arm), because the next
25663
+ * deployment has seen none of this machine's history — so the rows reach it
25664
+ * exactly as they did when this wrote a delivery time.
25665
+ *
25666
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25667
+ * window unstamped — that half-state would re-send the whole attached period
25668
+ * on the next attach, which is the failure the boundary exists to prevent.
25669
+ */
25670
+ closeAttachedWindow(attachedAtMs, atMs) {
25671
+ this.ensureRowStmt.run();
25672
+ withTransaction(
25673
+ this.db,
25674
+ () => {
25675
+ const row = getRow(this.fingerprintStmt);
25676
+ const from = row?.backlogBefore ?? attachedAtMs;
25677
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25678
+ this.releaseBoundaryStmt.run();
25679
+ },
25680
+ "IMMEDIATE"
25681
+ );
25682
+ }
25683
+ /**
25684
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25685
+ *
25686
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25687
+ * different deployment and therefore discards what was delivered to the old
25688
+ * one: here the recipient is the same, so everything already sent to it stays
25689
+ * sent.
25690
+ */
25691
+ freezeBoundary(backlogBefore) {
25692
+ this.ensureRowStmt.run();
25693
+ this.freezeBoundaryStmt.run({ backlogBefore });
25694
+ }
25695
+ /** Take the claim, or report that someone live already holds it. */
25696
+ claim(pid, host, nowMs, staleAfterMs) {
25697
+ this.ensureRowStmt.run();
25698
+ let taken = false;
25699
+ withTransaction(
25700
+ this.db,
25701
+ () => {
25702
+ const result = this.claimStmt.run({
25703
+ pid,
25704
+ host,
25705
+ now: nowMs,
25706
+ staleBefore: nowMs - staleAfterMs
25707
+ });
25708
+ taken = result.changes === 1;
25709
+ },
25710
+ "IMMEDIATE"
25711
+ );
25712
+ return taken;
25713
+ }
25714
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25715
+ heartbeat(pid, nowMs) {
25716
+ this.heartbeatStmt.run({ now: nowMs, pid });
25717
+ }
25718
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25719
+ release(pid) {
25720
+ this.releaseStmt.run({ pid });
25721
+ }
25722
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25723
+ lease() {
25724
+ return getRow(this.leaseStmt);
25725
+ }
25726
+ };
25727
+
25728
+ // ../../packages/persistence/src/migrations.ts
25729
+ function describeObject(object2) {
25730
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25731
+ }
25732
+ function splitStatements(sql) {
25733
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25734
+ }
25735
+ function createdIndexName(statement) {
25736
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25737
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25738
+ }
25739
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25740
+ function applyMigrations(db, file2, options = {}) {
25741
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25742
+ db.exec(
25743
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25744
+ );
25745
+ const applied = new Set(
25746
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25747
+ );
25748
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25749
+ const record2 = db.prepare(
25750
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25751
+ );
25752
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25753
+ if (applied.has(migration.tag)) continue;
25754
+ if (options.skipTags?.has(migration.tag) === true) continue;
25755
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25756
+ const evidence = evidenceObjects(migration.sql);
25757
+ const present = evidence.filter((o) => evidenceExists(db, o));
25758
+ if (present.length > 0 && present.length < evidence.length) {
25759
+ const missing = evidence.filter((o) => !present.includes(o));
25760
+ 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.`;
25761
+ akaWarn(message);
25762
+ throw new Error(`[aka] ${message}`);
25763
+ }
25764
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25765
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25766
+ const statements = splitStatements(migration.sql);
25767
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25768
+ try {
25769
+ withTransaction(
25770
+ db,
25771
+ () => {
25772
+ for (const statement of statements) {
25773
+ const indexName = createdIndexName(statement);
25774
+ if (indexName === void 0) {
25775
+ if (alreadyApplied) continue;
25776
+ } else if (indexExists(db, indexName)) {
25777
+ continue;
25778
+ }
25779
+ db.exec(statement);
25780
+ }
25781
+ if (wantsFkOff && !alreadyApplied) {
25782
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25783
+ if (violations.length > 0) {
25784
+ throw new Error(
25785
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25786
+ );
25787
+ }
25788
+ }
25789
+ record2.run(migration.tag, Date.now());
25790
+ },
25791
+ "IMMEDIATE"
25792
+ );
25793
+ } finally {
25794
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25795
+ }
25796
+ }
25797
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25798
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25799
+ }
25800
+ ensureSyncedAtColumn(db, "audit_events");
25801
+ ensureScanLedgerTable(db);
25802
+ ensureHistorySyncTable(db);
25803
+ ensureBlockedDetectionsTable(db);
25804
+ ensureRuleProbeCacheTable(db);
25805
+ ensureWriteGateTrigger(db);
25806
+ ensureTokenUsageColumns(db);
25807
+ reconcileSourceProjectIds(db);
25808
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25809
+ const drained = runLegacyHistoryBackfill(db);
25810
+ if (drained) applyLegacyDropMigration(db, file2);
25811
+ }
25812
+ }
25813
+ function readLegacyTables(db) {
25814
+ let holdsRows = false;
25815
+ const marks = [];
25816
+ for (const table of ["events", "findings"]) {
25817
+ try {
25818
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
25819
+ if (row === void 0) {
25820
+ holdsRows = true;
25821
+ marks.push(`${table}:unreadable`);
25822
+ continue;
25823
+ }
25824
+ if (row.n > 0) holdsRows = true;
25825
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
25826
+ } catch {
25827
+ holdsRows = true;
25828
+ marks.push(`${table}:unreadable`);
25829
+ }
25830
+ }
25831
+ return { holdsRows, mark: marks.join("|") };
25832
+ }
25833
+ function applyLegacyDropMigration(db, file2) {
25834
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25835
+ if (!migration) return;
25836
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25837
+ if (file2 !== void 0 && before?.holdsRows === true) {
25838
+ try {
25839
+ backupBeforeLegacyDrop(db, file2);
25840
+ } catch (error61) {
25841
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25842
+ return;
25843
+ }
25844
+ }
25845
+ try {
25846
+ withTransaction(
25847
+ db,
25848
+ () => {
25849
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25850
+ if (alreadyDropped) return;
25851
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25852
+ akaWarn(
25853
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25854
+ );
25855
+ return;
25856
+ }
25857
+ for (const statement of splitStatements(migration.sql)) {
25858
+ db.exec(statement);
25859
+ }
25860
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25861
+ migration.tag,
25862
+ Date.now()
25863
+ );
25864
+ },
25865
+ "IMMEDIATE"
25866
+ );
25867
+ } catch (error61) {
25868
+ akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
25869
+ }
25870
+ }
25871
+ function backupBeforeLegacyDrop(db, file2) {
25872
+ reapStalePartials(file2);
25873
+ const backup = backupPath(file2, "pre-drop");
25874
+ snapshotStore(db, backup);
25875
+ return backup;
25876
+ }
25877
+ var TOKEN_USAGE_COLUMNS = [
25878
+ {
25879
+ name: "input_tokens",
25880
+ ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
25881
+ },
25882
+ {
25883
+ name: "output_tokens",
25884
+ ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
25885
+ },
25886
+ {
25887
+ name: "cache_creation_input_tokens",
25888
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
25889
+ },
25890
+ {
25891
+ name: "cache_read_input_tokens",
25892
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
25893
+ },
25894
+ {
25895
+ name: "model",
25896
+ ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25897
+ },
25898
+ {
25899
+ name: "provider",
25900
+ ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
24931
25901
  }
24932
25902
  ];
24933
25903
  function ensureTokenUsageColumns(db) {
@@ -25188,10 +26158,62 @@ function ensureSyncedAtColumn(db, table) {
25188
26158
  if (!columns.includes("outbox_owed")) {
25189
26159
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25190
26160
  }
26161
+ if (!columns.includes("sync_failed_at")) {
26162
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26163
+ }
26164
+ if (!columns.includes("sync_failure")) {
26165
+ withTransaction(
26166
+ db,
26167
+ () => {
26168
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26169
+ db.exec(
26170
+ `UPDATE ${table} SET synced_at = NULL
26171
+ WHERE synced_at = -1
26172
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26173
+ );
26174
+ },
26175
+ "IMMEDIATE"
26176
+ );
26177
+ }
25191
26178
  db.exec(
25192
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25193
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26179
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26180
+ BEFORE UPDATE OF sync_failure ON ${table}
26181
+ WHEN ${syncFailureRejectCondition()}
26182
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25194
26183
  );
26184
+ const syncIndexColumns = [
26185
+ "event_type",
26186
+ "synced_at",
26187
+ "sync_claimed_at",
26188
+ "started_at",
26189
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26190
+ // has to be in the index for the read to stay covered — but putting it
26191
+ // ahead of `started_at` would reorder the prefix the structural drain's
26192
+ // reads match on.
26193
+ "sync_failure"
26194
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26195
+ //
26196
+ // The delivery-state read tests it — a capture's state depends on whether a
26197
+ // live forward marked it owed — so carrying it here makes that read covering
26198
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26199
+ // But a sixth column changes what the planner charges for this index, and
26200
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26201
+ // then stops choosing the per-session index for the token rollup and walks
26202
+ // every `llm_call` in the store through the event-type index instead. That
26203
+ // read grows with the store; this one does not.
26204
+ //
26205
+ // 40 ms on the largest store measured, once per render, is a cost worth
26206
+ // paying to leave every other read's plan where it was.
26207
+ ];
26208
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26209
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26210
+ if (!syncIndexMatches) {
26211
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26212
+ db.exec(
26213
+ `CREATE INDEX idx_audit_events_sync
26214
+ ON audit_events (${syncIndexColumns.join(", ")})`
26215
+ );
26216
+ }
25195
26217
  db.exec(
25196
26218
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25197
26219
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25413,7 +26435,11 @@ function buildAuditEvent(row) {
25413
26435
  link: linkParsed?.success ? linkParsed.data : null,
25414
26436
  targetId: row.target_id,
25415
26437
  internal: intToBool(row.internal),
25416
- flagged: intToBool(row.flagged)
26438
+ flagged: intToBool(row.flagged),
26439
+ // Only meaningful when the title came out empty — a row whose body was
26440
+ // expired but whose title fell back to `tool_name` still has something to
26441
+ // render, and flagging it would make the view apologise for nothing.
26442
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25417
26443
  };
25418
26444
  }
25419
26445
  var TIMELINE_COLUMNS = `
@@ -25421,6 +26447,7 @@ var TIMELINE_COLUMNS = `
25421
26447
  event_type,
25422
26448
  started_at,
25423
26449
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26450
+ content_expired_at,
25424
26451
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25425
26452
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25426
26453
  json_extract(attributes, '$.severity') AS severity,
@@ -26086,6 +27113,88 @@ var SqliteAuditEventsRepository = class {
26086
27113
  }
26087
27114
  };
26088
27115
 
27116
+ // ../../packages/persistence/src/repositories/body-retention.ts
27117
+ var DEFAULT_BATCH_SIZE = 500;
27118
+ var DEFAULT_MAX_ROWS = 5e4;
27119
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27120
+ var SqliteBodyRetentionRepository = class {
27121
+ constructor(db) {
27122
+ this.db = db;
27123
+ const select = (laneClause) => `
27124
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27125
+ FROM audit_events
27126
+ WHERE content IS NOT NULL
27127
+ AND started_at < :cutoff
27128
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27129
+ ${laneClause}
27130
+ ORDER BY started_at
27131
+ LIMIT :limit`;
27132
+ this.candidatesStmt = this.db.prepare(select(""));
27133
+ this.candidatesSyncSafeStmt = this.db.prepare(
27134
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27135
+ );
27136
+ this.heldBySyncStmt = this.db.prepare(`
27137
+ SELECT COUNT(*) AS n
27138
+ FROM audit_events
27139
+ WHERE content IS NOT NULL
27140
+ AND started_at < :cutoff
27141
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27142
+ AND synced_at IS NULL`);
27143
+ this.expireStmt = this.db.prepare(
27144
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27145
+ );
27146
+ }
27147
+ db;
27148
+ candidatesStmt;
27149
+ candidatesSyncSafeStmt;
27150
+ heldBySyncStmt;
27151
+ expireStmt;
27152
+ /** How many bytes a pass with these options would free, changing nothing. */
27153
+ preview(opts) {
27154
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27155
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27156
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27157
+ return {
27158
+ rowsExpired: rows.length,
27159
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27160
+ rowsHeldBySync: this.countHeldBySync(opts)
27161
+ };
27162
+ }
27163
+ /** Clear eligible bodies, in bounded batches. */
27164
+ expire(opts) {
27165
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27166
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27167
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27168
+ let rowsExpired = 0;
27169
+ let bytesFreed = 0;
27170
+ let done = true;
27171
+ while (rowsExpired < maxRows) {
27172
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27173
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27174
+ if (batch.length === 0) break;
27175
+ withTransaction(
27176
+ this.db,
27177
+ () => {
27178
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27179
+ },
27180
+ "IMMEDIATE"
27181
+ );
27182
+ rowsExpired += batch.length;
27183
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27184
+ if (batch.length < remaining) break;
27185
+ if (rowsExpired >= maxRows) {
27186
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27187
+ }
27188
+ }
27189
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27190
+ }
27191
+ countHeldBySync(opts) {
27192
+ if (opts.sweepSyncLane) return 0;
27193
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27194
+ return row.n;
27195
+ }
27196
+ };
27197
+
26089
27198
  // ../../packages/persistence/src/repositories/classified-data.ts
26090
27199
  var SqliteClassifiedDataRepository = class {
26091
27200
  constructor(db) {
@@ -26914,7 +28023,15 @@ function toFlatFindingRow(r) {
26914
28023
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26915
28024
  eventId: r.event_id,
26916
28025
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26917
- status: deriveInstanceStatus(r)
28026
+ status: deriveInstanceStatus(r),
28027
+ delivery: deriveFindingDelivery({
28028
+ kind: r.kind,
28029
+ syncedAt: r.synced_at,
28030
+ syncClaimedAt: r.sync_claimed_at,
28031
+ syncFailedAt: r.sync_failed_at,
28032
+ syncFailure: r.sync_failure,
28033
+ outboxOwed: r.outbox_owed
28034
+ })
26918
28035
  };
26919
28036
  }
26920
28037
  function encodeGroupCursor(group) {
@@ -26978,7 +28095,10 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
26978
28095
  e.tool_name AS tool_name,
26979
28096
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
26980
28097
  e.event_type AS kind, f.finding_key AS finding_key,
26981
- ${latestResolutionStatusSql("f")} AS latest_status`;
28098
+ ${latestResolutionStatusSql("f")} AS latest_status,
28099
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28100
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28101
+ e.outbox_owed AS outbox_owed`;
26982
28102
  var DAY_MS3 = 864e5;
26983
28103
  var SqliteFindingsRepository = class {
26984
28104
  constructor(db) {
@@ -27223,6 +28343,7 @@ var SqliteFindingsRepository = class {
27223
28343
  providers: query.provider,
27224
28344
  actions: query.action,
27225
28345
  statuses: query.status,
28346
+ deliveries: query.deployment,
27226
28347
  tools: query.tool,
27227
28348
  repo: query.repo,
27228
28349
  file: query.file,
@@ -27290,6 +28411,7 @@ var SqliteFindingsRepository = class {
27290
28411
  providers: query.provider,
27291
28412
  actions: query.action,
27292
28413
  statuses: query.status,
28414
+ deliveries: query.deployment,
27293
28415
  tools: query.tool,
27294
28416
  q: query.q
27295
28417
  };
@@ -27553,7 +28675,9 @@ var SqliteFindingsRepository = class {
27553
28675
  )
27554
28676
  );
27555
28677
  for (const row of grouped) {
27556
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28678
+ if (Object.hasOwn(byAction, row.action_taken)) {
28679
+ byAction[row.action_taken] = row.c;
28680
+ }
27557
28681
  }
27558
28682
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27559
28683
  const sevRows = allRows(
@@ -27570,7 +28694,9 @@ var SqliteFindingsRepository = class {
27570
28694
  )
27571
28695
  );
27572
28696
  for (const row of sevRows) {
27573
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28697
+ if (Object.hasOwn(bySeverity, row.severity)) {
28698
+ bySeverity[row.severity] = row.c;
28699
+ }
27574
28700
  }
27575
28701
  const categories = ENFORCEABLE_CATEGORIES;
27576
28702
  const enabledRows = allRows(
@@ -27619,525 +28745,6 @@ function isoDay(ms) {
27619
28745
  return new Date(ms).toISOString().slice(0, 10);
27620
28746
  }
27621
28747
 
27622
- // ../../packages/persistence/src/repositories/history-sync.ts
27623
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27624
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27625
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27626
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27627
- var SKIPPED = -1;
27628
- var ROW_COLUMNS = `id,
27629
- parent_id AS parentId,
27630
- root_session_id AS rootSessionId,
27631
- event_type AS eventType,
27632
- host_id AS hostId,
27633
- harness_id AS harnessId,
27634
- source_project_id AS sourceProjectId,
27635
- started_at AS startedAt,
27636
- ended_at AS endedAt,
27637
- severity,
27638
- priority,
27639
- content,
27640
- content_hash AS contentHash,
27641
- attributes`;
27642
- var SqliteHistorySyncRepository = class {
27643
- constructor(db) {
27644
- this.db = db;
27645
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27646
- this.sessionsStmt = db.prepare(
27647
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27648
- FROM audit_events
27649
- WHERE synced_at IS NULL
27650
- AND event_type IN (${TYPE_LIST})
27651
- AND started_at < :before
27652
- GROUP BY sessionId
27653
- ORDER BY earliest
27654
- LIMIT :limit`
27655
- );
27656
- this.rowsStmt = db.prepare(
27657
- `SELECT ${ROW_COLUMNS}
27658
- FROM audit_events
27659
- WHERE synced_at IS NULL
27660
- AND event_type IN (${TYPE_LIST})
27661
- AND started_at < :before
27662
- AND COALESCE(root_session_id, id) = :sessionId
27663
- ORDER BY (event_type = 'session') DESC, started_at
27664
- LIMIT :limit`
27665
- );
27666
- this.captureRowsStmt = db.prepare(
27667
- `SELECT ${ROW_COLUMNS}
27668
- FROM audit_events
27669
- WHERE synced_at IS NULL
27670
- AND sync_claimed_at IS NULL
27671
- AND outbox_owed = 1
27672
- AND event_type IN (${CAPTURE_TYPE_LIST})
27673
- AND started_at < :before
27674
- ORDER BY started_at
27675
- LIMIT :limit`
27676
- );
27677
- this.markOwedStmt = db.prepare(
27678
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27679
- );
27680
- this.markCaptureBacklogOwedStmt = db.prepare(
27681
- `UPDATE audit_events SET outbox_owed = 1
27682
- WHERE synced_at IS NULL
27683
- AND event_type IN (${CAPTURE_TYPE_LIST})
27684
- AND started_at < :before`
27685
- );
27686
- this.stampStmt = db.prepare(
27687
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27688
- );
27689
- this.claimRowStmt = db.prepare(
27690
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27691
- );
27692
- this.releaseRowStmt = db.prepare(
27693
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27694
- );
27695
- this.releaseStaleClaimsStmt = db.prepare(
27696
- `UPDATE audit_events SET sync_claimed_at = NULL
27697
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27698
- );
27699
- this.partitionStmt = db.prepare(
27700
- `SELECT
27701
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27702
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27703
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27704
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27705
- COUNT(*) AS total
27706
- FROM audit_events
27707
- WHERE event_type IN (${TYPE_LIST})`
27708
- );
27709
- this.countsStmt = db.prepare(
27710
- `SELECT
27711
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27712
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27713
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27714
- FROM audit_events
27715
- WHERE event_type IN (${TYPE_LIST})`
27716
- );
27717
- this.captureSkipCountStmt = db.prepare(
27718
- `SELECT COUNT(*) AS skipped
27719
- FROM audit_events
27720
- WHERE synced_at = ${String(SKIPPED)}
27721
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27722
- );
27723
- this.fingerprintStmt = db.prepare(
27724
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27725
- FROM history_sync WHERE id = 1`
27726
- );
27727
- this.setFingerprintStmt = db.prepare(
27728
- `UPDATE history_sync
27729
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27730
- WHERE id = 1`
27731
- );
27732
- this.disownCapturesStmt = db.prepare(
27733
- `UPDATE audit_events SET outbox_owed = NULL
27734
- WHERE outbox_owed IS NOT NULL
27735
- AND event_type IN (${CAPTURE_TYPE_LIST})
27736
- AND started_at < :attachedAt`
27737
- );
27738
- this.rearmStmt = db.prepare(
27739
- `UPDATE audit_events SET synced_at = NULL
27740
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27741
- );
27742
- this.claimStmt = db.prepare(
27743
- `UPDATE history_sync
27744
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27745
- WHERE id = 1
27746
- AND (owner_pid IS NULL
27747
- OR heartbeat_at IS NULL
27748
- OR heartbeat_at < :staleBefore
27749
- OR heartbeat_at > :now)`
27750
- );
27751
- this.heartbeatStmt = db.prepare(
27752
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27753
- );
27754
- this.releaseStmt = db.prepare(
27755
- `UPDATE history_sync
27756
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27757
- WHERE id = 1 AND owner_pid = :pid`
27758
- );
27759
- this.closeWindowStmt = db.prepare(
27760
- `UPDATE audit_events SET synced_at = :at
27761
- WHERE synced_at IS NULL
27762
- AND event_type IN (${TYPE_LIST})
27763
- AND started_at >= :attachedAt`
27764
- );
27765
- this.releaseBoundaryStmt = db.prepare(
27766
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27767
- );
27768
- this.freezeBoundaryStmt = db.prepare(
27769
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27770
- );
27771
- this.leaseStmt = db.prepare(
27772
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27773
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27774
- FROM history_sync WHERE id = 1`
27775
- );
27776
- this.inspectionsStmt = db.prepare(
27777
- `SELECT d.rule_id AS ruleId,
27778
- d.name AS ruleName,
27779
- d.version AS ruleVersion,
27780
- d.category AS category,
27781
- d.severity AS severity,
27782
- f.span_start AS spanStart,
27783
- f.span_end AS spanEnd,
27784
- f.masked_match AS maskedMatch,
27785
- f.action_taken AS actionTaken,
27786
- f.confidence AS confidence
27787
- FROM inspection_findings f
27788
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27789
- WHERE f.audit_event_id = :auditEventId
27790
- ORDER BY f.span_start, f.id`
27791
- );
27792
- }
27793
- db;
27794
- ensureRowStmt;
27795
- sessionsStmt;
27796
- rowsStmt;
27797
- stampStmt;
27798
- countsStmt;
27799
- fingerprintStmt;
27800
- setFingerprintStmt;
27801
- rearmStmt;
27802
- claimStmt;
27803
- heartbeatStmt;
27804
- releaseStmt;
27805
- leaseStmt;
27806
- inspectionsStmt;
27807
- closeWindowStmt;
27808
- releaseBoundaryStmt;
27809
- freezeBoundaryStmt;
27810
- captureRowsStmt;
27811
- markOwedStmt;
27812
- markCaptureBacklogOwedStmt;
27813
- captureSkipCountStmt;
27814
- disownCapturesStmt;
27815
- partitionStmt;
27816
- claimRowStmt;
27817
- releaseRowStmt;
27818
- releaseStaleClaimsStmt;
27819
- /**
27820
- * The masked detections recorded against one tool call.
27821
- *
27822
- * These travel with the event because a tool call's target is not
27823
- * re-inspectable from the event alone — unlike a capture, where the text
27824
- * itself is re-scannable. What crosses is the masked match and the rule that
27825
- * produced it, never the value.
27826
- */
27827
- inspectionsFor(auditEventId) {
27828
- return allRows(this.inspectionsStmt, { auditEventId });
27829
- }
27830
- /**
27831
- * Sessions with structural rows still to send, oldest first.
27832
- *
27833
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27834
- * read. Anything recorded after the machine attached is the live forward
27835
- * path's to deliver; this drain exists for what was recorded before it, and a
27836
- * row both paths send is at best a duplicate request and at worst — for a
27837
- * session root — an overwrite of the inventory ids the live path resolved.
27838
- */
27839
- pendingSessions(limit, before) {
27840
- return allRows(this.sessionsStmt, { limit, before }).map(
27841
- (r) => r.sessionId
27842
- );
27843
- }
27844
- /** One session's undelivered structural rows within the backlog, root first. */
27845
- pendingRows(sessionId, limit, before) {
27846
- return allRows(this.rowsStmt, { sessionId, limit, before });
27847
- }
27848
- /**
27849
- * Captures this machine still owes the deployment, oldest first.
27850
- *
27851
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27852
- * by a time window — see captureRowsStmt for why a window could not express
27853
- * this. `before` is the grace window that leaves a just-recorded capture to
27854
- * the live path.
27855
- */
27856
- pendingCaptureRows(limit, before) {
27857
- return allRows(this.captureRowsStmt, { limit, before });
27858
- }
27859
- /**
27860
- * Record that a capture is OWED to the deployment.
27861
- *
27862
- * Written by the attached forward path when a live send did not confirm
27863
- * delivery, and read by the drain as the whole of its eligibility test. It is
27864
- * a fact rather than an inference: the machine was attached, the send did not
27865
- * land, so the row is owed — which no time window can state, because the same
27866
- * window that holds the rows a past attachment left owed also holds every
27867
- * capture recorded while the machine was DETACHED, and those were never
27868
- * offered to anyone.
27869
- *
27870
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27871
- * out of the drain's read.
27872
- */
27873
- markCaptureOwed(id) {
27874
- this.markOwedStmt.run({ id });
27875
- }
27876
- /**
27877
- * Mark every capture already on disk as owed, as of `before`.
27878
- *
27879
- * The consent-time backfill, called once from `aka attach` when a human
27880
- * grants existing-history consent — never from an ongoing drain pass, and
27881
- * never inferred from a boundary that could later move. `before` is the
27882
- * caller's own "now" at the moment consent was granted, so what this marks
27883
- * is exactly the backlog the consent prompt already counted, not whatever a
27884
- * later re-attach or key rotation might widen it to.
27885
- *
27886
- * Returns how many rows matched, for the caller to log or test against. Not a
27887
- * count of NEWLY marked rows — a row still unsynced from an earlier call
27888
- * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27889
- */
27890
- markCaptureBacklogOwed(before) {
27891
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27892
- }
27893
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27894
- markSynced(ids, atMs) {
27895
- this.stampAll(ids, atMs);
27896
- }
27897
- /**
27898
- * Record that a row will never be sent.
27899
- *
27900
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27901
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27902
- * is retried; marking those would turn one outage into permanent data loss.
27903
- */
27904
- markSkipped(ids) {
27905
- this.stampAll(ids, SKIPPED);
27906
- }
27907
- eachInTransaction(ids, run) {
27908
- if (ids.length === 0) return;
27909
- withTransaction(
27910
- this.db,
27911
- () => {
27912
- for (const id of ids) run(id);
27913
- },
27914
- "IMMEDIATE"
27915
- );
27916
- }
27917
- stampAll(ids, value) {
27918
- if (ids.length === 0) return;
27919
- withTransaction(
27920
- this.db,
27921
- () => {
27922
- for (const id of ids) this.stampStmt.run({ at: value, id });
27923
- },
27924
- "IMMEDIATE"
27925
- );
27926
- }
27927
- /**
27928
- * Claim rows as in-flight.
27929
- *
27930
- * Advisory in exactly the sense the lease is: it records that a send is in
27931
- * progress so a surface can say so, and a lost claim costs a row showing as
27932
- * queued while it is actually being sent. It is not exclusion — the far side
27933
- * settles a duplicate on the row id.
27934
- */
27935
- claimRows(ids, atMs) {
27936
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
27937
- }
27938
- /** Give back a claim without settling — the send failed, the row is queued again. */
27939
- releaseRows(ids) {
27940
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
27941
- }
27942
- /**
27943
- * Clear claims older than `staleBefore`, and report how many were cleared.
27944
- *
27945
- * A process killed between claiming and settling leaves rows claimed with
27946
- * nothing left to settle them. Without this they read as "sending" for ever.
27947
- */
27948
- releaseStaleClaims(staleBefore) {
27949
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
27950
- }
27951
- /**
27952
- * Every tracked row in exactly one delivery state.
27953
- *
27954
- * Takes no boundary on purpose. The boundary answers "what should the drain
27955
- * pick up now", which is a different question from "what state is this row
27956
- * in" — and a machine that has never attached has no boundary to pass, so
27957
- * requiring one would force a caller to invent one and report the whole store
27958
- * as queued.
27959
- */
27960
- partition() {
27961
- const row = getRow(this.partitionStmt, {});
27962
- return {
27963
- queued: row?.queued ?? 0,
27964
- inProgress: row?.inProgress ?? 0,
27965
- synced: row?.synced ?? 0,
27966
- failed: row?.failed ?? 0,
27967
- total: row?.total ?? 0
27968
- };
27969
- }
27970
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
27971
- counts(before) {
27972
- const row = getRow(
27973
- this.countsStmt,
27974
- { before }
27975
- );
27976
- const captures = getRow(this.captureSkipCountStmt);
27977
- return {
27978
- pending: row?.pending ?? 0,
27979
- sent: row?.sent ?? 0,
27980
- skipped: row?.skipped ?? 0,
27981
- capturesSkipped: captures?.skipped ?? 0
27982
- };
27983
- }
27984
- /**
27985
- * The deployment the current stamps were made against, and where its backlog
27986
- * ends.
27987
- *
27988
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
27989
- * machine that has never drained is — and every writer below seeds the row
27990
- * before it needs one, so nothing depends on this creating it. Keeping the
27991
- * write off the gate path matters because the gate runs on every pass while a
27992
- * write has to take the database's write lock.
27993
- */
27994
- deployment() {
27995
- const row = getRow(
27996
- this.fingerprintStmt
27997
- );
27998
- return {
27999
- fingerprint: row?.fingerprint ?? void 0,
28000
- backlogBefore: row?.backlogBefore ?? void 0
28001
- };
28002
- }
28003
- /**
28004
- * Point the ledger at a different deployment, discarding what it recorded
28005
- * about the previous one.
28006
- *
28007
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28008
- * machine has just left are undelivered as far as the new one is concerned.
28009
- * All four in one transaction, so a crash between them cannot leave stamps
28010
- * attributed to the wrong deployment, a boundary that belongs to another, or
28011
- * a disown with no re-mark to follow it.
28012
- *
28013
- * The boundary is written HERE and only here, which is what freezes it: a
28014
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28015
- * unchanged, so this never runs and the backlog does not widen back over rows
28016
- * the live path has since delivered.
28017
- *
28018
- * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28019
- * granted existing-history consent for the deployment this call is arming —
28020
- * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28021
- * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28022
- * apart. Passed only when that grant is valid, since this method has no way
28023
- * to check consent itself and must not mark a row owed for a machine that
28024
- * never agreed to it. Applied AFTER the disown above, in the SAME
28025
- * transaction: what the disown clears is every marker below `backlogBefore`,
28026
- * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28027
- * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28028
- * on the cleared side of that bound — and the re-mark in the same
28029
- * transaction is what puts those rows back. A crash between the two cannot
28030
- * strand the ledger disowned with nothing re-marked — the transaction either
28031
- * lands whole or not at all, and a fingerprint mismatch that has not yet
28032
- * committed re-enters this method on the very next pass. Omit it (the
28033
- * structural-only tests do) to exercise the disown in isolation.
28034
- *
28035
- * The disown is bounded by `backlogBefore`, which is what keeps it from
28036
- * touching a marker the NEW deployment's OWN live path has already set: B's
28037
- * live path can mark a capture owed from the moment `aka attach` writes the
28038
- * descriptor, before the drain's first pass ever reaches this method, and
28039
- * such a row sits at or after the bound rather than below it. What keeps the
28040
- * disown from eating THIS SAME CALL's own re-mark is the order, not the
28041
- * bound — disown runs first, re-mark second, both inside the one
28042
- * transaction above.
28043
- */
28044
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28045
- this.ensureRowStmt.run();
28046
- withTransaction(
28047
- this.db,
28048
- () => {
28049
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28050
- this.rearmStmt.run();
28051
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28052
- this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28053
- }
28054
- if (backfillCapturesBefore !== void 0) {
28055
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28056
- }
28057
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28058
- },
28059
- "IMMEDIATE"
28060
- );
28061
- }
28062
- /**
28063
- * End the attached period: hand its rows to the live path, and release the
28064
- * boundary so the next attachment can freeze a new one.
28065
- *
28066
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28067
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28068
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28069
- * during the detached period, because the machine is not attached. Rows
28070
- * recorded in that window sit after the boundary and before the re-attach, so
28071
- * neither path takes them, and the pending count reports none outstanding.
28072
- *
28073
- * Stamping the attached window is not a claim that every one of those rows
28074
- * reached the deployment — the live path drops on failure and says so
28075
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28076
- * status quo: they sit outside the frozen boundary today and are equally never
28077
- * re-sent. Making it explicit is what lets the boundary move.
28078
- *
28079
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28080
- * window unstamped — that half-state would re-send the whole attached period
28081
- * on the next attach, which is the failure the boundary exists to prevent.
28082
- */
28083
- closeAttachedWindow(attachedAtMs, atMs) {
28084
- this.ensureRowStmt.run();
28085
- withTransaction(
28086
- this.db,
28087
- () => {
28088
- const row = getRow(this.fingerprintStmt);
28089
- const from = row?.backlogBefore ?? attachedAtMs;
28090
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28091
- this.releaseBoundaryStmt.run();
28092
- },
28093
- "IMMEDIATE"
28094
- );
28095
- }
28096
- /**
28097
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28098
- *
28099
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28100
- * different deployment and therefore discards what was delivered to the old
28101
- * one: here the recipient is the same, so everything already sent to it stays
28102
- * sent.
28103
- */
28104
- freezeBoundary(backlogBefore) {
28105
- this.ensureRowStmt.run();
28106
- this.freezeBoundaryStmt.run({ backlogBefore });
28107
- }
28108
- /** Take the claim, or report that someone live already holds it. */
28109
- claim(pid, host, nowMs, staleAfterMs) {
28110
- this.ensureRowStmt.run();
28111
- let taken = false;
28112
- withTransaction(
28113
- this.db,
28114
- () => {
28115
- const result = this.claimStmt.run({
28116
- pid,
28117
- host,
28118
- now: nowMs,
28119
- staleBefore: nowMs - staleAfterMs
28120
- });
28121
- taken = result.changes === 1;
28122
- },
28123
- "IMMEDIATE"
28124
- );
28125
- return taken;
28126
- }
28127
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28128
- heartbeat(pid, nowMs) {
28129
- this.heartbeatStmt.run({ now: nowMs, pid });
28130
- }
28131
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28132
- release(pid) {
28133
- this.releaseStmt.run({ pid });
28134
- }
28135
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28136
- lease() {
28137
- return getRow(this.leaseStmt);
28138
- }
28139
- };
28140
-
28141
28748
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28142
28749
  var SqliteInspectionDefinitionsRepository = class {
28143
28750
  constructor(db) {
@@ -28340,6 +28947,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28340
28947
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28341
28948
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28342
28949
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
28950
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28343
28951
  if (values.vaultConsent !== void 0) {
28344
28952
  merged.vaultConsent = values.vaultConsent ? (
28345
28953
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30847,7 +31455,7 @@ var SqliteSecurityRepository = class {
30847
31455
  ELSE 0
30848
31456
  END) AS open_at_rest
30849
31457
  FROM inspection_findings f
30850
- JOIN audit_events e ON e.id = f.audit_event_id
31458
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30851
31459
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30852
31460
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30853
31461
  ON latest.finding_key = f.finding_key
@@ -31073,7 +31681,7 @@ var SqliteSecurityRepository = class {
31073
31681
  this.db.prepare(
31074
31682
  `SELECT e.repo AS repo, count(*) AS c
31075
31683
  FROM inspection_findings f
31076
- JOIN audit_events e ON e.id = f.audit_event_id
31684
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31077
31685
  WHERE e.started_at >= :from AND e.started_at < :to
31078
31686
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31079
31687
  AND e.repo IS NOT NULL
@@ -31197,7 +31805,7 @@ var SqliteSecurityRepository = class {
31197
31805
  d.severity AS severity,
31198
31806
  COUNT(*) AS count
31199
31807
  FROM inspection_findings f
31200
- JOIN audit_events e ON e.id = f.audit_event_id
31808
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31201
31809
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31202
31810
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31203
31811
  ON latest.finding_key = f.finding_key
@@ -31232,7 +31840,7 @@ var SqliteSecurityRepository = class {
31232
31840
  `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31233
31841
  d.rule_id AS rule_id, d.category AS category
31234
31842
  FROM inspection_findings f
31235
- JOIN audit_events e ON e.id = f.audit_event_id
31843
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31236
31844
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31237
31845
  WHERE e.started_at >= :from AND e.started_at < :to
31238
31846
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -32073,6 +32681,7 @@ function openWithPragmas(file2) {
32073
32681
  db.exec("PRAGMA journal_mode = WAL");
32074
32682
  db.exec("PRAGMA busy_timeout = 2000");
32075
32683
  db.exec("PRAGMA foreign_keys = ON");
32684
+ registerSqlFunctions(db);
32076
32685
  } catch (err) {
32077
32686
  closeQuietly(db);
32078
32687
  throw err;
@@ -32102,7 +32711,7 @@ function backupLegacyStore(db, file2) {
32102
32711
  discardStore(file2, backup);
32103
32712
  return backup;
32104
32713
  }
32105
- function openAndInitialize(file2, base) {
32714
+ function openAndInitialize(file2, base, skipTags) {
32106
32715
  let db = openWithPragmas(file2);
32107
32716
  try {
32108
32717
  if (isForeignSqliteLineage(db)) {
@@ -32112,7 +32721,7 @@ function openAndInitialize(file2, base) {
32112
32721
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32113
32722
  );
32114
32723
  }
32115
- applyMigrations(db, file2);
32724
+ applyMigrations(db, file2, { skipTags });
32116
32725
  tightenPerms(file2);
32117
32726
  const policies = new SqlitePoliciesRepository(db);
32118
32727
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32127,6 +32736,7 @@ function openAndInitialize(file2, base) {
32127
32736
  exceptions: new SqliteExceptionsRepository(db),
32128
32737
  resolutions: new SqliteResolutionsRepository(db),
32129
32738
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32739
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32130
32740
  security: new SqliteSecurityRepository(db),
32131
32741
  detections: new SqliteDetectionsRepository(db),
32132
32742
  shares: new SqliteSharesRepository(db),
@@ -32149,7 +32759,8 @@ function openAndInitialize(file2, base) {
32149
32759
  throw err;
32150
32760
  }
32151
32761
  }
32152
- function openLocalDatabase(dir) {
32762
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32763
+ function openLocalDatabase(dir, options = {}) {
32153
32764
  ensureDataDirSync(dir);
32154
32765
  const file2 = join7(dir, DB_FILENAME);
32155
32766
  reapStalePartials(file2);
@@ -32161,6 +32772,7 @@ function openLocalDatabase(dir) {
32161
32772
  installedPacks,
32162
32773
  scanLedger,
32163
32774
  historySync,
32775
+ bodyRetention,
32164
32776
  secretVault,
32165
32777
  exceptions,
32166
32778
  resolutions,
@@ -32184,7 +32796,8 @@ function openLocalDatabase(dir) {
32184
32796
  // `dir` is always `<base>/data` — every caller resolves it through
32185
32797
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32186
32798
  // settings/ and data/, and the pack-policy floor needs both halves.
32187
- dirname2(dir)
32799
+ dirname2(dir),
32800
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32188
32801
  );
32189
32802
  function captureRowId(event) {
32190
32803
  return captureId(
@@ -32377,6 +32990,7 @@ function openLocalDatabase(dir) {
32377
32990
  installedPacks,
32378
32991
  scanLedger,
32379
32992
  historySync,
32993
+ bodyRetention,
32380
32994
  secretVault,
32381
32995
  exceptions,
32382
32996
  resolutions,
@@ -32417,6 +33031,7 @@ function openLocalDatabase(dir) {
32417
33031
 
32418
33032
  // ../../packages/persistence/src/egress-wire.ts
32419
33033
  import { createHash as createHash3 } from "crypto";
33034
+ var SLASH = "/".charCodeAt(0);
32420
33035
 
32421
33036
  // ../../packages/persistence/src/finding-key.ts
32422
33037
  import { createHash as createHash4 } from "crypto";
@@ -32427,18 +33042,113 @@ import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
32427
33042
  import { join as join8 } from "path";
32428
33043
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
32429
33044
 
33045
+ // ../../packages/persistence/src/forward-health.ts
33046
+ import { readFileSync as readFileSync7 } from "fs";
33047
+ import { join as join9 } from "path";
33048
+ var FAILURES = /* @__PURE__ */ new Set([
33049
+ "unauthorized",
33050
+ "forbidden",
33051
+ "unreachable"
33052
+ ]);
33053
+ var BREAKER_COOLDOWN_MS = 3e4;
33054
+ function parseForwardHealth(raw, nowMs) {
33055
+ try {
33056
+ const parsed2 = JSON.parse(raw);
33057
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33058
+ const record2 = parsed2;
33059
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33060
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33061
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33062
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33063
+ } catch {
33064
+ return null;
33065
+ }
33066
+ }
33067
+ function readForwardHealth(dir, nowMs = Date.now()) {
33068
+ try {
33069
+ return parseForwardHealth(
33070
+ readFileSync7(join9(dir, ATTACHED_FORWARD_STATE_FILENAME), "utf8"),
33071
+ nowMs
33072
+ );
33073
+ } catch {
33074
+ return null;
33075
+ }
33076
+ }
33077
+ function isForwardPaused(health, nowMs) {
33078
+ const openedAtMs = health?.openedAtMs ?? null;
33079
+ if (openedAtMs === null) return false;
33080
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33081
+ }
33082
+
32430
33083
  // ../../packages/persistence/src/history-backfill.ts
32431
33084
  import { existsSync as existsSync4 } from "fs";
32432
- import { join as join9 } from "path";
33085
+ import { join as join10 } from "path";
32433
33086
 
32434
33087
  // ../../packages/persistence/src/history-preview.ts
32435
33088
  import { existsSync as existsSync5 } from "fs";
32436
- import { join as join10 } from "path";
33089
+ import { join as join11 } from "path";
32437
33090
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32438
33091
 
33092
+ // ../../packages/persistence/src/history-sync-state.ts
33093
+ import { readFileSync as readFileSync8 } from "fs";
33094
+ import { join as join12 } from "path";
33095
+ var HISTORY_SYNC_STATE_FILENAME = ATTACHED_HISTORY_SYNC_STATE_FILENAME;
33096
+ var PHASES = /* @__PURE__ */ new Set(["filling", "complete"]);
33097
+ var OUTCOMES = /* @__PURE__ */ new Set([
33098
+ "ok",
33099
+ "unreachable",
33100
+ "refused",
33101
+ "interrupted"
33102
+ ]);
33103
+ var SPEC_VERSION = 1;
33104
+ function historySyncStatePath(dataDir2) {
33105
+ return join12(dataDir2, HISTORY_SYNC_STATE_FILENAME);
33106
+ }
33107
+ function writeHistorySyncState(dataDir2, state) {
33108
+ try {
33109
+ ensureDataDirSync(dataDir2);
33110
+ const persisted = { specVersion: SPEC_VERSION, ...state };
33111
+ writeOwnerOnlyFileSync(historySyncStatePath(dataDir2), `${JSON.stringify(persisted)}
33112
+ `);
33113
+ } catch {
33114
+ }
33115
+ }
33116
+ function readHistorySyncState(dataDir2) {
33117
+ try {
33118
+ const parsed2 = JSON.parse(readFileSync8(historySyncStatePath(dataDir2), "utf8"));
33119
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33120
+ const r = parsed2;
33121
+ if (r.specVersion !== SPEC_VERSION) return null;
33122
+ if (typeof r.phase !== "string" || !PHASES.has(r.phase)) return null;
33123
+ if (typeof r.lastOutcome !== "string" || !OUTCOMES.has(r.lastOutcome)) return null;
33124
+ if (!isCount(r.lastPassAtMs)) return null;
33125
+ if (!isCount(r.sentTotal) || !isCount(r.pendingTotal) || !isCount(r.skippedTotal)) return null;
33126
+ if (!isNullableCount(r.startedAtMs) || !isNullableCount(r.completedAtMs)) return null;
33127
+ return {
33128
+ specVersion: SPEC_VERSION,
33129
+ phase: r.phase,
33130
+ lastOutcome: r.lastOutcome,
33131
+ lastPassAtMs: r.lastPassAtMs,
33132
+ sentTotal: r.sentTotal,
33133
+ pendingTotal: r.pendingTotal,
33134
+ skippedTotal: r.skippedTotal,
33135
+ startedAtMs: r.startedAtMs,
33136
+ completedAtMs: r.completedAtMs
33137
+ };
33138
+ } catch {
33139
+ return null;
33140
+ }
33141
+ }
33142
+ function isCount(v) {
33143
+ return typeof v === "number" && Number.isFinite(v) && v >= 0;
33144
+ }
33145
+ function isNullableCount(v) {
33146
+ return v === null || isCount(v);
33147
+ }
33148
+
32439
33149
  // ../../packages/persistence/src/store-symlinks.ts
32440
33150
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32441
- import { dirname as dirname3, join as join11, resolve } from "path";
33151
+ import { dirname as dirname3, join as join13, resolve } from "path";
32442
33152
 
32443
33153
  // ../../packages/persistence/src/vault/crypto.ts
32444
33154
  import {
@@ -32452,15 +33162,15 @@ import {
32452
33162
  // ../../packages/persistence/src/vault/key-provider.ts
32453
33163
  import { execFileSync } from "child_process";
32454
33164
  import { randomBytes as randomBytes2 } from "crypto";
32455
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32456
- import { join as join12 } from "path";
33165
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33166
+ import { join as join14 } from "path";
32457
33167
 
32458
33168
  // ../../packages/persistence/src/vault/vault.ts
32459
33169
  import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
32460
33170
 
32461
33171
  // ../../packages/persistence/src/warn-era-cap.ts
32462
33172
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
32463
- import { join as join13 } from "path";
33173
+ import { join as join15 } from "path";
32464
33174
 
32465
33175
  // ../../packages/remote/src/http.ts
32466
33176
  import { request as httpRequest } from "http";
@@ -32645,10 +33355,10 @@ function parsed(schema, body, route) {
32645
33355
  }
32646
33356
  function withoutTrailingSlashes(endpoint) {
32647
33357
  let end = endpoint.length;
32648
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
33358
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
32649
33359
  return endpoint.slice(0, end);
32650
33360
  }
32651
- var SLASH = "/".charCodeAt(0);
33361
+ var SLASH2 = "/".charCodeAt(0);
32652
33362
  function createRemoteClient(options) {
32653
33363
  const base = withoutTrailingSlashes(options.endpoint);
32654
33364
  const url2 = (route) => `${base}${route}`;
@@ -32765,18 +33475,17 @@ function createRemoteClient(options) {
32765
33475
  }
32766
33476
 
32767
33477
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
32768
- import { readFileSync as readFileSync8 } from "fs";
32769
- import { join as join14 } from "path";
33478
+ import { readFileSync as readFileSync10 } from "fs";
33479
+ import { join as join16 } from "path";
32770
33480
 
32771
33481
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
32772
33482
  import { randomUUID as randomUUID15 } from "crypto";
32773
- import { readFileSync as readFileSync15 } from "fs";
32774
33483
  import { readFile, rename, writeFile } from "fs/promises";
32775
- import { join as join24 } from "path";
33484
+ import { join as join26 } from "path";
32776
33485
 
32777
33486
  // ../../packages/plugin-sdk/src/config.ts
32778
33487
  import { existsSync as existsSync8 } from "fs";
32779
- import { join as join15 } from "path";
33488
+ import { join as join17 } from "path";
32780
33489
 
32781
33490
  // ../../packages/plugin-sdk/src/provider-env.ts
32782
33491
  var booleanish = external_exports.string().optional().transform((v) => {
@@ -32797,9 +33506,9 @@ var providerEnvShape = {
32797
33506
  var ProviderEnvSchema = external_exports.object(providerEnvShape);
32798
33507
 
32799
33508
  // ../../packages/plugin-sdk/src/config-inventory.ts
32800
- import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
33509
+ import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
32801
33510
  import { homedir as homedir2 } from "os";
32802
- import { basename as basename3, join as join17 } from "path";
33511
+ import { basename as basename3, join as join19 } from "path";
32803
33512
 
32804
33513
  // ../../packages/detections/src/egress/registry.ts
32805
33514
  var EXTRACTOR_VERSION = "1";
@@ -33557,8 +34266,8 @@ var CPU_CORROBORATION_SHARE = 0.2;
33557
34266
  var CORROBORATION_FLOOR_MS = BUDGET_MS * CPU_CORROBORATION_SHARE;
33558
34267
 
33559
34268
  // ../../packages/plugin-sdk/src/repo.ts
33560
- import { existsSync as existsSync9, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
33561
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join16, sep as sep2 } from "path";
34269
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
34270
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
33562
34271
 
33563
34272
  // ../../packages/plugin-sdk/src/events.ts
33564
34273
  import { createHash as createHash5, randomUUID as randomUUID13 } from "crypto";
@@ -33569,8 +34278,8 @@ import { fileURLToPath } from "url";
33569
34278
  import { Worker } from "worker_threads";
33570
34279
 
33571
34280
  // ../../packages/plugin-sdk/src/host-floor.ts
33572
- import { readFileSync as readFileSync12 } from "fs";
33573
- import { join as join19 } from "path";
34281
+ import { readFileSync as readFileSync14 } from "fs";
34282
+ import { join as join21 } from "path";
33574
34283
 
33575
34284
  // ../../packages/plugin-sdk/src/model-governance.ts
33576
34285
  import {
@@ -33578,11 +34287,11 @@ import {
33578
34287
  fstatSync,
33579
34288
  mkdirSync as mkdirSync2,
33580
34289
  openSync as openSync2,
33581
- readFileSync as readFileSync11,
34290
+ readFileSync as readFileSync13,
33582
34291
  readSync,
33583
34292
  writeFileSync as writeFileSync5
33584
34293
  } from "fs";
33585
- import { join as join18 } from "path";
34294
+ import { join as join20 } from "path";
33586
34295
  var TAIL_BYTES = 256 * 1024;
33587
34296
 
33588
34297
  // ../../packages/plugin-sdk/src/host-floor.ts
@@ -33605,15 +34314,15 @@ var HOST_FLOORS = {
33605
34314
 
33606
34315
  // ../../packages/plugin-sdk/src/ignore-layers.ts
33607
34316
  var import_ignore = __toESM(require_ignore(), 1);
33608
- import { readFileSync as readFileSync13 } from "fs";
33609
- import { join as join20 } from "path";
34317
+ import { readFileSync as readFileSync15 } from "fs";
34318
+ import { join as join22 } from "path";
33610
34319
 
33611
34320
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
33612
34321
  import { arch, hostname as hostname4, platform, release } from "os";
33613
34322
 
33614
34323
  // ../../packages/plugin-sdk/src/nudge.ts
33615
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync14, writeFileSync as writeFileSync6 } from "fs";
33616
- import { join as join21 } from "path";
34324
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
34325
+ import { join as join23 } from "path";
33617
34326
 
33618
34327
  // ../../packages/plugin-sdk/src/paths.ts
33619
34328
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -33621,7 +34330,7 @@ import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
33621
34330
 
33622
34331
  // ../../packages/plugin-sdk/src/project-files.ts
33623
34332
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
33624
- import { basename as basename5, join as join22 } from "path";
34333
+ import { basename as basename5, join as join24 } from "path";
33625
34334
 
33626
34335
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
33627
34336
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -33657,94 +34366,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
33657
34366
 
33658
34367
  // ../../packages/plugin-sdk/src/throttle.ts
33659
34368
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
33660
- import { join as join23 } from "path";
33661
-
33662
- // ../../packages/plugin-runtime/src/attached/forward-policy.ts
33663
- var BREAKER_COOLDOWN_MS = 3e4;
33664
- var FAILURES = /* @__PURE__ */ new Set([
33665
- "unauthorized",
33666
- "forbidden",
33667
- "unreachable"
33668
- ]);
33669
- var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
33670
- var STATE_FILENAME = FORWARD_STATE_FILENAME;
33671
- function parseBreakerState(raw, nowMs) {
33672
- try {
33673
- const parsed2 = JSON.parse(raw);
33674
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
33675
- const record2 = parsed2;
33676
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33677
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33678
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33679
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
33680
- } catch {
33681
- return null;
33682
- }
33683
- }
33684
- function readForwardHealth(dir, nowMs = Date.now()) {
33685
- try {
33686
- return parseBreakerState(readFileSync15(join24(dir, STATE_FILENAME), "utf8"), nowMs);
33687
- } catch {
33688
- return null;
33689
- }
33690
- }
33691
-
33692
- // ../../packages/plugin-runtime/src/attached/history-state.ts
33693
- import { readFileSync as readFileSync16 } from "fs";
33694
34369
  import { join as join25 } from "path";
33695
- var HISTORY_SYNC_STATE_FILENAME = ATTACHED_HISTORY_SYNC_STATE_FILENAME;
33696
- var PHASES = /* @__PURE__ */ new Set(["filling", "complete"]);
33697
- var OUTCOMES = /* @__PURE__ */ new Set([
33698
- "ok",
33699
- "unreachable",
33700
- "refused",
33701
- "interrupted"
33702
- ]);
33703
- var SPEC_VERSION = 1;
33704
- function historySyncStatePath(dataDir2) {
33705
- return join25(dataDir2, HISTORY_SYNC_STATE_FILENAME);
33706
- }
33707
- function writeHistorySyncState(dataDir2, state) {
33708
- try {
33709
- ensureDataDirSync(dataDir2);
33710
- const persisted = { specVersion: SPEC_VERSION, ...state };
33711
- writeOwnerOnlyFileSync(historySyncStatePath(dataDir2), `${JSON.stringify(persisted)}
33712
- `);
33713
- } catch {
33714
- }
33715
- }
33716
- function readHistorySyncState(dataDir2) {
33717
- try {
33718
- const parsed2 = JSON.parse(readFileSync16(historySyncStatePath(dataDir2), "utf8"));
33719
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
33720
- const r = parsed2;
33721
- if (r.specVersion !== SPEC_VERSION) return null;
33722
- if (typeof r.phase !== "string" || !PHASES.has(r.phase)) return null;
33723
- if (typeof r.lastOutcome !== "string" || !OUTCOMES.has(r.lastOutcome)) return null;
33724
- if (!isCount(r.lastPassAtMs)) return null;
33725
- if (!isCount(r.sentTotal) || !isCount(r.pendingTotal) || !isCount(r.skippedTotal)) return null;
33726
- if (!isNullableCount(r.startedAtMs) || !isNullableCount(r.completedAtMs)) return null;
33727
- return {
33728
- specVersion: SPEC_VERSION,
33729
- phase: r.phase,
33730
- lastOutcome: r.lastOutcome,
33731
- lastPassAtMs: r.lastPassAtMs,
33732
- sentTotal: r.sentTotal,
33733
- pendingTotal: r.pendingTotal,
33734
- skippedTotal: r.skippedTotal,
33735
- startedAtMs: r.startedAtMs,
33736
- completedAtMs: r.completedAtMs
33737
- };
33738
- } catch {
33739
- return null;
33740
- }
33741
- }
33742
- function isCount(v) {
33743
- return typeof v === "number" && Number.isFinite(v) && v >= 0;
33744
- }
33745
- function isNullableCount(v) {
33746
- return v === null || isCount(v);
33747
- }
33748
34370
 
33749
34371
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
33750
34372
  import { createHash as createHash6 } from "crypto";
@@ -33791,7 +34413,20 @@ function rebuildCapture(row) {
33791
34413
  // it, IngestEvent.safeParse then refuses the assembled event, and the whole
33792
34414
  // capture becomes a permanent skip. That is the per-row door the rest of this
33793
34415
  // function exists to avoid, and this field was the last one still using it.
33794
- ...withList("exceptionIds", keepAll(attributes.exception_ids, EXCEPTION_ID))
34416
+ ...withList("exceptionIds", keepAll(attributes.exception_ids, EXCEPTION_ID)),
34417
+ // Carried, for the same reason exceptionIds is: it says WHY an enforced
34418
+ // detection let a value through, and a capture that means one thing live
34419
+ // and another when drained is worse than one that carries neither.
34420
+ //
34421
+ // Parsed rather than type-checked. The bag is free-form JSON, so a hand
34422
+ // edit or an older build can leave any string here; an unparseable one is
34423
+ // dropped rather than assembled into an event the deployment would refuse
34424
+ // with a 400 — which, on a drain that reads the head of the unstamped set
34425
+ // with no cursor, is the per-row door that retires the whole lane.
34426
+ ...withField(
34427
+ "redactDegradedTo",
34428
+ keep(stringOrUndefined(attributes.redact_degraded_to), REDACT_DEGRADED_TO)
34429
+ )
33795
34430
  // inspectionMs is DELIBERATELY not carried. It measures latency a live host
33796
34431
  // session actually waited on, and a row being drained hours later is not
33797
34432
  // that; the field's own contract says a replay leaves it absent rather than
@@ -33820,6 +34455,7 @@ function keepAll(value, schema) {
33820
34455
  var CORRELATION_ID = EventMetadata.shape.correlationId;
33821
34456
  var TRACE_ID = EventMetadata.shape.traceId;
33822
34457
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
34458
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
33823
34459
  function isoOrUndefined(epochMs) {
33824
34460
  if (!Number.isFinite(epochMs)) return void 0;
33825
34461
  const iso = new Date(epochMs);
@@ -33899,7 +34535,6 @@ function attributesOf(raw) {
33899
34535
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
33900
34536
  var HISTORY_REQUEST_TIMEOUT_MS = 15e3;
33901
34537
  var HISTORY_PASS_BUDGET_MS = 12e4;
33902
- var HISTORY_LEASE_STALE_MS = 6e4;
33903
34538
  var HEARTBEAT_EVERY_MS = 1e4;
33904
34539
  var PACE_INTERVAL_MS = 200;
33905
34540
  var MAX_ATTEMPTS = 4;
@@ -33908,6 +34543,23 @@ var SESSION_PAGE = 25;
33908
34543
  var ROW_PAGE = 200;
33909
34544
  var CAPTURE_GRACE_MS = 3e4;
33910
34545
  var CAPTURE_BATCH_SIZE = INGEST_BATCH_MAX;
34546
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
34547
+ function underByteCeiling(ready) {
34548
+ const fitting = [];
34549
+ const oversized = [];
34550
+ let bytes = 0;
34551
+ for (const item of ready) {
34552
+ const size = Buffer.byteLength(item.event.content, "utf8");
34553
+ if (size > CAPTURE_BATCH_BYTES) {
34554
+ oversized.push(item.id);
34555
+ continue;
34556
+ }
34557
+ if (bytes + size > CAPTURE_BATCH_BYTES) break;
34558
+ bytes += size;
34559
+ fitting.push(item);
34560
+ }
34561
+ return { fitting, oversized };
34562
+ }
33911
34563
  var STRUCTURAL_BUDGET_SHARE = 0.7;
33912
34564
  var BATCH_SIZE = AUDIT_EVENT_BATCH_MAX;
33913
34565
  function endpointFingerprint(endpoint) {
@@ -33937,8 +34589,7 @@ async function runHistorySync(deps) {
33937
34589
  const state = readControlPlaneCredentialFile(deps.settingsDir, connection);
33938
34590
  if (!state.usable) return didNotRun("credential-unusable");
33939
34591
  const nowMs = now();
33940
- const openedAtMs = readForwardHealth(deps.dataDir, nowMs)?.openedAtMs ?? null;
33941
- if (openedAtMs !== null && nowMs - openedAtMs < BREAKER_COOLDOWN_MS) {
34592
+ if (isForwardPaused(readForwardHealth(deps.dataDir, nowMs), nowMs)) {
33942
34593
  return didNotRun("breaker-open");
33943
34594
  }
33944
34595
  db = (deps.openStore ?? openLocalDatabase)(deps.dataDir);
@@ -33958,7 +34609,7 @@ async function runHistorySync(deps) {
33958
34609
  backlogBefore = recorded.backlogBefore;
33959
34610
  }
33960
34611
  const pid = process.pid;
33961
- if (!ledger.claim(pid, hostname5(), now(), HISTORY_LEASE_STALE_MS)) {
34612
+ if (!ledger.claim(pid, hostname5(), now(), HISTORY_SYNC_LEASE_STALE_MS)) {
33962
34613
  return didNotRun("already-running");
33963
34614
  }
33964
34615
  const client = deps.sendBatch !== void 0 && deps.sendCaptures !== void 0 && deps.sendOne !== void 0 ? void 0 : createRemoteClient({
@@ -34008,6 +34659,7 @@ async function runHistorySync(deps) {
34008
34659
  async function drain(d) {
34009
34660
  const startedAt = d.now();
34010
34661
  const deadline = startedAt + d.budgetMs;
34662
+ d.ledger.releaseStaleClaims(startedAt - HISTORY_SYNC_LEASE_STALE_MS);
34011
34663
  const structuralDeadline = Math.min(deadline, startedAt + d.budgetMs * STRUCTURAL_BUDGET_SHARE);
34012
34664
  let sent = 0;
34013
34665
  let skipped = 0;
@@ -34030,7 +34682,7 @@ async function drain(d) {
34030
34682
  for (const row of rows) {
34031
34683
  const event = rebuildAuditEvent(row, d.ledger.inspectionsFor(row.id));
34032
34684
  if (event === void 0) {
34033
- d.ledger.markSkipped([row.id]);
34685
+ d.ledger.markSkipped([row.id], d.now());
34034
34686
  skipped += 1;
34035
34687
  continue;
34036
34688
  }
@@ -34042,7 +34694,14 @@ async function drain(d) {
34042
34694
  break outer;
34043
34695
  }
34044
34696
  const chunk = ready.slice(i, i + BATCH_SIZE);
34045
- const result = await sendChunk(d, chunk, beat);
34697
+ const chunkIds = chunk.map((c) => c.id);
34698
+ d.ledger.claimRows(chunkIds, d.now());
34699
+ let result;
34700
+ try {
34701
+ result = await sendChunk(d, chunk, beat);
34702
+ } finally {
34703
+ releaseClaim(d, chunkIds);
34704
+ }
34046
34705
  sent += result.sent;
34047
34706
  skipped += result.skipped;
34048
34707
  if (result.stopped !== void 0) {
@@ -34100,7 +34759,7 @@ async function drainCaptures(d, deadline, beat) {
34100
34759
  ready.push({ id: row.id, event });
34101
34760
  }
34102
34761
  if (unbuildable.length > 0) {
34103
- d.ledger.markSkipped(unbuildable);
34762
+ d.ledger.markSkipped(unbuildable, d.now());
34104
34763
  skipped += unbuildable.length;
34105
34764
  }
34106
34765
  if (ready.length === 0) {
@@ -34108,7 +34767,24 @@ async function drainCaptures(d, deadline, beat) {
34108
34767
  await d.sleep(PACE_INTERVAL_MS);
34109
34768
  continue;
34110
34769
  }
34111
- const result = await sendCaptureChunk(d, ready, beat);
34770
+ const { fitting, oversized } = underByteCeiling(ready);
34771
+ if (oversized.length > 0) {
34772
+ d.ledger.markSkipped(oversized, d.now());
34773
+ skipped += oversized.length;
34774
+ }
34775
+ if (fitting.length === 0) {
34776
+ beat();
34777
+ await d.sleep(PACE_INTERVAL_MS);
34778
+ continue;
34779
+ }
34780
+ const readyIds = fitting.map((r) => r.id);
34781
+ d.ledger.claimRows(readyIds, d.now());
34782
+ let result;
34783
+ try {
34784
+ result = await sendCaptureChunk(d, fitting, beat);
34785
+ } finally {
34786
+ releaseClaim(d, readyIds);
34787
+ }
34112
34788
  sent += result.sent;
34113
34789
  skipped += result.skipped;
34114
34790
  if (result.stopped !== void 0) return { sent, skipped, stopped: result.stopped };
@@ -34136,7 +34812,7 @@ async function sendCaptureChunk(d, chunk, beat) {
34136
34812
  {
34137
34813
  const only = chunk.length === 1 ? chunk[0] : void 0;
34138
34814
  if (only !== void 0) {
34139
- d.ledger.markSkipped([only.id]);
34815
+ recordGaveUp(d, [only.id], outcome.verdict);
34140
34816
  return { sent: 0, skipped: 1 };
34141
34817
  }
34142
34818
  return await isolate(d, chunk, beat);
@@ -34163,7 +34839,8 @@ async function sendCapturesWithRetries(d, chunk, beat) {
34163
34839
  } catch (err) {
34164
34840
  const kind = classify(err);
34165
34841
  if (kind === "refused") return { verdict: "refused" };
34166
- if (kind === "skip") return { verdict: "skip" };
34842
+ if (kind === "payload-invalid") return { verdict: "payload-invalid" };
34843
+ if (kind === "deployment-refused") return { verdict: "deployment-refused" };
34167
34844
  if (attempt === MAX_ATTEMPTS - 1) return { verdict: "unreachable" };
34168
34845
  const ceiling = Math.min(MAX_BACKOFF_MS, 1e3 * 2 ** attempt);
34169
34846
  beat();
@@ -34205,7 +34882,7 @@ async function sendSingleRow(d, one, beat) {
34205
34882
  if (outcome.verdict === "refused" || outcome.verdict === "unreachable") {
34206
34883
  return { sent: 0, skipped: 0, stopped: outcome.verdict };
34207
34884
  }
34208
- d.ledger.markSkipped([one.id]);
34885
+ recordGaveUp(d, [one.id], outcome.verdict);
34209
34886
  return { sent: 0, skipped: 1 };
34210
34887
  }
34211
34888
  async function isolateStructural(d, chunk, beat) {
@@ -34229,7 +34906,8 @@ async function sendWithRetries(d, attempt, beat) {
34229
34906
  } catch (err) {
34230
34907
  const kind = classify(err);
34231
34908
  if (kind === "refused") return { verdict: "refused" };
34232
- if (kind === "skip") return { verdict: "skip" };
34909
+ if (kind === "payload-invalid") return { verdict: "payload-invalid" };
34910
+ if (kind === "deployment-refused") return { verdict: "deployment-refused" };
34233
34911
  if (i === MAX_ATTEMPTS - 1) return { verdict: "unreachable" };
34234
34912
  const ceiling = Math.min(MAX_BACKOFF_MS, 1e3 * 2 ** i);
34235
34913
  beat();
@@ -34238,6 +34916,22 @@ async function sendWithRetries(d, attempt, beat) {
34238
34916
  }
34239
34917
  return { verdict: "unreachable" };
34240
34918
  }
34919
+ function releaseClaim(d, ids) {
34920
+ try {
34921
+ d.ledger.releaseRows(ids);
34922
+ } catch {
34923
+ }
34924
+ }
34925
+ function recordGaveUp(d, ids, verdict) {
34926
+ switch (verdict) {
34927
+ case "deployment-refused":
34928
+ d.ledger.markRefused(ids, d.now());
34929
+ return;
34930
+ case "payload-invalid":
34931
+ d.ledger.markSkipped(ids, d.now());
34932
+ return;
34933
+ }
34934
+ }
34241
34935
  function statusOf2(err) {
34242
34936
  if (typeof err !== "object" || err === null || !("status" in err)) return null;
34243
34937
  const { status } = err;
@@ -34245,7 +34939,7 @@ function statusOf2(err) {
34245
34939
  return status >= 100 && status <= 599 ? status : null;
34246
34940
  }
34247
34941
  function classify(err) {
34248
- if (err.name === "RemoteRequestInvalid") return "skip";
34942
+ if (err.name === "RemoteRequestInvalid") return "payload-invalid";
34249
34943
  switch (statusOf2(err)) {
34250
34944
  // Terminal in a way a timeout is not: the credential may have died with an
34251
34945
  // offboarded member, and every later row would fail the same way.
@@ -34253,11 +34947,11 @@ function classify(err) {
34253
34947
  case 403:
34254
34948
  return "refused";
34255
34949
  // The deployment understood the request and rejected it. Re-sending an
34256
- // identical body cannot change that.
34950
+ // identical body TO THIS DEPLOYMENT cannot change that.
34257
34951
  case 400:
34258
34952
  case 413:
34259
34953
  case 422:
34260
- return "skip";
34954
+ return "deployment-refused";
34261
34955
  default:
34262
34956
  return "retry";
34263
34957
  }
@@ -34293,7 +34987,18 @@ async function runHistorySyncPass(base = defaultDataDir(), seams = {}) {
34293
34987
  // field whose capture half is one pass wide, so the surface beside
34294
34988
  // `sentTotal` and `pendingTotal` would announce a permanent loss once and
34295
34989
  // drop it on the next pass, while the rows stayed gone.
34296
- skippedTotal: result.counts.skipped + result.counts.capturesSkipped,
34990
+ //
34991
+ // EVERY reason the store can name, not just the original one. Splitting
34992
+ // `skipped` into its reasons gave the store a truer answer and silently
34993
+ // shrank this number twice over: a structural row a deployment rejected,
34994
+ // and a window a detach closed over undelivered, both used to land in
34995
+ // `skipped` and reach a surface, and after the splits each reached
34996
+ // nothing. A bucket this sum does not name is a row that disappears from
34997
+ // the only total anyone sees.
34998
+ //
34999
+ // The capture term needs no counterpart: that lane keeps both of its
35000
+ // reasons in one total, because neither is ever freed there.
35001
+ skippedTotal: result.counts.skipped + result.counts.refused + result.counts.detached + result.counts.capturesSkipped,
34297
35002
  // The first pass that ran is when this machine started sending, and it
34298
35003
  // keeps that answer across every later pass.
34299
35004
  startedAtMs: previous?.startedAtMs ?? result.atMs,
@@ -34330,7 +35035,7 @@ import { readFileSync as readFileSync17 } from "fs";
34330
35035
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
34331
35036
  import { randomUUID as randomUUID16 } from "crypto";
34332
35037
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
34333
- import { join as join26 } from "path";
35038
+ import { join as join27 } from "path";
34334
35039
 
34335
35040
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
34336
35041
  import { rename as rename2 } from "fs/promises";
@@ -34345,11 +35050,11 @@ import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
34345
35050
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
34346
35051
  import { randomUUID as randomUUID17 } from "crypto";
34347
35052
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
34348
- import { join as join27 } from "path";
35053
+ import { join as join28 } from "path";
34349
35054
 
34350
35055
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
34351
35056
  import { readFileSync as readFileSync18 } from "fs";
34352
- import { join as join28 } from "path";
35057
+ import { join as join29 } from "path";
34353
35058
 
34354
35059
  // ../../packages/plugin-runtime/src/attached/status.ts
34355
35060
  var REFUSAL_LINES = {
@@ -34370,6 +35075,14 @@ import { spawn as spawn2 } from "child_process";
34370
35075
  import { fileURLToPath as fileURLToPath3 } from "url";
34371
35076
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
34372
35077
 
35078
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
35079
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
35080
+
35081
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
35082
+ import { spawn as spawn3 } from "child_process";
35083
+ import { fileURLToPath as fileURLToPath4 } from "url";
35084
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
35085
+
34373
35086
  // ../../packages/plugin-runtime/src/attached/factory.ts
34374
35087
  import { hostname as hostname6 } from "os";
34375
35088