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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ var require_ignore = __commonJS({
50
50
  var REGEX_SPLITALL_CRLF = /\r?\n/g;
51
51
  var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
52
52
  var REGEX_TEST_TRAILING_SLASH = /\/$/;
53
- var SLASH2 = "/";
53
+ var SLASH3 = "/";
54
54
  var TMP_KEY_IGNORE = "node-ignore";
55
55
  if (typeof Symbol !== "undefined") {
56
56
  TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
@@ -422,11 +422,11 @@ var require_ignore = __commonJS({
422
422
  if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
423
423
  return this.test(path);
424
424
  }
425
- const slices = path.split(SLASH2).filter(Boolean);
425
+ const slices = path.split(SLASH3).filter(Boolean);
426
426
  slices.pop();
427
427
  if (slices.length) {
428
428
  const parent = this._t(
429
- slices.join(SLASH2) + SLASH2,
429
+ slices.join(SLASH3) + SLASH3,
430
430
  this._testCache,
431
431
  true,
432
432
  slices
@@ -442,14 +442,14 @@ var require_ignore = __commonJS({
442
442
  return cache[path];
443
443
  }
444
444
  if (!slices) {
445
- slices = path.split(SLASH2).filter(Boolean);
445
+ slices = path.split(SLASH3).filter(Boolean);
446
446
  }
447
447
  slices.pop();
448
448
  if (!slices.length) {
449
449
  return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE);
450
450
  }
451
451
  const parent = this._t(
452
- slices.join(SLASH2) + SLASH2,
452
+ slices.join(SLASH3) + SLASH3,
453
453
  cache,
454
454
  checkUnignored,
455
455
  slices
@@ -502,6 +502,14 @@ var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
502
502
  import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
503
503
  import { join as join2 } from "path";
504
504
 
505
+ // ../../packages/schema/src/drizzle/deferred-migrations.ts
506
+ var DEFERRED_MIGRATION_TAGS = [
507
+ "0031_audit_capture_by_time_index",
508
+ "0032_audit_capture_by_id_index",
509
+ "0033_audit_capture_location_index",
510
+ "0034_findings_read_indexes"
511
+ ];
512
+
505
513
  // ../../packages/schema/src/drizzle/sqlite-ddl.ts
506
514
  var SQLITE_MIGRATIONS = [
507
515
  {
@@ -619,6 +627,30 @@ var SQLITE_MIGRATIONS = [
619
627
  {
620
628
  tag: "0028_activity_session_probe_indexes",
621
629
  sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"
630
+ },
631
+ {
632
+ tag: "0029_audit_capture_rollup_index",
633
+ sql: "CREATE INDEX `idx_audit_capture_rollup` ON `audit_events` (`event_type`,`started_at`,`repo`,`id`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
634
+ },
635
+ {
636
+ tag: "0030_audit_content_expiry",
637
+ sql: "ALTER TABLE `audit_events` ADD `content_expired_at` integer;--> statement-breakpoint\nCREATE INDEX `idx_audit_expirable_body` ON `audit_events` (`started_at`) WHERE content IS NOT NULL;"
638
+ },
639
+ {
640
+ tag: "0031_audit_capture_by_time_index",
641
+ sql: "CREATE INDEX `idx_audit_capture_by_time` ON `audit_events` (`started_at`,`id`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
642
+ },
643
+ {
644
+ tag: "0032_audit_capture_by_id_index",
645
+ sql: "CREATE INDEX `idx_audit_capture_by_id` ON `audit_events` (`id`,`started_at`,`event_type`,`root_session_id`,`source_tool`,`repo`,`file_path`,`tool_name`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
646
+ },
647
+ {
648
+ tag: "0033_audit_capture_location_index",
649
+ sql: "CREATE INDEX `idx_audit_capture_location` ON `audit_events` (`repo`,`file_path`,`started_at`,`id`,`event_type`) WHERE event_type IN ('prompt','response','code_change','tool_use');"
650
+ },
651
+ {
652
+ tag: "0034_findings_read_indexes",
653
+ sql: "CREATE INDEX `idx_inspection_definitions_rule` ON `inspection_definitions` (`rule_id`,`severity`,`category`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_def` ON `inspection_findings` (`inspection_definition_id`,`audit_event_id`);--> statement-breakpoint\nCREATE INDEX `idx_inspection_findings_event_cover` ON `inspection_findings` (`audit_event_id`,`inspection_definition_id`,`action_taken`,`finding_key`,`id`);"
622
654
  }
623
655
  ];
624
656
 
@@ -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: {
@@ -23401,6 +23589,11 @@ function isActionAtLeast(action, floor) {
23401
23589
  function strongerAction(a, b) {
23402
23590
  return actionRank(a) >= actionRank(b) ? a : b;
23403
23591
  }
23592
+ function strongerRedactFallback(local, remote) {
23593
+ if (remote === void 0) return local;
23594
+ const localAction = builtinPolicyToAction(local);
23595
+ return localAction === strongerAction(localAction, builtinPolicyToAction(remote)) ? local : remote;
23596
+ }
23404
23597
  function weakestBuiltinAtLeast(floor) {
23405
23598
  return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
23406
23599
  }
@@ -23649,7 +23842,7 @@ function isVaultConsentValid(consent) {
23649
23842
  }
23650
23843
 
23651
23844
  // ../../packages/schema/src/zod/local.ts
23652
- var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
23845
+ var WORKSPACE_SETTINGS_SPEC_VERSION = 8;
23653
23846
  var MODEL_JUDGE_PAYLOAD_VERSION = 1;
23654
23847
  var RunMode = external_exports.enum(["standalone", "attached"]);
23655
23848
  var ControlPlaneConnection = external_exports.object({
@@ -23669,6 +23862,15 @@ var HistorySyncConsent = external_exports.object({
23669
23862
  payloadVersion: external_exports.number().int().positive(),
23670
23863
  endpoint: external_exports.string()
23671
23864
  });
23865
+ var BODY_RETENTION_DEFAULT_DAYS = 30;
23866
+ var BodyRetention = external_exports.object({
23867
+ enabled: external_exports.boolean().default(false),
23868
+ // Never 0, and the ceiling is a fat-finger guard rather than a policy
23869
+ // limit — `enabled` is the real gate. A low value cannot reach a row the
23870
+ // sync ledger still owes: the sweep's age filter only ever NARROWS a
23871
+ // candidate set that is already bounded by "delivered, or never owed".
23872
+ retainDays: external_exports.number().int().min(1).max(3650).default(BODY_RETENTION_DEFAULT_DAYS)
23873
+ }).meta({ id: "BodyRetention" });
23672
23874
  var WorkspaceSettings = external_exports.object({
23673
23875
  specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
23674
23876
  runMode: RunMode.default("standalone"),
@@ -23717,7 +23919,13 @@ var WorkspaceSettings = external_exports.object({
23717
23919
  // carry prompt/reply/tool-output text in `content`; the key name predates
23718
23920
  // both widenings. Absent until granted, and a grant for a different endpoint
23719
23921
  // or an older payload no longer counts.
23720
- historySyncConsent: HistorySyncConsent.optional()
23922
+ historySyncConsent: HistorySyncConsent.optional(),
23923
+ // Local body expiry (see BodyRetention). Off until switched on; expiring a
23924
+ // body never removes the row or its findings.
23925
+ bodyRetention: BodyRetention.default({
23926
+ enabled: false,
23927
+ retainDays: BODY_RETENTION_DEFAULT_DAYS
23928
+ })
23721
23929
  });
23722
23930
  function defaultWorkspaceSettings() {
23723
23931
  return WorkspaceSettings.parse({});
@@ -23812,12 +24020,15 @@ function toCaptureAttributes(event) {
23812
24020
  ...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
23813
24021
  ...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
23814
24022
  ...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
24023
+ ...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
23815
24024
  // `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
23816
24025
  // has ever populated either), but every legacy metadata key still rides
23817
24026
  // the bag rather than being silently dropped — CaptureAttributes'
23818
24027
  // `.catchall(z.unknown())` carries the long tail.
23819
24028
  ...metadata?.model !== void 0 ? { model: metadata.model } : {},
23820
- ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
24029
+ ...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {},
24030
+ ...metadata?.messageId !== void 0 ? { message_id: metadata.messageId } : {},
24031
+ ...metadata?.conversationId !== void 0 ? { conversation_id: metadata.conversationId } : {}
23821
24032
  };
23822
24033
  }
23823
24034
  function captureDefinitionVersion(finding) {
@@ -23845,13 +24056,22 @@ var ManagedSettingKey = external_exports.enum([
23845
24056
  "vaultInlineReveal",
23846
24057
  "modelJudgeConsent",
23847
24058
  "dataSharesInPlace",
23848
- "redactFallback"
24059
+ "redactFallback",
24060
+ // Pins the toggle and the day count together — see BodyRetention on why the
24061
+ // two are one unit. An administrator mandating a window wants the count
24062
+ // enforced with it, not one a user can widen while the toggle stays on.
24063
+ "bodyRetention"
23849
24064
  ]).meta({ id: "ManagedSettingKey" });
23850
24065
  function isManagedSettingKey(value) {
23851
24066
  return ManagedSettingKey.safeParse(value).success;
23852
24067
  }
23853
24068
  var ManagedSettingsValues = external_exports.object({
23854
24069
  runMode: external_exports.enum(["standalone", "attached"]).optional(),
24070
+ // `controlPlane` and `bodyRetention` are the two nested values, and both are
24071
+ // plain, non-strict objects: a key under either that this build does not know
24072
+ // is stripped and nothing reports it. The unknown-value split in
24073
+ // ManagedSettings below classifies top-level names only, so it stops at
24074
+ // these boundaries.
23855
24075
  controlPlane: external_exports.object({
23856
24076
  endpoint: external_exports.string().min(1),
23857
24077
  label: external_exports.string().min(1).optional()
@@ -23862,7 +24082,8 @@ var ManagedSettingsValues = external_exports.object({
23862
24082
  vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
23863
24083
  modelJudgeConsent: external_exports.boolean().optional(),
23864
24084
  dataSharesInPlace: external_exports.boolean().optional(),
23865
- redactFallback: RedactFallback.optional()
24085
+ redactFallback: RedactFallback.optional(),
24086
+ bodyRetention: BodyRetention.optional()
23866
24087
  }).meta({ id: "ManagedSettingsValues" });
23867
24088
  var ManagedSettings = external_exports.object({
23868
24089
  specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
@@ -23870,7 +24091,21 @@ var ManagedSettings = external_exports.object({
23870
24091
  // decision from a bug. Absent renders as a generic "your organization".
23871
24092
  organization: external_exports.string().min(1).optional(),
23872
24093
  // What the administrator pinned.
23873
- values: ManagedSettingsValues.default({}),
24094
+ //
24095
+ // Parsed as a RECORD rather than as the nested schema, and split below for
24096
+ // the same reason `lockedFields` is parsed as names: a plain `z.object`
24097
+ // drops an unrecognised key and succeeds, so a pin this build does not know
24098
+ // vanished and nothing anywhere said so. A pin with no lock is a supported
24099
+ // shape — it is a DEFAULT the user may still change — so that silence hit
24100
+ // exactly the file an administrator is most likely to write while a fleet
24101
+ // is mid-upgrade.
24102
+ //
24103
+ // Splitting here rather than calling `.strict()`: strict would REFUSE the
24104
+ // file, which is the outcome the lock half already rejected — an older
24105
+ // build then runs entirely unmanaged, every pin and lock gone. A bad KNOWN
24106
+ // value still fails, because the nested schema is re-run over the known
24107
+ // subset and its issues are re-raised on this parse.
24108
+ values: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
23874
24109
  // Which of those the user may not change. A key here with no matching value
23875
24110
  // freezes whatever the user last chose; a value with no lock is a DEFAULT
23876
24111
  // the user may still override. The two are separable on purpose.
@@ -23883,17 +24118,31 @@ var ManagedSettings = external_exports.object({
23883
24118
  // the fleets most likely to carry a version skew. A name outside the enum
23884
24119
  // is still never HONOURED: the lockable set stays explicit above.
23885
24120
  lockedFields: external_exports.array(external_exports.string()).default([])
23886
- }).transform(({ lockedFields, ...rest }) => {
24121
+ }).transform(({ lockedFields, values, ...rest }, ctx) => {
23887
24122
  const known = [];
23888
24123
  const unknown2 = [];
23889
24124
  for (const name of lockedFields) {
23890
24125
  if (isManagedSettingKey(name)) known.push(name);
23891
24126
  else unknown2.push(name);
23892
24127
  }
24128
+ const knownValues = /* @__PURE__ */ Object.create(null);
24129
+ const unknownValues = [];
24130
+ for (const [name, value] of Object.entries(values)) {
24131
+ if (Object.hasOwn(ManagedSettingsValues.shape, name)) knownValues[name] = value;
24132
+ else unknownValues.push(name);
24133
+ }
24134
+ const pinned = ManagedSettingsValues.safeParse(knownValues);
24135
+ if (!pinned.success) {
24136
+ for (const issue2 of pinned.error.issues)
24137
+ ctx.addIssue({ ...issue2, path: ["values", ...issue2.path] });
24138
+ return external_exports.NEVER;
24139
+ }
23893
24140
  return {
23894
24141
  ...rest,
24142
+ values: pinned.data,
23895
24143
  lockedFields: known,
23896
- ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {}
24144
+ ...unknown2.length > 0 ? { unknownLockedFields: unknown2 } : {},
24145
+ ...unknownValues.length > 0 ? { unknownValueFields: unknownValues } : {}
23897
24146
  };
23898
24147
  }).meta({ id: "ManagedSettings" });
23899
24148
 
@@ -24157,7 +24406,23 @@ var SaveSettingsInput = external_exports.object({
24157
24406
  modelJudgeConsent: ModelJudgeConsentChoice,
24158
24407
  historySyncConsent: HistorySyncConsentChoice,
24159
24408
  vaultConsent: external_exports.string(),
24160
- vaultInlineReveal: external_exports.string()
24409
+ vaultInlineReveal: external_exports.string(),
24410
+ // Widened to `string` like its neighbours rather than typed as
24411
+ // `RedactFallback`, on this module's own layering rule: shape here, VALUE at
24412
+ // the call site, so the domain check receives the type it was written for.
24413
+ //
24414
+ // NOT because a narrower schema would reject differently. `parseActionInput`
24415
+ // is a `safeParse` wrapper and throws for no field schema, so either spelling
24416
+ // reaches a recoverable `{ ok: false }` and there is no rejected promise to
24417
+ // trade against. The real cost runs the other way and is the part worth
24418
+ // knowing: a value this schema admits and the domain enum then rejects lands
24419
+ // on the action's shared refusal, which names NO field, where a shape
24420
+ // rejection reaches `malformedInput` and names the schema key.
24421
+ redactFallback: external_exports.string(),
24422
+ // Shape only, the way the enum fields above are strings only: the RANGE is
24423
+ // `BodyRetention`'s and the action checks it there, so there is one place
24424
+ // that decides what a legal horizon is rather than two that can drift.
24425
+ bodyRetention: external_exports.object({ enabled: external_exports.boolean(), retainDays: external_exports.number() })
24161
24426
  });
24162
24427
  var AttachInput = external_exports.object({
24163
24428
  endpoint: external_exports.string(),
@@ -24329,6 +24594,52 @@ function reviewSeverityRank(reasons) {
24329
24594
  return Math.min(...reasons.map((r) => REVIEW_SEVERITY_RANK[r]));
24330
24595
  }
24331
24596
 
24597
+ // ../../packages/schema/src/zod/web-capture.ts
24598
+ var WebUsageSource = external_exports.enum(["site", "estimated", "none"]);
24599
+ var WebUsage = external_exports.object({
24600
+ inputTokens: external_exports.number().int().nonnegative().optional(),
24601
+ outputTokens: external_exports.number().int().nonnegative().optional(),
24602
+ cacheReadInputTokens: external_exports.number().int().nonnegative().optional(),
24603
+ cacheCreationInputTokens: external_exports.number().int().nonnegative().optional()
24604
+ });
24605
+ var WebToolCall = external_exports.object({
24606
+ toolUseId: external_exports.string().min(1),
24607
+ toolName: external_exports.string().min(1),
24608
+ target: external_exports.string().optional(),
24609
+ isError: external_exports.boolean().optional(),
24610
+ inputSize: external_exports.number().int().nonnegative().optional(),
24611
+ outputSize: external_exports.number().int().nonnegative().optional()
24612
+ });
24613
+ var WebExchange = external_exports.object({
24614
+ messageId: external_exports.string().min(1),
24615
+ startedAt: external_exports.iso.datetime(),
24616
+ model: external_exports.string().optional(),
24617
+ usage: WebUsage.optional(),
24618
+ usageSource: WebUsageSource,
24619
+ stopReason: external_exports.string().optional(),
24620
+ conversationId: external_exports.string().optional(),
24621
+ turnIndex: external_exports.number().int().nonnegative().optional(),
24622
+ toolCalls: external_exports.array(WebToolCall).default([]),
24623
+ // Absent when the adapter recovered no text. Capped by the caller at
24624
+ // RESPONSE_TEXT_MAX_BYTES; `truncated` records that the cap was reached, so a
24625
+ // short capture is never mistaken for a short reply.
24626
+ responseText: external_exports.string().optional(),
24627
+ truncated: external_exports.boolean().default(false)
24628
+ });
24629
+ var RESPONSE_TEXT_MAX_BYTES = 2 * 1024 * 1024;
24630
+ var WebCaptureStatus = external_exports.object({
24631
+ patched: external_exports.boolean(),
24632
+ live: external_exports.boolean(),
24633
+ blind: external_exports.boolean(),
24634
+ sendsSeenDom: external_exports.number().int().nonnegative(),
24635
+ exchangesSeenNet: external_exports.number().int().nonnegative(),
24636
+ parseFailures: external_exports.number().int().nonnegative(),
24637
+ unparsedBodies: external_exports.number().int().nonnegative(),
24638
+ // The adapter-declared JSON key paths that were absent from a real payload —
24639
+ // the earliest signal that a site's contract moved.
24640
+ shapeMisses: external_exports.array(external_exports.string()).default([])
24641
+ });
24642
+
24332
24643
  // ../../packages/persistence/src/paths.ts
24333
24644
  import {
24334
24645
  chmodSync,
@@ -24689,6 +25000,22 @@ function discardStore(file2, backup) {
24689
25000
  }
24690
25001
  }
24691
25002
 
25003
+ // ../../packages/persistence/src/internal/sql-functions.ts
25004
+ var utf8 = new TextDecoder();
25005
+ function akaLower(value) {
25006
+ if (value === null) return null;
25007
+ if (typeof value === "string") return value.toLowerCase();
25008
+ if (typeof value === "number" || typeof value === "bigint") return String(value).toLowerCase();
25009
+ return utf8.decode(value).toLowerCase();
25010
+ }
25011
+ function registerSqlFunctions(db) {
25012
+ db.function(
25013
+ "aka_lower",
25014
+ { deterministic: true, directOnly: true, useBigIntArguments: true },
25015
+ akaLower
25016
+ );
25017
+ }
25018
+
24692
25019
  // ../../packages/persistence/src/internal/sql-text.ts
24693
25020
  function escapeLikePattern(s) {
24694
25021
  return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -24773,6 +25100,11 @@ function schemaObjectExists(db, kind, name) {
24773
25100
  function indexExists(db, name) {
24774
25101
  return schemaObjectExists(db, "index", name);
24775
25102
  }
25103
+ function indexColumns(db, name) {
25104
+ if (!indexExists(db, name)) return [];
25105
+ const columns = db.prepare(`PRAGMA index_info(${name})`).all();
25106
+ return columns.map((c) => c.name).filter((c) => c !== null);
25107
+ }
24776
25108
  function columnNames(db, table, opts) {
24777
25109
  const pragma = opts?.includeGenerated ? "table_xinfo" : "table_info";
24778
25110
  const columns = db.prepare(`PRAGMA ${pragma}(${table})`).all();
@@ -24834,177 +25166,819 @@ function mapRowsTolerant(rows, map2) {
24834
25166
  return out;
24835
25167
  }
24836
25168
 
24837
- // ../../packages/persistence/src/migrations.ts
24838
- function describeObject(object2) {
24839
- return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
24840
- }
24841
- function splitStatements(sql) {
24842
- return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
24843
- }
24844
- function createdIndexName(statement) {
24845
- const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
24846
- return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25169
+ // ../../packages/persistence/src/internal/outbox-lane.ts
25170
+ var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
25171
+ var OUTBOX_CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25172
+
25173
+ // ../../packages/persistence/src/sync-failure.ts
25174
+ var SYNC_FAILURE_REASONS = SyncFailureReason.options;
25175
+ function syncFailureRejectCondition(column = "sync_failure") {
25176
+ const members2 = SYNC_FAILURE_REASONS.map((r) => `'${r}'`).join(", ");
25177
+ return `NEW.${column} IS NOT NULL AND NEW.${column} NOT IN (${members2})`;
24847
25178
  }
24848
- var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
24849
- function applyMigrations(db, file2) {
24850
- const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
24851
- db.exec(
24852
- "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
24853
- );
24854
- const applied = new Set(
24855
- db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
24856
- );
24857
- const preLedgerStore = applied.size === 0 && legacyCount > 0;
24858
- const record2 = db.prepare(
24859
- "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
24860
- );
24861
- for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
24862
- if (applied.has(migration.tag)) continue;
24863
- if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
24864
- const evidence = evidenceObjects(migration.sql);
24865
- const present = evidence.filter((o) => evidenceExists(db, o));
24866
- if (present.length > 0 && present.length < evidence.length) {
24867
- const missing = evidence.filter((o) => !present.includes(o));
24868
- 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.`;
24869
- akaWarn(message);
24870
- throw new Error(`[aka] ${message}`);
24871
- }
24872
- const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
24873
- const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
24874
- const statements = splitStatements(migration.sql);
24875
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
24876
- try {
24877
- withTransaction(
24878
- db,
24879
- () => {
24880
- for (const statement of statements) {
24881
- const indexName = createdIndexName(statement);
24882
- if (indexName === void 0) {
24883
- if (alreadyApplied) continue;
24884
- } else if (indexExists(db, indexName)) {
24885
- continue;
24886
- }
24887
- db.exec(statement);
24888
- }
24889
- if (wantsFkOff && !alreadyApplied) {
24890
- const violations = db.prepare("PRAGMA foreign_key_check").all();
24891
- if (violations.length > 0) {
24892
- throw new Error(
24893
- `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
24894
- );
24895
- }
24896
- }
24897
- record2.run(migration.tag, Date.now());
24898
- },
24899
- "IMMEDIATE"
24900
- );
24901
- } finally {
24902
- if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
24903
- }
25179
+
25180
+ // ../../packages/persistence/src/repositories/history-sync.ts
25181
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
25182
+ var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25183
+ var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
25184
+ var COUNTED_EVENT_TYPES = [
25185
+ ...STRUCTURAL_EVENT_TYPES,
25186
+ ...OUTBOX_CAPTURE_EVENT_TYPES
25187
+ ];
25188
+ var COUNTED_TYPE_LIST = COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
25189
+ var PARTITION_BUCKETS = `
25190
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
25191
+ SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
25192
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
25193
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25194
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25195
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25196
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached,
25197
+ -- Spelled as what it INCLUDES rather than what it excludes, so a reason
25198
+ -- added later lands in no bucket and fails the sum assertion, instead
25199
+ -- of silently joining this one.
25200
+ SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0
25201
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25202
+ THEN 1 ELSE 0 END) AS failed,
25203
+ COUNT(*) AS total`;
25204
+ var COUNTED_SCOPE = `
25205
+ WHERE event_type IN (${COUNTED_TYPE_LIST})
25206
+ AND (
25207
+ event_type IN (${TYPE_LIST})
25208
+ OR synced_at IS NOT NULL
25209
+ OR outbox_owed = 1
25210
+ )`;
25211
+ var SKIPPED = -1;
25212
+ var ROW_COLUMNS = `id,
25213
+ parent_id AS parentId,
25214
+ root_session_id AS rootSessionId,
25215
+ event_type AS eventType,
25216
+ host_id AS hostId,
25217
+ harness_id AS harnessId,
25218
+ source_project_id AS sourceProjectId,
25219
+ started_at AS startedAt,
25220
+ ended_at AS endedAt,
25221
+ severity,
25222
+ priority,
25223
+ content,
25224
+ content_hash AS contentHash,
25225
+ attributes`;
25226
+ var SqliteHistorySyncRepository = class {
25227
+ constructor(db) {
25228
+ this.db = db;
25229
+ this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
25230
+ this.sessionsStmt = db.prepare(
25231
+ `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
25232
+ FROM audit_events
25233
+ WHERE synced_at IS NULL
25234
+ AND event_type IN (${TYPE_LIST})
25235
+ AND started_at < :before
25236
+ GROUP BY sessionId
25237
+ ORDER BY earliest
25238
+ LIMIT :limit`
25239
+ );
25240
+ this.rowsStmt = db.prepare(
25241
+ `SELECT ${ROW_COLUMNS}
25242
+ FROM audit_events
25243
+ WHERE synced_at IS NULL
25244
+ AND event_type IN (${TYPE_LIST})
25245
+ AND started_at < :before
25246
+ AND COALESCE(root_session_id, id) = :sessionId
25247
+ ORDER BY (event_type = 'session') DESC, started_at
25248
+ LIMIT :limit`
25249
+ );
25250
+ this.captureRowsStmt = db.prepare(
25251
+ `SELECT ${ROW_COLUMNS}
25252
+ FROM audit_events
25253
+ WHERE synced_at IS NULL
25254
+ AND sync_claimed_at IS NULL
25255
+ AND outbox_owed = 1
25256
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25257
+ AND started_at < :before
25258
+ ORDER BY started_at
25259
+ LIMIT :limit`
25260
+ );
25261
+ this.markOwedStmt = db.prepare(
25262
+ `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
25263
+ );
25264
+ this.markCaptureBacklogOwedStmt = db.prepare(
25265
+ `UPDATE audit_events SET outbox_owed = 1
25266
+ WHERE synced_at IS NULL
25267
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25268
+ AND started_at < :before`
25269
+ );
25270
+ this.stampStmt = db.prepare(
25271
+ `UPDATE audit_events
25272
+ SET synced_at = :at,
25273
+ sync_claimed_at = NULL,
25274
+ sync_failed_at = :failedAt,
25275
+ sync_failure = :failure
25276
+ WHERE id = :id`
25277
+ );
25278
+ this.claimRowStmt = db.prepare(
25279
+ `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
25280
+ );
25281
+ this.releaseRowStmt = db.prepare(
25282
+ `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
25283
+ );
25284
+ this.releaseStaleClaimsStmt = db.prepare(
25285
+ `UPDATE audit_events SET sync_claimed_at = NULL
25286
+ WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
25287
+ );
25288
+ this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
25289
+ FROM audit_events${COUNTED_SCOPE}`);
25290
+ this.partitionByKindStmt = db.prepare(
25291
+ `SELECT event_type AS kind,${PARTITION_BUCKETS}
25292
+ FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
25293
+ GROUP BY event_type`
25294
+ );
25295
+ this.countsStmt = db.prepare(
25296
+ `SELECT
25297
+ SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
25298
+ SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
25299
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25300
+ AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
25301
+ THEN 1 ELSE 0 END) AS skipped,
25302
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25303
+ AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
25304
+ SUM(CASE WHEN synced_at = ${String(SKIPPED)}
25305
+ AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
25306
+ FROM audit_events
25307
+ WHERE event_type IN (${TYPE_LIST})`
25308
+ );
25309
+ this.captureSkipCountStmt = db.prepare(
25310
+ // EVERY sentinel capture, whatever the reason — deliberately NOT split the
25311
+ // way the structural totals are. The split exists because a refusal is
25312
+ // terminal only against the deployment that gave it, and the structural
25313
+ // re-arm frees it on a change of deployment. The capture lane has no such
25314
+ // escape: re-arming a capture would offer one deployment's undelivered
25315
+ // prompts, with their text, to a deployment that never saw them, which is
25316
+ // exactly what disownCapturesStmt exists to prevent. So on this lane both
25317
+ // reasons mean the same thing — this row will not be sent — and splitting
25318
+ // them would put refused captures in a bucket nothing reads and nothing
25319
+ // frees.
25320
+ `SELECT COUNT(*) AS skipped
25321
+ FROM audit_events
25322
+ WHERE synced_at = ${String(SKIPPED)}
25323
+ AND event_type IN (${CAPTURE_TYPE_LIST})`
25324
+ );
25325
+ this.fingerprintStmt = db.prepare(
25326
+ `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
25327
+ FROM history_sync WHERE id = 1`
25328
+ );
25329
+ this.setFingerprintStmt = db.prepare(
25330
+ `UPDATE history_sync
25331
+ SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
25332
+ WHERE id = 1`
25333
+ );
25334
+ this.disownCapturesStmt = db.prepare(
25335
+ `UPDATE audit_events SET outbox_owed = NULL
25336
+ WHERE outbox_owed IS NOT NULL
25337
+ AND event_type IN (${CAPTURE_TYPE_LIST})
25338
+ AND started_at < :attachedAt`
25339
+ );
25340
+ this.rearmStmt = db.prepare(
25341
+ `UPDATE audit_events
25342
+ SET synced_at = NULL, sync_failed_at = NULL, sync_failure = NULL
25343
+ WHERE (synced_at > 0
25344
+ OR sync_failure IN ('deployment_refused', 'detached_undelivered'))
25345
+ AND event_type IN (${TYPE_LIST})`
25346
+ );
25347
+ this.claimStmt = db.prepare(
25348
+ `UPDATE history_sync
25349
+ SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
25350
+ WHERE id = 1
25351
+ AND (owner_pid IS NULL
25352
+ OR heartbeat_at IS NULL
25353
+ OR heartbeat_at < :staleBefore
25354
+ OR heartbeat_at > :now)`
25355
+ );
25356
+ this.heartbeatStmt = db.prepare(
25357
+ `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
25358
+ );
25359
+ this.releaseStmt = db.prepare(
25360
+ `UPDATE history_sync
25361
+ SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
25362
+ WHERE id = 1 AND owner_pid = :pid`
25363
+ );
25364
+ this.closeWindowStmt = db.prepare(
25365
+ `UPDATE audit_events
25366
+ SET synced_at = ${String(SKIPPED)},
25367
+ sync_failed_at = :at,
25368
+ sync_failure = 'detached_undelivered'
25369
+ WHERE synced_at IS NULL
25370
+ AND event_type IN (${TYPE_LIST})
25371
+ AND started_at >= :attachedAt`
25372
+ );
25373
+ this.releaseBoundaryStmt = db.prepare(
25374
+ `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
25375
+ );
25376
+ this.freezeBoundaryStmt = db.prepare(
25377
+ `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
25378
+ );
25379
+ this.leaseStmt = db.prepare(
25380
+ `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
25381
+ acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
25382
+ FROM history_sync WHERE id = 1`
25383
+ );
25384
+ this.inspectionsStmt = db.prepare(
25385
+ `SELECT d.rule_id AS ruleId,
25386
+ d.name AS ruleName,
25387
+ d.version AS ruleVersion,
25388
+ d.category AS category,
25389
+ d.severity AS severity,
25390
+ f.span_start AS spanStart,
25391
+ f.span_end AS spanEnd,
25392
+ f.masked_match AS maskedMatch,
25393
+ f.action_taken AS actionTaken,
25394
+ f.confidence AS confidence
25395
+ FROM inspection_findings f
25396
+ JOIN inspection_definitions d ON d.id = f.inspection_definition_id
25397
+ WHERE f.audit_event_id = :auditEventId
25398
+ ORDER BY f.span_start, f.id`
25399
+ );
24904
25400
  }
24905
- if (legacyCount < SQLITE_MIGRATIONS.length) {
24906
- db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25401
+ db;
25402
+ ensureRowStmt;
25403
+ sessionsStmt;
25404
+ rowsStmt;
25405
+ stampStmt;
25406
+ countsStmt;
25407
+ fingerprintStmt;
25408
+ setFingerprintStmt;
25409
+ rearmStmt;
25410
+ claimStmt;
25411
+ heartbeatStmt;
25412
+ releaseStmt;
25413
+ leaseStmt;
25414
+ inspectionsStmt;
25415
+ closeWindowStmt;
25416
+ releaseBoundaryStmt;
25417
+ freezeBoundaryStmt;
25418
+ captureRowsStmt;
25419
+ markOwedStmt;
25420
+ markCaptureBacklogOwedStmt;
25421
+ captureSkipCountStmt;
25422
+ disownCapturesStmt;
25423
+ partitionStmt;
25424
+ partitionByKindStmt;
25425
+ claimRowStmt;
25426
+ releaseRowStmt;
25427
+ releaseStaleClaimsStmt;
25428
+ /**
25429
+ * The masked detections recorded against one tool call.
25430
+ *
25431
+ * These travel with the event because a tool call's target is not
25432
+ * re-inspectable from the event alone — unlike a capture, where the text
25433
+ * itself is re-scannable. What crosses is the masked match and the rule that
25434
+ * produced it, never the value.
25435
+ */
25436
+ inspectionsFor(auditEventId) {
25437
+ return allRows(this.inspectionsStmt, { auditEventId });
24907
25438
  }
24908
- ensureSyncedAtColumn(db, "audit_events");
24909
- ensureScanLedgerTable(db);
24910
- ensureHistorySyncTable(db);
24911
- ensureBlockedDetectionsTable(db);
24912
- ensureRuleProbeCacheTable(db);
24913
- ensureWriteGateTrigger(db);
24914
- ensureTokenUsageColumns(db);
24915
- reconcileSourceProjectIds(db);
24916
- if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
24917
- const drained = runLegacyHistoryBackfill(db);
24918
- if (drained) applyLegacyDropMigration(db, file2);
25439
+ /**
25440
+ * Sessions with structural rows still to send, oldest first.
25441
+ *
25442
+ * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
25443
+ * read. Anything recorded after the machine attached is the live forward
25444
+ * path's to deliver; this drain exists for what was recorded before it, and a
25445
+ * row both paths send is at best a duplicate request and at worst — for a
25446
+ * session root — an overwrite of the inventory ids the live path resolved.
25447
+ */
25448
+ pendingSessions(limit, before) {
25449
+ return allRows(this.sessionsStmt, { limit, before }).map(
25450
+ (r) => r.sessionId
25451
+ );
24919
25452
  }
24920
- }
24921
- function readLegacyTables(db) {
24922
- let holdsRows = false;
24923
- const marks = [];
24924
- for (const table of ["events", "findings"]) {
24925
- try {
24926
- const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
24927
- if (row === void 0) {
24928
- holdsRows = true;
24929
- marks.push(`${table}:unreadable`);
24930
- continue;
24931
- }
24932
- if (row.n > 0) holdsRows = true;
24933
- marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
24934
- } catch {
24935
- holdsRows = true;
24936
- marks.push(`${table}:unreadable`);
24937
- }
25453
+ /** One session's undelivered structural rows within the backlog, root first. */
25454
+ pendingRows(sessionId, limit, before) {
25455
+ return allRows(this.rowsStmt, { sessionId, limit, before });
24938
25456
  }
24939
- return { holdsRows, mark: marks.join("|") };
24940
- }
24941
- function applyLegacyDropMigration(db, file2) {
24942
- const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
24943
- if (!migration) return;
24944
- const before = file2 === void 0 ? void 0 : readLegacyTables(db);
24945
- if (file2 !== void 0 && before?.holdsRows === true) {
24946
- try {
24947
- backupBeforeLegacyDrop(db, file2);
24948
- } catch (error61) {
24949
- akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
24950
- return;
24951
- }
25457
+ /**
25458
+ * Captures this machine still owes the deployment, oldest first.
25459
+ *
25460
+ * Selected by the `outbox_owed` marker the attached forward path writes, not
25461
+ * by a time window — see captureRowsStmt for why a window could not express
25462
+ * this. `before` is the grace window that leaves a just-recorded capture to
25463
+ * the live path.
25464
+ */
25465
+ pendingCaptureRows(limit, before) {
25466
+ return allRows(this.captureRowsStmt, { limit, before });
24952
25467
  }
24953
- try {
25468
+ /**
25469
+ * Record that a capture is OWED to the deployment.
25470
+ *
25471
+ * Written by the attached forward path when a live send did not confirm
25472
+ * delivery, and read by the drain as the whole of its eligibility test. It is
25473
+ * a fact rather than an inference: the machine was attached, the send did not
25474
+ * land, so the row is owed — which no time window can state, because the same
25475
+ * window that holds the rows a past attachment left owed also holds every
25476
+ * capture recorded while the machine was DETACHED, and those were never
25477
+ * offered to anyone.
25478
+ *
25479
+ * Idempotent, and never un-set: `markSynced` settling the row is what takes it
25480
+ * out of the drain's read.
25481
+ */
25482
+ markCaptureOwed(id) {
25483
+ this.markOwedStmt.run({ id });
25484
+ }
25485
+ /**
25486
+ * Mark every capture already on disk as owed, as of `before`.
25487
+ *
25488
+ * The consent-time backfill, called once from `aka attach` when a human
25489
+ * grants existing-history consent — never from an ongoing drain pass, and
25490
+ * never inferred from a boundary that could later move. `before` is the
25491
+ * caller's own "now" at the moment consent was granted, so what this marks
25492
+ * is exactly the backlog the consent prompt already counted, not whatever a
25493
+ * later re-attach or key rotation might widen it to.
25494
+ *
25495
+ * Returns how many rows matched, for the caller to log or test against. Not a
25496
+ * count of NEWLY marked rows — a row still unsynced from an earlier call
25497
+ * matches again and is counted again, the same as `UPDATE`'s own `changes`.
25498
+ */
25499
+ markCaptureBacklogOwed(before) {
25500
+ return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
25501
+ }
25502
+ /**
25503
+ * Record delivery. Called only AFTER the far side has accepted the rows.
25504
+ *
25505
+ * CLEARS any failure reason in the same statement. A row that failed against
25506
+ * one deployment and then landed is delivered, and leaving the reason behind
25507
+ * would leave the store holding two contradictory answers about one row —
25508
+ * with the surface free to render either.
25509
+ */
25510
+ markSynced(ids, atMs) {
25511
+ this.stampAll(ids, atMs, null);
25512
+ }
25513
+ /**
25514
+ * Record that THIS MACHINE cannot express the row on the wire.
25515
+ *
25516
+ * Reserved for a local defect — a row that cannot be rebuilt into a valid
25517
+ * payload, or a body the client itself refused to send. It fails identically
25518
+ * against every deployment, so it is terminal everywhere and the re-arm leaves
25519
+ * it alone. A row that merely failed to REACH the deployment stays NULL, so it
25520
+ * is retried; marking those would turn one outage into permanent data loss.
25521
+ */
25522
+ markSkipped(ids, atMs) {
25523
+ this.stampAll(ids, SKIPPED, "payload_invalid", atMs);
25524
+ }
25525
+ /**
25526
+ * Record that THIS DEPLOYMENT refused the row.
25527
+ *
25528
+ * The same sentinel as `markSkipped`, and deliberately so: both stop the row
25529
+ * being re-offered on this lane, and `synced_at` goes on answering whether a
25530
+ * row is outstanding rather than why. What separates them is the reason, and
25531
+ * what the reason buys is the re-arm — a refusal is one deployment's verdict
25532
+ * on one body, so it is terminal only for as long as this machine points at
25533
+ * that deployment, and `rearmFor` clears it when the deployment changes.
25534
+ *
25535
+ * Leaving such a row NULL instead would be worse than the loss it replaces:
25536
+ * these reads carry no cursor, so an unstamped row the deployment refuses is
25537
+ * the head of every subsequent page, and the lane stalls behind it for ever.
25538
+ */
25539
+ markRefused(ids, atMs) {
25540
+ this.stampAll(ids, SKIPPED, "deployment_refused", atMs);
25541
+ }
25542
+ eachInTransaction(ids, run) {
25543
+ if (ids.length === 0) return;
24954
25544
  withTransaction(
24955
- db,
25545
+ this.db,
24956
25546
  () => {
24957
- const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
24958
- if (alreadyDropped) return;
24959
- if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
24960
- akaWarn(
24961
- "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
24962
- );
24963
- return;
24964
- }
24965
- for (const statement of splitStatements(migration.sql)) {
24966
- db.exec(statement);
24967
- }
24968
- db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
24969
- migration.tag,
24970
- Date.now()
24971
- );
25547
+ for (const id of ids) run(id);
24972
25548
  },
24973
25549
  "IMMEDIATE"
24974
25550
  );
24975
- } catch (error61) {
24976
- akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
24977
25551
  }
24978
- }
24979
- function backupBeforeLegacyDrop(db, file2) {
24980
- reapStalePartials(file2);
24981
- const backup = backupPath(file2, "pre-drop");
24982
- snapshotStore(db, backup);
24983
- return backup;
24984
- }
24985
- var TOKEN_USAGE_COLUMNS = [
24986
- {
24987
- name: "input_tokens",
24988
- ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
24989
- },
24990
- {
24991
- name: "output_tokens",
24992
- ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
24993
- },
24994
- {
24995
- name: "cache_creation_input_tokens",
24996
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
24997
- },
24998
- {
24999
- name: "cache_read_input_tokens",
25000
- ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
25001
- },
25002
- {
25003
- name: "model",
25004
- ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25005
- },
25006
- {
25007
- name: "provider",
25552
+ stampAll(ids, value, failure, failedAtMs) {
25553
+ if (ids.length === 0) return;
25554
+ const failedAt = failure === null ? null : failedAtMs ?? null;
25555
+ withTransaction(
25556
+ this.db,
25557
+ () => {
25558
+ for (const id of ids) this.stampStmt.run({ at: value, failedAt, failure, id });
25559
+ },
25560
+ "IMMEDIATE"
25561
+ );
25562
+ }
25563
+ /**
25564
+ * Claim rows as in-flight.
25565
+ *
25566
+ * Advisory in exactly the sense the lease is: it records that a send is in
25567
+ * progress so a surface can say so, and a lost claim costs a row showing as
25568
+ * queued while it is actually being sent. It is not exclusion — the far side
25569
+ * settles a duplicate on the row id.
25570
+ */
25571
+ claimRows(ids, atMs) {
25572
+ this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
25573
+ }
25574
+ /** Give back a claim without settling — the send failed, the row is queued again. */
25575
+ releaseRows(ids) {
25576
+ this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
25577
+ }
25578
+ /**
25579
+ * Clear claims older than `staleBefore`, and report how many were cleared.
25580
+ *
25581
+ * A process killed between claiming and settling leaves rows claimed with
25582
+ * nothing left to settle them. Without this they read as "sending" for ever.
25583
+ */
25584
+ releaseStaleClaims(staleBefore) {
25585
+ return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
25586
+ }
25587
+ /**
25588
+ * Every tracked row in exactly one delivery state.
25589
+ *
25590
+ * Takes no boundary on purpose. The boundary answers "what should the drain
25591
+ * pick up now", which is a different question from "what state is this row
25592
+ * in" — and a machine that has never attached has no boundary to pass, so
25593
+ * requiring one would force a caller to invent one and report the whole store
25594
+ * as queued.
25595
+ */
25596
+ /**
25597
+ * The same partition, one row per kind that a lane carries.
25598
+ *
25599
+ * A kind with nothing to report is ABSENT rather than a row of zeros: the
25600
+ * scope decides which rows exist at all, so a kind that has never been
25601
+ * recorded — or whose captures nobody ever owed — produces no group. A caller
25602
+ * rendering a fixed list of kinds must therefore treat a missing one as "no
25603
+ * rows", never as "zero sent"; the two look identical in a bar and mean
25604
+ * different things.
25605
+ */
25606
+ partitionByKind() {
25607
+ return allRows(
25608
+ this.partitionByKindStmt,
25609
+ {}
25610
+ ).map((row) => ({
25611
+ kind: row.kind,
25612
+ queued: row.queued ?? 0,
25613
+ inProgress: row.inProgress ?? 0,
25614
+ synced: row.synced ?? 0,
25615
+ failed: row.failed ?? 0,
25616
+ refused: row.refused ?? 0,
25617
+ detached: row.detached ?? 0,
25618
+ total: row.total ?? 0
25619
+ }));
25620
+ }
25621
+ partition() {
25622
+ const row = getRow(this.partitionStmt, {});
25623
+ return {
25624
+ queued: row?.queued ?? 0,
25625
+ inProgress: row?.inProgress ?? 0,
25626
+ synced: row?.synced ?? 0,
25627
+ failed: row?.failed ?? 0,
25628
+ refused: row?.refused ?? 0,
25629
+ detached: row?.detached ?? 0,
25630
+ total: row?.total ?? 0
25631
+ };
25632
+ }
25633
+ /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
25634
+ counts(before) {
25635
+ const row = getRow(this.countsStmt, { before });
25636
+ const captures = getRow(this.captureSkipCountStmt);
25637
+ return {
25638
+ pending: row?.pending ?? 0,
25639
+ sent: row?.sent ?? 0,
25640
+ skipped: row?.skipped ?? 0,
25641
+ refused: row?.refused ?? 0,
25642
+ detached: row?.detached ?? 0,
25643
+ capturesSkipped: captures?.skipped ?? 0
25644
+ };
25645
+ }
25646
+ /**
25647
+ * The deployment the current stamps were made against, and where its backlog
25648
+ * ends.
25649
+ *
25650
+ * READ-ONLY. An absent row reads as an absent deployment, which is what a
25651
+ * machine that has never drained is — and every writer below seeds the row
25652
+ * before it needs one, so nothing depends on this creating it. Keeping the
25653
+ * write off the gate path matters because the gate runs on every pass while a
25654
+ * write has to take the database's write lock.
25655
+ */
25656
+ deployment() {
25657
+ const row = getRow(
25658
+ this.fingerprintStmt
25659
+ );
25660
+ return {
25661
+ fingerprint: row?.fingerprint ?? void 0,
25662
+ backlogBefore: row?.backlogBefore ?? void 0
25663
+ };
25664
+ }
25665
+ /**
25666
+ * Point the ledger at a different deployment, discarding what it recorded
25667
+ * about the previous one.
25668
+ *
25669
+ * Delivery is a fact about ONE recipient: rows sent to the deployment a
25670
+ * machine has just left are undelivered as far as the new one is concerned.
25671
+ * All four in one transaction, so a crash between them cannot leave stamps
25672
+ * attributed to the wrong deployment, a boundary that belongs to another, or
25673
+ * a disown with no re-mark to follow it.
25674
+ *
25675
+ * The boundary is written HERE and only here, which is what freezes it: a
25676
+ * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
25677
+ * unchanged, so this never runs and the backlog does not widen back over rows
25678
+ * the live path has since delivered.
25679
+ *
25680
+ * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
25681
+ * granted existing-history consent for the deployment this call is arming —
25682
+ * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
25683
+ * instant, `backlogBefore` is the ATTACH instant, and the two can be far
25684
+ * apart. Passed only when that grant is valid, since this method has no way
25685
+ * to check consent itself and must not mark a row owed for a machine that
25686
+ * never agreed to it. Applied AFTER the disown above, in the SAME
25687
+ * transaction: what the disown clears is every marker below `backlogBefore`,
25688
+ * which includes this deployment's OWN pre-attach rows — `aka attach` calls
25689
+ * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
25690
+ * on the cleared side of that bound — and the re-mark in the same
25691
+ * transaction is what puts those rows back. A crash between the two cannot
25692
+ * strand the ledger disowned with nothing re-marked — the transaction either
25693
+ * lands whole or not at all, and a fingerprint mismatch that has not yet
25694
+ * committed re-enters this method on the very next pass. Omit it (the
25695
+ * structural-only tests do) to exercise the disown in isolation.
25696
+ *
25697
+ * The disown is bounded by `backlogBefore`, which is what keeps it from
25698
+ * touching a marker the NEW deployment's OWN live path has already set: B's
25699
+ * live path can mark a capture owed from the moment `aka attach` writes the
25700
+ * descriptor, before the drain's first pass ever reaches this method, and
25701
+ * such a row sits at or after the bound rather than below it. What keeps the
25702
+ * disown from eating THIS SAME CALL's own re-mark is the order, not the
25703
+ * bound — disown runs first, re-mark second, both inside the one
25704
+ * transaction above.
25705
+ */
25706
+ rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
25707
+ this.ensureRowStmt.run();
25708
+ withTransaction(
25709
+ this.db,
25710
+ () => {
25711
+ const previous = getRow(this.fingerprintStmt)?.fingerprint;
25712
+ this.rearmStmt.run();
25713
+ if (previous !== null && previous !== void 0 && previous !== fingerprint) {
25714
+ this.disownCapturesStmt.run({ attachedAt: backlogBefore });
25715
+ }
25716
+ if (backfillCapturesBefore !== void 0) {
25717
+ this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
25718
+ }
25719
+ this.setFingerprintStmt.run({ fingerprint, backlogBefore });
25720
+ },
25721
+ "IMMEDIATE"
25722
+ );
25723
+ }
25724
+ /**
25725
+ * End the attached period: hand its rows to the live path, and release the
25726
+ * boundary so the next attachment can freeze a new one.
25727
+ *
25728
+ * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
25729
+ * nothing delivers. The fingerprint is unchanged, so the boundary is never
25730
+ * re-frozen and stays at the FIRST attachment — while nothing forwards at all
25731
+ * during the detached period, because the machine is not attached. Rows
25732
+ * recorded in that window sit after the boundary and before the re-attach, so
25733
+ * neither path takes them, and the pending count reports none outstanding.
25734
+ *
25735
+ * WHAT IT RECORDS, and what it deliberately does not. These rows were the
25736
+ * closing attachment's to deliver and are no longer outstanding — that is what
25737
+ * lets the boundary move. It is NOT a claim that any of them arrived, and the
25738
+ * distinction is not academic: this used to write a delivery TIME, which every
25739
+ * read treats as delivery, so one detach turned a window of undelivered rows
25740
+ * into a window of delivered ones and no surface could tell. It writes the
25741
+ * skip sentinel and a reason of its own instead, so "no longer owed" and
25742
+ * "received" stop being the same fact.
25743
+ *
25744
+ * A change of deployment still frees them (see the re-arm), because the next
25745
+ * deployment has seen none of this machine's history — so the rows reach it
25746
+ * exactly as they did when this wrote a delivery time.
25747
+ *
25748
+ * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
25749
+ * window unstamped — that half-state would re-send the whole attached period
25750
+ * on the next attach, which is the failure the boundary exists to prevent.
25751
+ */
25752
+ closeAttachedWindow(attachedAtMs, atMs) {
25753
+ this.ensureRowStmt.run();
25754
+ withTransaction(
25755
+ this.db,
25756
+ () => {
25757
+ const row = getRow(this.fingerprintStmt);
25758
+ const from = row?.backlogBefore ?? attachedAtMs;
25759
+ this.closeWindowStmt.run({ at: atMs, attachedAt: from });
25760
+ this.releaseBoundaryStmt.run();
25761
+ },
25762
+ "IMMEDIATE"
25763
+ );
25764
+ }
25765
+ /**
25766
+ * Freeze a boundary for the deployment already on file, KEEPING the stamps.
25767
+ *
25768
+ * The re-attach half of the above. Distinct from `rearmFor`, which is for a
25769
+ * different deployment and therefore discards what was delivered to the old
25770
+ * one: here the recipient is the same, so everything already sent to it stays
25771
+ * sent.
25772
+ */
25773
+ freezeBoundary(backlogBefore) {
25774
+ this.ensureRowStmt.run();
25775
+ this.freezeBoundaryStmt.run({ backlogBefore });
25776
+ }
25777
+ /** Take the claim, or report that someone live already holds it. */
25778
+ claim(pid, host, nowMs, staleAfterMs) {
25779
+ this.ensureRowStmt.run();
25780
+ let taken = false;
25781
+ withTransaction(
25782
+ this.db,
25783
+ () => {
25784
+ const result = this.claimStmt.run({
25785
+ pid,
25786
+ host,
25787
+ now: nowMs,
25788
+ staleBefore: nowMs - staleAfterMs
25789
+ });
25790
+ taken = result.changes === 1;
25791
+ },
25792
+ "IMMEDIATE"
25793
+ );
25794
+ return taken;
25795
+ }
25796
+ /** Say the holder is still alive. A no-op once the claim has moved on. */
25797
+ heartbeat(pid, nowMs) {
25798
+ this.heartbeatStmt.run({ now: nowMs, pid });
25799
+ }
25800
+ /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
25801
+ release(pid) {
25802
+ this.releaseStmt.run({ pid });
25803
+ }
25804
+ /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
25805
+ lease() {
25806
+ return getRow(this.leaseStmt);
25807
+ }
25808
+ };
25809
+
25810
+ // ../../packages/persistence/src/migrations.ts
25811
+ function describeObject(object2) {
25812
+ return object2.kind === "column" ? `column ${object2.table}.${object2.name}` : `table ${object2.name}`;
25813
+ }
25814
+ function splitStatements(sql) {
25815
+ return sql.split(/-->\s*statement-breakpoint/).map((s) => s.trim()).filter((s) => s.length > 0);
25816
+ }
25817
+ function createdIndexName(statement) {
25818
+ const body = statement.replace(/^(?:\s*--[^\n]*\n?)+/, "").trimStart();
25819
+ return /^CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?`([^`]+)`/.exec(body)?.[1];
25820
+ }
25821
+ var LEGACY_DROP_MIGRATION_TAG = "0014_drop_legacy_events_findings";
25822
+ function applyMigrations(db, file2, options = {}) {
25823
+ const legacyCount = db.prepare("PRAGMA user_version").get().user_version;
25824
+ db.exec(
25825
+ "CREATE TABLE IF NOT EXISTS migration_ledger (tag TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)"
25826
+ );
25827
+ const applied = new Set(
25828
+ db.prepare("SELECT tag FROM migration_ledger").all().map((r) => r.tag)
25829
+ );
25830
+ const preLedgerStore = applied.size === 0 && legacyCount > 0;
25831
+ const record2 = db.prepare(
25832
+ "INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)"
25833
+ );
25834
+ for (const [index, migration] of SQLITE_MIGRATIONS.entries()) {
25835
+ if (applied.has(migration.tag)) continue;
25836
+ if (options.skipTags?.has(migration.tag) === true) continue;
25837
+ if (migration.tag === LEGACY_DROP_MIGRATION_TAG) continue;
25838
+ const evidence = evidenceObjects(migration.sql);
25839
+ const present = evidence.filter((o) => evidenceExists(db, o));
25840
+ if (present.length > 0 && present.length < evidence.length) {
25841
+ const missing = evidence.filter((o) => !present.includes(o));
25842
+ 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.`;
25843
+ akaWarn(message);
25844
+ throw new Error(`[aka] ${message}`);
25845
+ }
25846
+ const alreadyApplied = evidence.length > 0 ? present.length === evidence.length : preLedgerStore && index < legacyCount;
25847
+ const wantsFkOff = /PRAGMA foreign_keys\s*=\s*OFF/i.test(migration.sql);
25848
+ const statements = splitStatements(migration.sql);
25849
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = OFF");
25850
+ try {
25851
+ withTransaction(
25852
+ db,
25853
+ () => {
25854
+ for (const statement of statements) {
25855
+ const indexName = createdIndexName(statement);
25856
+ if (indexName === void 0) {
25857
+ if (alreadyApplied) continue;
25858
+ } else if (indexExists(db, indexName)) {
25859
+ continue;
25860
+ }
25861
+ db.exec(statement);
25862
+ }
25863
+ if (wantsFkOff && !alreadyApplied) {
25864
+ const violations = db.prepare("PRAGMA foreign_key_check").all();
25865
+ if (violations.length > 0) {
25866
+ throw new Error(
25867
+ `[aka] sqlite migration ${migration.tag} left ${String(violations.length)} foreign-key violation(s); rolling back.`
25868
+ );
25869
+ }
25870
+ }
25871
+ record2.run(migration.tag, Date.now());
25872
+ },
25873
+ "IMMEDIATE"
25874
+ );
25875
+ } finally {
25876
+ if (wantsFkOff) db.exec("PRAGMA foreign_keys = ON");
25877
+ }
25878
+ }
25879
+ if (legacyCount < SQLITE_MIGRATIONS.length) {
25880
+ db.exec(`PRAGMA user_version = ${String(SQLITE_MIGRATIONS.length)}`);
25881
+ }
25882
+ ensureSyncedAtColumn(db, "audit_events");
25883
+ ensureScanLedgerTable(db);
25884
+ ensureHistorySyncTable(db);
25885
+ ensureBlockedDetectionsTable(db);
25886
+ ensureRuleProbeCacheTable(db);
25887
+ ensureWriteGateTrigger(db);
25888
+ ensureTokenUsageColumns(db);
25889
+ reconcileSourceProjectIds(db);
25890
+ if (!applied.has(LEGACY_DROP_MIGRATION_TAG)) {
25891
+ const drained = runLegacyHistoryBackfill(db);
25892
+ if (drained) applyLegacyDropMigration(db, file2);
25893
+ }
25894
+ }
25895
+ function readLegacyTables(db) {
25896
+ let holdsRows = false;
25897
+ const marks = [];
25898
+ for (const table of ["events", "findings"]) {
25899
+ try {
25900
+ const row = db.prepare(`SELECT count(*) AS n, ifnull(max(rowid), -1) AS hi FROM ${table}`).get();
25901
+ if (row === void 0) {
25902
+ holdsRows = true;
25903
+ marks.push(`${table}:unreadable`);
25904
+ continue;
25905
+ }
25906
+ if (row.n > 0) holdsRows = true;
25907
+ marks.push(`${table}:${String(row.n)}:${String(row.hi)}`);
25908
+ } catch {
25909
+ holdsRows = true;
25910
+ marks.push(`${table}:unreadable`);
25911
+ }
25912
+ }
25913
+ return { holdsRows, mark: marks.join("|") };
25914
+ }
25915
+ function applyLegacyDropMigration(db, file2) {
25916
+ const migration = SQLITE_MIGRATIONS.find((m) => m.tag === LEGACY_DROP_MIGRATION_TAG);
25917
+ if (!migration) return;
25918
+ const before = file2 === void 0 ? void 0 : readLegacyTables(db);
25919
+ if (file2 !== void 0 && before?.holdsRows === true) {
25920
+ try {
25921
+ backupBeforeLegacyDrop(db, file2);
25922
+ } catch (error61) {
25923
+ akaWarn(`legacy events/findings backup failed; deferring the drop: ${String(error61)}`);
25924
+ return;
25925
+ }
25926
+ }
25927
+ try {
25928
+ withTransaction(
25929
+ db,
25930
+ () => {
25931
+ const alreadyDropped = db.prepare("SELECT 1 FROM migration_ledger WHERE tag = ?").get(migration.tag);
25932
+ if (alreadyDropped) return;
25933
+ if (before !== void 0 && readLegacyTables(db).mark !== before.mark) {
25934
+ akaWarn(
25935
+ "legacy events/findings rows changed after the pre-drop snapshot decision; deferring the drop so the next open can copy them first."
25936
+ );
25937
+ return;
25938
+ }
25939
+ for (const statement of splitStatements(migration.sql)) {
25940
+ db.exec(statement);
25941
+ }
25942
+ db.prepare("INSERT OR IGNORE INTO migration_ledger (tag, applied_at) VALUES (?, ?)").run(
25943
+ migration.tag,
25944
+ Date.now()
25945
+ );
25946
+ },
25947
+ "IMMEDIATE"
25948
+ );
25949
+ } catch (error61) {
25950
+ akaWarn(`legacy events/findings drop failed; deferring: ${String(error61)}`);
25951
+ }
25952
+ }
25953
+ function backupBeforeLegacyDrop(db, file2) {
25954
+ reapStalePartials(file2);
25955
+ const backup = backupPath(file2, "pre-drop");
25956
+ snapshotStore(db, backup);
25957
+ return backup;
25958
+ }
25959
+ var TOKEN_USAGE_COLUMNS = [
25960
+ {
25961
+ name: "input_tokens",
25962
+ ddl: "ALTER TABLE audit_events ADD COLUMN input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.input_tokens')) VIRTUAL"
25963
+ },
25964
+ {
25965
+ name: "output_tokens",
25966
+ ddl: "ALTER TABLE audit_events ADD COLUMN output_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.output_tokens')) VIRTUAL"
25967
+ },
25968
+ {
25969
+ name: "cache_creation_input_tokens",
25970
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_creation_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_creation_input_tokens')) VIRTUAL"
25971
+ },
25972
+ {
25973
+ name: "cache_read_input_tokens",
25974
+ ddl: "ALTER TABLE audit_events ADD COLUMN cache_read_input_tokens integer GENERATED ALWAYS AS (json_extract(attributes, '$.cache_read_input_tokens')) VIRTUAL"
25975
+ },
25976
+ {
25977
+ name: "model",
25978
+ ddl: "ALTER TABLE audit_events ADD COLUMN model text GENERATED ALWAYS AS (json_extract(attributes, '$.model')) VIRTUAL"
25979
+ },
25980
+ {
25981
+ name: "provider",
25008
25982
  ddl: "ALTER TABLE audit_events ADD COLUMN provider text GENERATED ALWAYS AS (json_extract(attributes, '$.provider')) VIRTUAL"
25009
25983
  }
25010
25984
  ];
@@ -25266,10 +26240,62 @@ function ensureSyncedAtColumn(db, table) {
25266
26240
  if (!columns.includes("outbox_owed")) {
25267
26241
  db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
25268
26242
  }
26243
+ if (!columns.includes("sync_failed_at")) {
26244
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failed_at integer`);
26245
+ }
26246
+ if (!columns.includes("sync_failure")) {
26247
+ withTransaction(
26248
+ db,
26249
+ () => {
26250
+ db.exec(`ALTER TABLE ${table} ADD COLUMN sync_failure text`);
26251
+ db.exec(
26252
+ `UPDATE ${table} SET synced_at = NULL
26253
+ WHERE synced_at = -1
26254
+ AND event_type IN (${COUNTED_EVENT_TYPES.map((t) => `'${t}'`).join(", ")})`
26255
+ );
26256
+ },
26257
+ "IMMEDIATE"
26258
+ );
26259
+ }
25269
26260
  db.exec(
25270
- `CREATE INDEX IF NOT EXISTS idx_audit_events_sync
25271
- ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
26261
+ `CREATE TRIGGER IF NOT EXISTS aka_sync_failure_guard
26262
+ BEFORE UPDATE OF sync_failure ON ${table}
26263
+ WHEN ${syncFailureRejectCondition()}
26264
+ BEGIN SELECT RAISE(ABORT, 'sync_failure is not one of the recorded reasons'); END`
25272
26265
  );
26266
+ const syncIndexColumns = [
26267
+ "event_type",
26268
+ "synced_at",
26269
+ "sync_claimed_at",
26270
+ "started_at",
26271
+ // Appended LAST on purpose. The delivery-state read now projects it, so it
26272
+ // has to be in the index for the read to stay covered — but putting it
26273
+ // ahead of `started_at` would reorder the prefix the structural drain's
26274
+ // reads match on.
26275
+ "sync_failure"
26276
+ // `outbox_owed` is DELIBERATELY ABSENT, and it was measured both ways.
26277
+ //
26278
+ // The delivery-state read tests it — a capture's state depends on whether a
26279
+ // live forward marked it owed — so carrying it here makes that read covering
26280
+ // rather than a row fetch per row: 16 ms against 40 ms on a real 6 GB store.
26281
+ // But a sixth column changes what the planner charges for this index, and
26282
+ // with no ANALYZE statistics it plans from schema shape alone: measured, it
26283
+ // then stops choosing the per-session index for the token rollup and walks
26284
+ // every `llm_call` in the store through the event-type index instead. That
26285
+ // read grows with the store; this one does not.
26286
+ //
26287
+ // 40 ms on the largest store measured, once per render, is a cost worth
26288
+ // paying to leave every other read's plan where it was.
26289
+ ];
26290
+ const currentSyncIndex = indexColumns(db, "idx_audit_events_sync");
26291
+ const syncIndexMatches = currentSyncIndex.length === syncIndexColumns.length && currentSyncIndex.every((column, i) => column === syncIndexColumns[i]);
26292
+ if (!syncIndexMatches) {
26293
+ db.exec("DROP INDEX IF EXISTS idx_audit_events_sync");
26294
+ db.exec(
26295
+ `CREATE INDEX idx_audit_events_sync
26296
+ ON audit_events (${syncIndexColumns.join(", ")})`
26297
+ );
26298
+ }
25273
26299
  db.exec(
25274
26300
  `CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
25275
26301
  ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
@@ -25491,7 +26517,11 @@ function buildAuditEvent(row) {
25491
26517
  link: linkParsed?.success ? linkParsed.data : null,
25492
26518
  targetId: row.target_id,
25493
26519
  internal: intToBool(row.internal),
25494
- flagged: intToBool(row.flagged)
26520
+ flagged: intToBool(row.flagged),
26521
+ // Only meaningful when the title came out empty — a row whose body was
26522
+ // expired but whose title fell back to `tool_name` still has something to
26523
+ // render, and flagging it would make the view apologise for nothing.
26524
+ bodyExpired: row.content_expired_at !== null && (row.title ?? "") === ""
25495
26525
  };
25496
26526
  }
25497
26527
  var TIMELINE_COLUMNS = `
@@ -25499,6 +26529,7 @@ var TIMELINE_COLUMNS = `
25499
26529
  event_type,
25500
26530
  started_at,
25501
26531
  coalesce(content, json_extract(attributes, '$.tool_name')) AS title,
26532
+ content_expired_at,
25502
26533
  coalesce(json_extract(attributes, '$.detail'), json_extract(attributes, '$.target')) AS detail,
25503
26534
  coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
25504
26535
  json_extract(attributes, '$.severity') AS severity,
@@ -26164,6 +27195,88 @@ var SqliteAuditEventsRepository = class {
26164
27195
  }
26165
27196
  };
26166
27197
 
27198
+ // ../../packages/persistence/src/repositories/body-retention.ts
27199
+ var DEFAULT_BATCH_SIZE = 500;
27200
+ var DEFAULT_MAX_ROWS = 5e4;
27201
+ var SYNC_LANE_TYPES_SQL = OUTBOX_CAPTURE_TYPE_LIST;
27202
+ var SqliteBodyRetentionRepository = class {
27203
+ constructor(db) {
27204
+ this.db = db;
27205
+ const select = (laneClause) => `
27206
+ SELECT id, LENGTH(CAST(content AS BLOB)) AS bytes
27207
+ FROM audit_events
27208
+ WHERE content IS NOT NULL
27209
+ AND started_at < :cutoff
27210
+ AND event_type IN (${CAPTURE_EVENT_TYPES_SQL})
27211
+ ${laneClause}
27212
+ ORDER BY started_at
27213
+ LIMIT :limit`;
27214
+ this.candidatesStmt = this.db.prepare(select(""));
27215
+ this.candidatesSyncSafeStmt = this.db.prepare(
27216
+ select(`AND (event_type NOT IN (${SYNC_LANE_TYPES_SQL}) OR synced_at IS NOT NULL)`)
27217
+ );
27218
+ this.heldBySyncStmt = this.db.prepare(`
27219
+ SELECT COUNT(*) AS n
27220
+ FROM audit_events
27221
+ WHERE content IS NOT NULL
27222
+ AND started_at < :cutoff
27223
+ AND event_type IN (${SYNC_LANE_TYPES_SQL})
27224
+ AND synced_at IS NULL`);
27225
+ this.expireStmt = this.db.prepare(
27226
+ `UPDATE audit_events SET content = NULL, content_expired_at = :now WHERE id = :id`
27227
+ );
27228
+ }
27229
+ db;
27230
+ candidatesStmt;
27231
+ candidatesSyncSafeStmt;
27232
+ heldBySyncStmt;
27233
+ expireStmt;
27234
+ /** How many bytes a pass with these options would free, changing nothing. */
27235
+ preview(opts) {
27236
+ const limit = opts.maxRows ?? DEFAULT_MAX_ROWS;
27237
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27238
+ const rows = stmt.all({ cutoff: opts.cutoff, limit });
27239
+ return {
27240
+ rowsExpired: rows.length,
27241
+ bytesFreed: rows.reduce((sum, r) => sum + r.bytes, 0),
27242
+ rowsHeldBySync: this.countHeldBySync(opts)
27243
+ };
27244
+ }
27245
+ /** Clear eligible bodies, in bounded batches. */
27246
+ expire(opts) {
27247
+ const batchSize = opts.batchSize ?? DEFAULT_BATCH_SIZE;
27248
+ const maxRows = opts.maxRows ?? DEFAULT_MAX_ROWS;
27249
+ const stmt = opts.sweepSyncLane ? this.candidatesStmt : this.candidatesSyncSafeStmt;
27250
+ let rowsExpired = 0;
27251
+ let bytesFreed = 0;
27252
+ let done = true;
27253
+ while (rowsExpired < maxRows) {
27254
+ const remaining = Math.min(batchSize, maxRows - rowsExpired);
27255
+ const batch = stmt.all({ cutoff: opts.cutoff, limit: remaining });
27256
+ if (batch.length === 0) break;
27257
+ withTransaction(
27258
+ this.db,
27259
+ () => {
27260
+ for (const row of batch) this.expireStmt.run({ id: row.id, now: opts.now });
27261
+ },
27262
+ "IMMEDIATE"
27263
+ );
27264
+ rowsExpired += batch.length;
27265
+ bytesFreed += batch.reduce((sum, r) => sum + r.bytes, 0);
27266
+ if (batch.length < remaining) break;
27267
+ if (rowsExpired >= maxRows) {
27268
+ done = stmt.all({ cutoff: opts.cutoff, limit: 1 }).length === 0;
27269
+ }
27270
+ }
27271
+ return { rowsExpired, bytesFreed, rowsHeldBySync: this.countHeldBySync(opts), done };
27272
+ }
27273
+ countHeldBySync(opts) {
27274
+ if (opts.sweepSyncLane) return 0;
27275
+ const row = this.heldBySyncStmt.get({ cutoff: opts.cutoff });
27276
+ return row.n;
27277
+ }
27278
+ };
27279
+
26167
27280
  // ../../packages/persistence/src/repositories/classified-data.ts
26168
27281
  var SqliteClassifiedDataRepository = class {
26169
27282
  constructor(db) {
@@ -26992,7 +28105,15 @@ function toFlatFindingRow(r) {
26992
28105
  ...r.tool_name === null ? {} : { toolName: r.tool_name },
26993
28106
  eventId: r.event_id,
26994
28107
  ...r.session_id === null ? {} : { sessionId: r.session_id },
26995
- status: deriveInstanceStatus(r)
28108
+ status: deriveInstanceStatus(r),
28109
+ delivery: deriveFindingDelivery({
28110
+ kind: r.kind,
28111
+ syncedAt: r.synced_at,
28112
+ syncClaimedAt: r.sync_claimed_at,
28113
+ syncFailedAt: r.sync_failed_at,
28114
+ syncFailure: r.sync_failure,
28115
+ outboxOwed: r.outbox_owed
28116
+ })
26996
28117
  };
26997
28118
  }
26998
28119
  function encodeGroupCursor(group) {
@@ -27056,7 +28177,10 @@ var FINDING_ROW_COLUMNS_SQL = `f.id AS id, d.rule_id AS rule_id, d.category AS c
27056
28177
  e.tool_name AS tool_name,
27057
28178
  f.audit_event_id AS event_id, e.root_session_id AS session_id,
27058
28179
  e.event_type AS kind, f.finding_key AS finding_key,
27059
- ${latestResolutionStatusSql("f")} AS latest_status`;
28180
+ ${latestResolutionStatusSql("f")} AS latest_status,
28181
+ e.synced_at AS synced_at, e.sync_claimed_at AS sync_claimed_at,
28182
+ e.sync_failed_at AS sync_failed_at, e.sync_failure AS sync_failure,
28183
+ e.outbox_owed AS outbox_owed`;
27060
28184
  var DAY_MS3 = 864e5;
27061
28185
  var SqliteFindingsRepository = class {
27062
28186
  constructor(db) {
@@ -27301,6 +28425,7 @@ var SqliteFindingsRepository = class {
27301
28425
  providers: query.provider,
27302
28426
  actions: query.action,
27303
28427
  statuses: query.status,
28428
+ deliveries: query.deployment,
27304
28429
  tools: query.tool,
27305
28430
  repo: query.repo,
27306
28431
  file: query.file,
@@ -27368,6 +28493,7 @@ var SqliteFindingsRepository = class {
27368
28493
  providers: query.provider,
27369
28494
  actions: query.action,
27370
28495
  statuses: query.status,
28496
+ deliveries: query.deployment,
27371
28497
  tools: query.tool,
27372
28498
  q: query.q
27373
28499
  };
@@ -27631,7 +28757,9 @@ var SqliteFindingsRepository = class {
27631
28757
  )
27632
28758
  );
27633
28759
  for (const row of grouped) {
27634
- if (row.action_taken in byAction) byAction[row.action_taken] = row.c;
28760
+ if (Object.hasOwn(byAction, row.action_taken)) {
28761
+ byAction[row.action_taken] = row.c;
28762
+ }
27635
28763
  }
27636
28764
  const bySeverity = { critical: 0, high: 0, medium: 0, low: 0 };
27637
28765
  const sevRows = allRows(
@@ -27648,7 +28776,9 @@ var SqliteFindingsRepository = class {
27648
28776
  )
27649
28777
  );
27650
28778
  for (const row of sevRows) {
27651
- if (row.severity in bySeverity) bySeverity[row.severity] = row.c;
28779
+ if (Object.hasOwn(bySeverity, row.severity)) {
28780
+ bySeverity[row.severity] = row.c;
28781
+ }
27652
28782
  }
27653
28783
  const categories = ENFORCEABLE_CATEGORIES;
27654
28784
  const enabledRows = allRows(
@@ -27697,525 +28827,6 @@ function isoDay(ms) {
27697
28827
  return new Date(ms).toISOString().slice(0, 10);
27698
28828
  }
27699
28829
 
27700
- // ../../packages/persistence/src/repositories/history-sync.ts
27701
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
27702
- var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27703
- var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
27704
- var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
27705
- var SKIPPED = -1;
27706
- var ROW_COLUMNS = `id,
27707
- parent_id AS parentId,
27708
- root_session_id AS rootSessionId,
27709
- event_type AS eventType,
27710
- host_id AS hostId,
27711
- harness_id AS harnessId,
27712
- source_project_id AS sourceProjectId,
27713
- started_at AS startedAt,
27714
- ended_at AS endedAt,
27715
- severity,
27716
- priority,
27717
- content,
27718
- content_hash AS contentHash,
27719
- attributes`;
27720
- var SqliteHistorySyncRepository = class {
27721
- constructor(db) {
27722
- this.db = db;
27723
- this.ensureRowStmt = db.prepare(`INSERT OR IGNORE INTO history_sync (id) VALUES (1)`);
27724
- this.sessionsStmt = db.prepare(
27725
- `SELECT COALESCE(root_session_id, id) AS sessionId, MIN(started_at) AS earliest
27726
- FROM audit_events
27727
- WHERE synced_at IS NULL
27728
- AND event_type IN (${TYPE_LIST})
27729
- AND started_at < :before
27730
- GROUP BY sessionId
27731
- ORDER BY earliest
27732
- LIMIT :limit`
27733
- );
27734
- this.rowsStmt = db.prepare(
27735
- `SELECT ${ROW_COLUMNS}
27736
- FROM audit_events
27737
- WHERE synced_at IS NULL
27738
- AND event_type IN (${TYPE_LIST})
27739
- AND started_at < :before
27740
- AND COALESCE(root_session_id, id) = :sessionId
27741
- ORDER BY (event_type = 'session') DESC, started_at
27742
- LIMIT :limit`
27743
- );
27744
- this.captureRowsStmt = db.prepare(
27745
- `SELECT ${ROW_COLUMNS}
27746
- FROM audit_events
27747
- WHERE synced_at IS NULL
27748
- AND sync_claimed_at IS NULL
27749
- AND outbox_owed = 1
27750
- AND event_type IN (${CAPTURE_TYPE_LIST})
27751
- AND started_at < :before
27752
- ORDER BY started_at
27753
- LIMIT :limit`
27754
- );
27755
- this.markOwedStmt = db.prepare(
27756
- `UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
27757
- );
27758
- this.markCaptureBacklogOwedStmt = db.prepare(
27759
- `UPDATE audit_events SET outbox_owed = 1
27760
- WHERE synced_at IS NULL
27761
- AND event_type IN (${CAPTURE_TYPE_LIST})
27762
- AND started_at < :before`
27763
- );
27764
- this.stampStmt = db.prepare(
27765
- `UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
27766
- );
27767
- this.claimRowStmt = db.prepare(
27768
- `UPDATE audit_events SET sync_claimed_at = :at WHERE id = :id AND synced_at IS NULL`
27769
- );
27770
- this.releaseRowStmt = db.prepare(
27771
- `UPDATE audit_events SET sync_claimed_at = NULL WHERE id = :id`
27772
- );
27773
- this.releaseStaleClaimsStmt = db.prepare(
27774
- `UPDATE audit_events SET sync_claimed_at = NULL
27775
- WHERE sync_claimed_at IS NOT NULL AND sync_claimed_at < :staleBefore`
27776
- );
27777
- this.partitionStmt = db.prepare(
27778
- `SELECT
27779
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NULL THEN 1 ELSE 0 END) AS queued,
27780
- SUM(CASE WHEN synced_at IS NULL AND sync_claimed_at IS NOT NULL THEN 1 ELSE 0 END) AS inProgress,
27781
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS synced,
27782
- SUM(CASE WHEN synced_at IS NOT NULL AND synced_at <= 0 THEN 1 ELSE 0 END) AS failed,
27783
- COUNT(*) AS total
27784
- FROM audit_events
27785
- WHERE event_type IN (${TYPE_LIST})`
27786
- );
27787
- this.countsStmt = db.prepare(
27788
- `SELECT
27789
- SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
27790
- SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
27791
- SUM(CASE WHEN synced_at = ${String(SKIPPED)} THEN 1 ELSE 0 END) AS skipped
27792
- FROM audit_events
27793
- WHERE event_type IN (${TYPE_LIST})`
27794
- );
27795
- this.captureSkipCountStmt = db.prepare(
27796
- `SELECT COUNT(*) AS skipped
27797
- FROM audit_events
27798
- WHERE synced_at = ${String(SKIPPED)}
27799
- AND event_type IN (${CAPTURE_TYPE_LIST})`
27800
- );
27801
- this.fingerprintStmt = db.prepare(
27802
- `SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
27803
- FROM history_sync WHERE id = 1`
27804
- );
27805
- this.setFingerprintStmt = db.prepare(
27806
- `UPDATE history_sync
27807
- SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
27808
- WHERE id = 1`
27809
- );
27810
- this.disownCapturesStmt = db.prepare(
27811
- `UPDATE audit_events SET outbox_owed = NULL
27812
- WHERE outbox_owed IS NOT NULL
27813
- AND event_type IN (${CAPTURE_TYPE_LIST})
27814
- AND started_at < :attachedAt`
27815
- );
27816
- this.rearmStmt = db.prepare(
27817
- `UPDATE audit_events SET synced_at = NULL
27818
- WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
27819
- );
27820
- this.claimStmt = db.prepare(
27821
- `UPDATE history_sync
27822
- SET owner_pid = :pid, owner_host = :host, acquired_at = :now, heartbeat_at = :now
27823
- WHERE id = 1
27824
- AND (owner_pid IS NULL
27825
- OR heartbeat_at IS NULL
27826
- OR heartbeat_at < :staleBefore
27827
- OR heartbeat_at > :now)`
27828
- );
27829
- this.heartbeatStmt = db.prepare(
27830
- `UPDATE history_sync SET heartbeat_at = :now WHERE id = 1 AND owner_pid = :pid`
27831
- );
27832
- this.releaseStmt = db.prepare(
27833
- `UPDATE history_sync
27834
- SET owner_pid = NULL, owner_host = NULL, acquired_at = NULL, heartbeat_at = NULL
27835
- WHERE id = 1 AND owner_pid = :pid`
27836
- );
27837
- this.closeWindowStmt = db.prepare(
27838
- `UPDATE audit_events SET synced_at = :at
27839
- WHERE synced_at IS NULL
27840
- AND event_type IN (${TYPE_LIST})
27841
- AND started_at >= :attachedAt`
27842
- );
27843
- this.releaseBoundaryStmt = db.prepare(
27844
- `UPDATE history_sync SET backlog_before = NULL WHERE id = 1`
27845
- );
27846
- this.freezeBoundaryStmt = db.prepare(
27847
- `UPDATE history_sync SET backlog_before = :backlogBefore WHERE id = 1`
27848
- );
27849
- this.leaseStmt = db.prepare(
27850
- `SELECT owner_pid AS ownerPid, owner_host AS ownerHost,
27851
- acquired_at AS acquiredAt, heartbeat_at AS heartbeatAt
27852
- FROM history_sync WHERE id = 1`
27853
- );
27854
- this.inspectionsStmt = db.prepare(
27855
- `SELECT d.rule_id AS ruleId,
27856
- d.name AS ruleName,
27857
- d.version AS ruleVersion,
27858
- d.category AS category,
27859
- d.severity AS severity,
27860
- f.span_start AS spanStart,
27861
- f.span_end AS spanEnd,
27862
- f.masked_match AS maskedMatch,
27863
- f.action_taken AS actionTaken,
27864
- f.confidence AS confidence
27865
- FROM inspection_findings f
27866
- JOIN inspection_definitions d ON d.id = f.inspection_definition_id
27867
- WHERE f.audit_event_id = :auditEventId
27868
- ORDER BY f.span_start, f.id`
27869
- );
27870
- }
27871
- db;
27872
- ensureRowStmt;
27873
- sessionsStmt;
27874
- rowsStmt;
27875
- stampStmt;
27876
- countsStmt;
27877
- fingerprintStmt;
27878
- setFingerprintStmt;
27879
- rearmStmt;
27880
- claimStmt;
27881
- heartbeatStmt;
27882
- releaseStmt;
27883
- leaseStmt;
27884
- inspectionsStmt;
27885
- closeWindowStmt;
27886
- releaseBoundaryStmt;
27887
- freezeBoundaryStmt;
27888
- captureRowsStmt;
27889
- markOwedStmt;
27890
- markCaptureBacklogOwedStmt;
27891
- captureSkipCountStmt;
27892
- disownCapturesStmt;
27893
- partitionStmt;
27894
- claimRowStmt;
27895
- releaseRowStmt;
27896
- releaseStaleClaimsStmt;
27897
- /**
27898
- * The masked detections recorded against one tool call.
27899
- *
27900
- * These travel with the event because a tool call's target is not
27901
- * re-inspectable from the event alone — unlike a capture, where the text
27902
- * itself is re-scannable. What crosses is the masked match and the rule that
27903
- * produced it, never the value.
27904
- */
27905
- inspectionsFor(auditEventId) {
27906
- return allRows(this.inspectionsStmt, { auditEventId });
27907
- }
27908
- /**
27909
- * Sessions with structural rows still to send, oldest first.
27910
- *
27911
- * BOUNDED BY THE BACKLOG BOUNDARY, which is the whole correctness of this
27912
- * read. Anything recorded after the machine attached is the live forward
27913
- * path's to deliver; this drain exists for what was recorded before it, and a
27914
- * row both paths send is at best a duplicate request and at worst — for a
27915
- * session root — an overwrite of the inventory ids the live path resolved.
27916
- */
27917
- pendingSessions(limit, before) {
27918
- return allRows(this.sessionsStmt, { limit, before }).map(
27919
- (r) => r.sessionId
27920
- );
27921
- }
27922
- /** One session's undelivered structural rows within the backlog, root first. */
27923
- pendingRows(sessionId, limit, before) {
27924
- return allRows(this.rowsStmt, { sessionId, limit, before });
27925
- }
27926
- /**
27927
- * Captures this machine still owes the deployment, oldest first.
27928
- *
27929
- * Selected by the `outbox_owed` marker the attached forward path writes, not
27930
- * by a time window — see captureRowsStmt for why a window could not express
27931
- * this. `before` is the grace window that leaves a just-recorded capture to
27932
- * the live path.
27933
- */
27934
- pendingCaptureRows(limit, before) {
27935
- return allRows(this.captureRowsStmt, { limit, before });
27936
- }
27937
- /**
27938
- * Record that a capture is OWED to the deployment.
27939
- *
27940
- * Written by the attached forward path when a live send did not confirm
27941
- * delivery, and read by the drain as the whole of its eligibility test. It is
27942
- * a fact rather than an inference: the machine was attached, the send did not
27943
- * land, so the row is owed — which no time window can state, because the same
27944
- * window that holds the rows a past attachment left owed also holds every
27945
- * capture recorded while the machine was DETACHED, and those were never
27946
- * offered to anyone.
27947
- *
27948
- * Idempotent, and never un-set: `markSynced` settling the row is what takes it
27949
- * out of the drain's read.
27950
- */
27951
- markCaptureOwed(id) {
27952
- this.markOwedStmt.run({ id });
27953
- }
27954
- /**
27955
- * Mark every capture already on disk as owed, as of `before`.
27956
- *
27957
- * The consent-time backfill, called once from `aka attach` when a human
27958
- * grants existing-history consent — never from an ongoing drain pass, and
27959
- * never inferred from a boundary that could later move. `before` is the
27960
- * caller's own "now" at the moment consent was granted, so what this marks
27961
- * is exactly the backlog the consent prompt already counted, not whatever a
27962
- * later re-attach or key rotation might widen it to.
27963
- *
27964
- * Returns how many rows matched, for the caller to log or test against. Not a
27965
- * count of NEWLY marked rows — a row still unsynced from an earlier call
27966
- * matches again and is counted again, the same as `UPDATE`'s own `changes`.
27967
- */
27968
- markCaptureBacklogOwed(before) {
27969
- return Number(this.markCaptureBacklogOwedStmt.run({ before }).changes);
27970
- }
27971
- /** Record delivery. Called only AFTER the far side has accepted the rows. */
27972
- markSynced(ids, atMs) {
27973
- this.stampAll(ids, atMs);
27974
- }
27975
- /**
27976
- * Record that a row will never be sent.
27977
- *
27978
- * Reserved for a local defect — a row that cannot be rebuilt into a valid
27979
- * payload. A row that merely failed to reach the deployment stays NULL, so it
27980
- * is retried; marking those would turn one outage into permanent data loss.
27981
- */
27982
- markSkipped(ids) {
27983
- this.stampAll(ids, SKIPPED);
27984
- }
27985
- eachInTransaction(ids, run) {
27986
- if (ids.length === 0) return;
27987
- withTransaction(
27988
- this.db,
27989
- () => {
27990
- for (const id of ids) run(id);
27991
- },
27992
- "IMMEDIATE"
27993
- );
27994
- }
27995
- stampAll(ids, value) {
27996
- if (ids.length === 0) return;
27997
- withTransaction(
27998
- this.db,
27999
- () => {
28000
- for (const id of ids) this.stampStmt.run({ at: value, id });
28001
- },
28002
- "IMMEDIATE"
28003
- );
28004
- }
28005
- /**
28006
- * Claim rows as in-flight.
28007
- *
28008
- * Advisory in exactly the sense the lease is: it records that a send is in
28009
- * progress so a surface can say so, and a lost claim costs a row showing as
28010
- * queued while it is actually being sent. It is not exclusion — the far side
28011
- * settles a duplicate on the row id.
28012
- */
28013
- claimRows(ids, atMs) {
28014
- this.eachInTransaction(ids, (id) => this.claimRowStmt.run({ at: atMs, id }));
28015
- }
28016
- /** Give back a claim without settling — the send failed, the row is queued again. */
28017
- releaseRows(ids) {
28018
- this.eachInTransaction(ids, (id) => this.releaseRowStmt.run({ id }));
28019
- }
28020
- /**
28021
- * Clear claims older than `staleBefore`, and report how many were cleared.
28022
- *
28023
- * A process killed between claiming and settling leaves rows claimed with
28024
- * nothing left to settle them. Without this they read as "sending" for ever.
28025
- */
28026
- releaseStaleClaims(staleBefore) {
28027
- return Number(this.releaseStaleClaimsStmt.run({ staleBefore }).changes);
28028
- }
28029
- /**
28030
- * Every tracked row in exactly one delivery state.
28031
- *
28032
- * Takes no boundary on purpose. The boundary answers "what should the drain
28033
- * pick up now", which is a different question from "what state is this row
28034
- * in" — and a machine that has never attached has no boundary to pass, so
28035
- * requiring one would force a caller to invent one and report the whole store
28036
- * as queued.
28037
- */
28038
- partition() {
28039
- const row = getRow(this.partitionStmt, {});
28040
- return {
28041
- queued: row?.queued ?? 0,
28042
- inProgress: row?.inProgress ?? 0,
28043
- synced: row?.synced ?? 0,
28044
- failed: row?.failed ?? 0,
28045
- total: row?.total ?? 0
28046
- };
28047
- }
28048
- /** `pending` counts only what is inside the backlog; sent and skipped are totals. */
28049
- counts(before) {
28050
- const row = getRow(
28051
- this.countsStmt,
28052
- { before }
28053
- );
28054
- const captures = getRow(this.captureSkipCountStmt);
28055
- return {
28056
- pending: row?.pending ?? 0,
28057
- sent: row?.sent ?? 0,
28058
- skipped: row?.skipped ?? 0,
28059
- capturesSkipped: captures?.skipped ?? 0
28060
- };
28061
- }
28062
- /**
28063
- * The deployment the current stamps were made against, and where its backlog
28064
- * ends.
28065
- *
28066
- * READ-ONLY. An absent row reads as an absent deployment, which is what a
28067
- * machine that has never drained is — and every writer below seeds the row
28068
- * before it needs one, so nothing depends on this creating it. Keeping the
28069
- * write off the gate path matters because the gate runs on every pass while a
28070
- * write has to take the database's write lock.
28071
- */
28072
- deployment() {
28073
- const row = getRow(
28074
- this.fingerprintStmt
28075
- );
28076
- return {
28077
- fingerprint: row?.fingerprint ?? void 0,
28078
- backlogBefore: row?.backlogBefore ?? void 0
28079
- };
28080
- }
28081
- /**
28082
- * Point the ledger at a different deployment, discarding what it recorded
28083
- * about the previous one.
28084
- *
28085
- * Delivery is a fact about ONE recipient: rows sent to the deployment a
28086
- * machine has just left are undelivered as far as the new one is concerned.
28087
- * All four in one transaction, so a crash between them cannot leave stamps
28088
- * attributed to the wrong deployment, a boundary that belongs to another, or
28089
- * a disown with no re-mark to follow it.
28090
- *
28091
- * The boundary is written HERE and only here, which is what freezes it: a
28092
- * re-attach to the SAME deployment (a key rotation) leaves the fingerprint
28093
- * unchanged, so this never runs and the backlog does not widen back over rows
28094
- * the live path has since delivered.
28095
- *
28096
- * `backfillCapturesBefore` is the caller's OWN "now" at the instant a human
28097
- * granted existing-history consent for the deployment this call is arming —
28098
- * a DIFFERENT instant from `backlogBefore`: the re-mark boundary is the GRANT
28099
- * instant, `backlogBefore` is the ATTACH instant, and the two can be far
28100
- * apart. Passed only when that grant is valid, since this method has no way
28101
- * to check consent itself and must not mark a row owed for a machine that
28102
- * never agreed to it. Applied AFTER the disown above, in the SAME
28103
- * transaction: what the disown clears is every marker below `backlogBefore`,
28104
- * which includes this deployment's OWN pre-attach rows — `aka attach` calls
28105
- * `seedCaptureBacklogOwed` at the attach instant, so every row it marks sits
28106
- * on the cleared side of that bound — and the re-mark in the same
28107
- * transaction is what puts those rows back. A crash between the two cannot
28108
- * strand the ledger disowned with nothing re-marked — the transaction either
28109
- * lands whole or not at all, and a fingerprint mismatch that has not yet
28110
- * committed re-enters this method on the very next pass. Omit it (the
28111
- * structural-only tests do) to exercise the disown in isolation.
28112
- *
28113
- * The disown is bounded by `backlogBefore`, which is what keeps it from
28114
- * touching a marker the NEW deployment's OWN live path has already set: B's
28115
- * live path can mark a capture owed from the moment `aka attach` writes the
28116
- * descriptor, before the drain's first pass ever reaches this method, and
28117
- * such a row sits at or after the bound rather than below it. What keeps the
28118
- * disown from eating THIS SAME CALL's own re-mark is the order, not the
28119
- * bound — disown runs first, re-mark second, both inside the one
28120
- * transaction above.
28121
- */
28122
- rearmFor(fingerprint, backlogBefore, backfillCapturesBefore) {
28123
- this.ensureRowStmt.run();
28124
- withTransaction(
28125
- this.db,
28126
- () => {
28127
- const previous = getRow(this.fingerprintStmt)?.fingerprint;
28128
- this.rearmStmt.run();
28129
- if (previous !== null && previous !== void 0 && previous !== fingerprint) {
28130
- this.disownCapturesStmt.run({ attachedAt: backlogBefore });
28131
- }
28132
- if (backfillCapturesBefore !== void 0) {
28133
- this.markCaptureBacklogOwedStmt.run({ before: backfillCapturesBefore });
28134
- }
28135
- this.setFingerprintStmt.run({ fingerprint, backlogBefore });
28136
- },
28137
- "IMMEDIATE"
28138
- );
28139
- }
28140
- /**
28141
- * End the attached period: hand its rows to the live path, and release the
28142
- * boundary so the next attachment can freeze a new one.
28143
- *
28144
- * WITHOUT THIS, a detach and a re-attach to the same deployment leave a window
28145
- * nothing delivers. The fingerprint is unchanged, so the boundary is never
28146
- * re-frozen and stays at the FIRST attachment — while nothing forwards at all
28147
- * during the detached period, because the machine is not attached. Rows
28148
- * recorded in that window sit after the boundary and before the re-attach, so
28149
- * neither path takes them, and the pending count reports none outstanding.
28150
- *
28151
- * Stamping the attached window is not a claim that every one of those rows
28152
- * reached the deployment — the live path drops on failure and says so
28153
- * elsewhere. It records that they were ITS to deliver, which is exactly the
28154
- * status quo: they sit outside the frozen boundary today and are equally never
28155
- * re-sent. Making it explicit is what lets the boundary move.
28156
- *
28157
- * ONE TRANSACTION, so a crash cannot release the boundary while leaving the
28158
- * window unstamped — that half-state would re-send the whole attached period
28159
- * on the next attach, which is the failure the boundary exists to prevent.
28160
- */
28161
- closeAttachedWindow(attachedAtMs, atMs) {
28162
- this.ensureRowStmt.run();
28163
- withTransaction(
28164
- this.db,
28165
- () => {
28166
- const row = getRow(this.fingerprintStmt);
28167
- const from = row?.backlogBefore ?? attachedAtMs;
28168
- this.closeWindowStmt.run({ at: atMs, attachedAt: from });
28169
- this.releaseBoundaryStmt.run();
28170
- },
28171
- "IMMEDIATE"
28172
- );
28173
- }
28174
- /**
28175
- * Freeze a boundary for the deployment already on file, KEEPING the stamps.
28176
- *
28177
- * The re-attach half of the above. Distinct from `rearmFor`, which is for a
28178
- * different deployment and therefore discards what was delivered to the old
28179
- * one: here the recipient is the same, so everything already sent to it stays
28180
- * sent.
28181
- */
28182
- freezeBoundary(backlogBefore) {
28183
- this.ensureRowStmt.run();
28184
- this.freezeBoundaryStmt.run({ backlogBefore });
28185
- }
28186
- /** Take the claim, or report that someone live already holds it. */
28187
- claim(pid, host, nowMs, staleAfterMs) {
28188
- this.ensureRowStmt.run();
28189
- let taken = false;
28190
- withTransaction(
28191
- this.db,
28192
- () => {
28193
- const result = this.claimStmt.run({
28194
- pid,
28195
- host,
28196
- now: nowMs,
28197
- staleBefore: nowMs - staleAfterMs
28198
- });
28199
- taken = result.changes === 1;
28200
- },
28201
- "IMMEDIATE"
28202
- );
28203
- return taken;
28204
- }
28205
- /** Say the holder is still alive. A no-op once the claim has moved on. */
28206
- heartbeat(pid, nowMs) {
28207
- this.heartbeatStmt.run({ now: nowMs, pid });
28208
- }
28209
- /** Give the claim up. Scoped to this holder, so a taken-over claim is left be. */
28210
- release(pid) {
28211
- this.releaseStmt.run({ pid });
28212
- }
28213
- /** Who holds the claim, if anyone. Read-only, for the same reason as above. */
28214
- lease() {
28215
- return getRow(this.leaseStmt);
28216
- }
28217
- };
28218
-
28219
28830
  // ../../packages/persistence/src/repositories/inspection-definitions.ts
28220
28831
  var SqliteInspectionDefinitionsRepository = class {
28221
28832
  constructor(db) {
@@ -28446,6 +29057,7 @@ function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ n
28446
29057
  if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
28447
29058
  if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
28448
29059
  if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
29060
+ if (values.bodyRetention !== void 0) merged.bodyRetention = values.bodyRetention;
28449
29061
  if (values.vaultConsent !== void 0) {
28450
29062
  merged.vaultConsent = values.vaultConsent ? (
28451
29063
  // Keep an existing valid grant so its acknowledgedAt survives; mint one
@@ -30953,7 +31565,7 @@ var SqliteSecurityRepository = class {
30953
31565
  ELSE 0
30954
31566
  END) AS open_at_rest
30955
31567
  FROM inspection_findings f
30956
- JOIN audit_events e ON e.id = f.audit_event_id
31568
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
30957
31569
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
30958
31570
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
30959
31571
  ON latest.finding_key = f.finding_key
@@ -31179,7 +31791,7 @@ var SqliteSecurityRepository = class {
31179
31791
  this.db.prepare(
31180
31792
  `SELECT e.repo AS repo, count(*) AS c
31181
31793
  FROM inspection_findings f
31182
- JOIN audit_events e ON e.id = f.audit_event_id
31794
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31183
31795
  WHERE e.started_at >= :from AND e.started_at < :to
31184
31796
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
31185
31797
  AND e.repo IS NOT NULL
@@ -31303,7 +31915,7 @@ var SqliteSecurityRepository = class {
31303
31915
  d.severity AS severity,
31304
31916
  COUNT(*) AS count
31305
31917
  FROM inspection_findings f
31306
- JOIN audit_events e ON e.id = f.audit_event_id
31918
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31307
31919
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31308
31920
  LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
31309
31921
  ON latest.finding_key = f.finding_key
@@ -31338,7 +31950,7 @@ var SqliteSecurityRepository = class {
31338
31950
  `SELECT e.started_at AS occurred_at, d.severity AS severity, f.action_taken AS action_taken,
31339
31951
  d.rule_id AS rule_id, d.category AS category
31340
31952
  FROM inspection_findings f
31341
- JOIN audit_events e ON e.id = f.audit_event_id
31953
+ JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
31342
31954
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
31343
31955
  WHERE e.started_at >= :from AND e.started_at < :to
31344
31956
  AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
@@ -32179,6 +32791,7 @@ function openWithPragmas(file2) {
32179
32791
  db.exec("PRAGMA journal_mode = WAL");
32180
32792
  db.exec("PRAGMA busy_timeout = 2000");
32181
32793
  db.exec("PRAGMA foreign_keys = ON");
32794
+ registerSqlFunctions(db);
32182
32795
  } catch (err) {
32183
32796
  closeQuietly(db);
32184
32797
  throw err;
@@ -32208,7 +32821,7 @@ function backupLegacyStore(db, file2) {
32208
32821
  discardStore(file2, backup);
32209
32822
  return backup;
32210
32823
  }
32211
- function openAndInitialize(file2, base) {
32824
+ function openAndInitialize(file2, base, skipTags) {
32212
32825
  let db = openWithPragmas(file2);
32213
32826
  try {
32214
32827
  if (isForeignSqliteLineage(db)) {
@@ -32218,7 +32831,7 @@ function openAndInitialize(file2, base) {
32218
32831
  `Detected an older, incompatible (tenant-bearing) ${DB_FILENAME}; backed it up to ${backup} and created a fresh store.`
32219
32832
  );
32220
32833
  }
32221
- applyMigrations(db, file2);
32834
+ applyMigrations(db, file2, { skipTags });
32222
32835
  tightenPerms(file2);
32223
32836
  const policies = new SqlitePoliciesRepository(db);
32224
32837
  const installedPacks = new SqliteInstalledPacksRepository(db, base);
@@ -32233,6 +32846,7 @@ function openAndInitialize(file2, base) {
32233
32846
  exceptions: new SqliteExceptionsRepository(db),
32234
32847
  resolutions: new SqliteResolutionsRepository(db),
32235
32848
  ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
32849
+ bodyRetention: new SqliteBodyRetentionRepository(db),
32236
32850
  security: new SqliteSecurityRepository(db),
32237
32851
  detections: new SqliteDetectionsRepository(db),
32238
32852
  shares: new SqliteSharesRepository(db),
@@ -32255,7 +32869,8 @@ function openAndInitialize(file2, base) {
32255
32869
  throw err;
32256
32870
  }
32257
32871
  }
32258
- function openLocalDatabase(dir) {
32872
+ var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
32873
+ function openLocalDatabase(dir, options = {}) {
32259
32874
  ensureDataDirSync(dir);
32260
32875
  const file2 = join7(dir, DB_FILENAME);
32261
32876
  reapStalePartials(file2);
@@ -32267,6 +32882,7 @@ function openLocalDatabase(dir) {
32267
32882
  installedPacks,
32268
32883
  scanLedger,
32269
32884
  historySync,
32885
+ bodyRetention,
32270
32886
  secretVault,
32271
32887
  exceptions,
32272
32888
  resolutions,
@@ -32290,7 +32906,8 @@ function openLocalDatabase(dir) {
32290
32906
  // `dir` is always `<base>/data` — every caller resolves it through
32291
32907
  // `dataDir()` — so its parent is the `~/.aka` base the layout splits into
32292
32908
  // settings/ and data/, and the pack-policy floor needs both halves.
32293
- dirname2(dir)
32909
+ dirname2(dir),
32910
+ options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
32294
32911
  );
32295
32912
  function captureRowId(event) {
32296
32913
  return captureId(
@@ -32483,6 +33100,7 @@ function openLocalDatabase(dir) {
32483
33100
  installedPacks,
32484
33101
  scanLedger,
32485
33102
  historySync,
33103
+ bodyRetention,
32486
33104
  secretVault,
32487
33105
  exceptions,
32488
33106
  resolutions,
@@ -32523,8 +33141,35 @@ function openLocalDatabase(dir) {
32523
33141
 
32524
33142
  // ../../packages/persistence/src/egress-wire.ts
32525
33143
  import { createHash as createHash3 } from "crypto";
33144
+ var PROJECT_KEY_DIGEST_VERSION = "v2";
33145
+ var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
33146
+ var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
33147
+ var FILE_URL = /^file:\/\//i;
33148
+ var SCHEME_FORM = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?(\/.*)?$/i;
33149
+ var SLASH = "/".charCodeAt(0);
33150
+ var GIT_SUFFIX = ".git";
33151
+ function trimSlashes(path) {
33152
+ let start = 0;
33153
+ let end = path.length;
33154
+ while (start < end && path.charCodeAt(start) === SLASH) start += 1;
33155
+ while (end > start && path.charCodeAt(end - 1) === SLASH) end -= 1;
33156
+ return path.slice(start, end);
33157
+ }
33158
+ function canonicalGitUrl(url2) {
33159
+ const trimmed = url2.trim();
33160
+ if (DOS_DRIVE.test(trimmed) || FILE_URL.test(trimmed)) return trimmed;
33161
+ const scheme = SCHEME_FORM.exec(trimmed);
33162
+ const scp = scheme === null ? SCP_FORM.exec(trimmed) : null;
33163
+ const host = (scheme?.[1] ?? scp?.[1])?.toLowerCase();
33164
+ if (host === void 0) return trimmed;
33165
+ const path = (scheme === null ? scp?.[2] : scheme[2]) ?? "";
33166
+ const bare = trimSlashes(path);
33167
+ const cleaned = bare.endsWith(GIT_SUFFIX) ? bare.slice(0, -GIT_SUFFIX.length) : bare;
33168
+ return cleaned === "" ? host : `${host}/${cleaned}`;
33169
+ }
32526
33170
  function hashProjectKey(projectKey) {
32527
- return createHash3("sha256").update(projectKey, "utf8").digest("hex");
33171
+ const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
33172
+ return createHash3("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
32528
33173
  }
32529
33174
  function toIngestHit(hit) {
32530
33175
  return {
@@ -32711,18 +33356,50 @@ function fingerprintValue(key, raw) {
32711
33356
  return createHmac("sha256", key.material).update(raw, "utf8").digest("hex");
32712
33357
  }
32713
33358
 
33359
+ // ../../packages/persistence/src/forward-health.ts
33360
+ import { readFileSync as readFileSync7 } from "fs";
33361
+ import { join as join9 } from "path";
33362
+ var FAILURES = /* @__PURE__ */ new Set([
33363
+ "unauthorized",
33364
+ "forbidden",
33365
+ "unreachable"
33366
+ ]);
33367
+ var BREAKER_COOLDOWN_MS = 3e4;
33368
+ function parseForwardHealth(raw, nowMs) {
33369
+ try {
33370
+ const parsed2 = JSON.parse(raw);
33371
+ if (typeof parsed2 !== "object" || parsed2 === null) return null;
33372
+ const record2 = parsed2;
33373
+ const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
33374
+ const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
33375
+ const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
33376
+ return { consecutiveFailures: failures, openedAtMs, lastFailure };
33377
+ } catch {
33378
+ return null;
33379
+ }
33380
+ }
33381
+ function isForwardPaused(health, nowMs) {
33382
+ const openedAtMs = health?.openedAtMs ?? null;
33383
+ if (openedAtMs === null) return false;
33384
+ return nowMs - openedAtMs < BREAKER_COOLDOWN_MS;
33385
+ }
33386
+
32714
33387
  // ../../packages/persistence/src/history-backfill.ts
32715
33388
  import { existsSync as existsSync4 } from "fs";
32716
- import { join as join9 } from "path";
33389
+ import { join as join10 } from "path";
32717
33390
 
32718
33391
  // ../../packages/persistence/src/history-preview.ts
32719
33392
  import { existsSync as existsSync5 } from "fs";
32720
- import { join as join10 } from "path";
33393
+ import { join as join11 } from "path";
32721
33394
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
32722
33395
 
33396
+ // ../../packages/persistence/src/history-sync-state.ts
33397
+ import { readFileSync as readFileSync8 } from "fs";
33398
+ import { join as join12 } from "path";
33399
+
32723
33400
  // ../../packages/persistence/src/store-symlinks.ts
32724
33401
  import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
32725
- import { dirname as dirname3, join as join11, resolve } from "path";
33402
+ import { dirname as dirname3, join as join13, resolve } from "path";
32726
33403
  var STORE_DB = "the store database (including the prompt corpus)";
32727
33404
  var STORE_SETTINGS = "your settings file";
32728
33405
  function storeContents(home) {
@@ -32731,7 +33408,7 @@ function storeContents(home) {
32731
33408
  [settingsDir(home), STORE_SETTINGS],
32732
33409
  [dataDir(home), STORE_DB],
32733
33410
  [keysDir(home), "the vault key"],
32734
- [join11(settingsDir(home), "settings.json"), STORE_SETTINGS],
33411
+ [join13(settingsDir(home), "settings.json"), STORE_SETTINGS],
32735
33412
  [dbPath(home), STORE_DB]
32736
33413
  ]);
32737
33414
  }
@@ -32882,8 +33559,8 @@ function formatPointer(category, keyVersion, pointerId, tag) {
32882
33559
  // ../../packages/persistence/src/vault/key-provider.ts
32883
33560
  import { execFileSync } from "child_process";
32884
33561
  import { randomBytes as randomBytes2 } from "crypto";
32885
- import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
32886
- import { join as join12 } from "path";
33562
+ import { chmodSync as chmodSync3, readFileSync as readFileSync9, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
33563
+ import { join as join14 } from "path";
32887
33564
  var VAULT_OCCUPANT_REASON = {
32888
33565
  symlink: "the path is a symlink; remove it so a keyring can be created",
32889
33566
  gone: "the path was occupied but holds no keyring (removed while it was being created)",
@@ -32982,7 +33659,7 @@ function claimRotationLock(lock, owner) {
32982
33659
  throw asError(err);
32983
33660
  }
32984
33661
  try {
32985
- writeFileSync3(join12(lock, LOCK_OWNER_FILE), `${owner}
33662
+ writeFileSync3(join14(lock, LOCK_OWNER_FILE), `${owner}
32986
33663
  `, { mode: DATA_FILE_MODE });
32987
33664
  return true;
32988
33665
  } catch (err) {
@@ -32991,7 +33668,7 @@ function claimRotationLock(lock, owner) {
32991
33668
  }
32992
33669
  }
32993
33670
  function acquireRotationLock(keysDir2) {
32994
- const lock = join12(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
33671
+ const lock = join14(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
32995
33672
  const owner = randomBytes2(16).toString("hex");
32996
33673
  if (claimRotationLock(lock, owner)) return { lock, owner };
32997
33674
  let held;
@@ -33018,7 +33695,7 @@ function acquireRotationLock(keysDir2) {
33018
33695
  }
33019
33696
  function releaseRotationLock(lease) {
33020
33697
  try {
33021
- if (readFileSync7(join12(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
33698
+ if (readFileSync9(join14(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
33022
33699
  } catch {
33023
33700
  return;
33024
33701
  }
@@ -33039,7 +33716,7 @@ var FileKeyProvider = class {
33039
33716
  this.#keysDir = keysDir2;
33040
33717
  }
33041
33718
  get filePath() {
33042
- return join12(this.#keysDir, VAULT_KEY_FILENAME);
33719
+ return join14(this.#keysDir, VAULT_KEY_FILENAME);
33043
33720
  }
33044
33721
  loadOrCreate() {
33045
33722
  return asAsync(() => {
@@ -33069,7 +33746,7 @@ var FileKeyProvider = class {
33069
33746
  #read() {
33070
33747
  let raw;
33071
33748
  try {
33072
- raw = readFileSync7(this.filePath, "utf8");
33749
+ raw = readFileSync9(this.filePath, "utf8");
33073
33750
  } catch (err) {
33074
33751
  if (err.code === "ENOENT") return null;
33075
33752
  throw err instanceof Error ? err : new Error(String(err));
@@ -33705,11 +34382,11 @@ var SecretVault = class {
33705
34382
 
33706
34383
  // ../../packages/persistence/src/warn-era-cap.ts
33707
34384
  import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
33708
- import { join as join13 } from "path";
34385
+ import { join as join15 } from "path";
33709
34386
  var MARKER = "warn-era-capped";
33710
34387
  function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
33711
34388
  if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
33712
- const marker = join13(dataDir2, MARKER);
34389
+ const marker = join15(dataDir2, MARKER);
33713
34390
  if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
33714
34391
  const capped = db.policies.capCategoryActions();
33715
34392
  writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
@@ -33900,10 +34577,10 @@ function parsed(schema, body, route) {
33900
34577
  }
33901
34578
  function withoutTrailingSlashes(endpoint) {
33902
34579
  let end = endpoint.length;
33903
- while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
34580
+ while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
33904
34581
  return endpoint.slice(0, end);
33905
34582
  }
33906
- var SLASH = "/".charCodeAt(0);
34583
+ var SLASH2 = "/".charCodeAt(0);
33907
34584
  function createRemoteClient(options) {
33908
34585
  const base = withoutTrailingSlashes(options.endpoint);
33909
34586
  const url2 = (route) => `${base}${route}`;
@@ -34085,11 +34762,11 @@ function withTimeout(promise2, ms) {
34085
34762
  }
34086
34763
 
34087
34764
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
34088
- import { readFileSync as readFileSync8 } from "fs";
34089
- import { join as join14 } from "path";
34765
+ import { readFileSync as readFileSync10 } from "fs";
34766
+ import { join as join16 } from "path";
34090
34767
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
34091
34768
  function forwardDropsPath(dataDir2) {
34092
- return join14(dataDir2, FORWARD_DROPS_FILENAME);
34769
+ return join16(dataDir2, FORWARD_DROPS_FILENAME);
34093
34770
  }
34094
34771
  function recordForwardDrops(dataDir2, count, nowMs) {
34095
34772
  if (count <= 0) return;
@@ -34107,7 +34784,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
34107
34784
  }
34108
34785
  function readForwardDrops(dataDir2) {
34109
34786
  try {
34110
- const parsed2 = JSON.parse(readFileSync8(forwardDropsPath(dataDir2), "utf8"));
34787
+ const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
34111
34788
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
34112
34789
  const record2 = parsed2;
34113
34790
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -34125,13 +34802,12 @@ function readForwardDrops(dataDir2) {
34125
34802
 
34126
34803
  // ../../packages/plugin-runtime/src/attached/forward-policy.ts
34127
34804
  import { randomUUID as randomUUID15 } from "crypto";
34128
- import { readFileSync as readFileSync15 } from "fs";
34129
34805
  import { readFile, rename, writeFile } from "fs/promises";
34130
- import { join as join24 } from "path";
34806
+ import { join as join26 } from "path";
34131
34807
 
34132
34808
  // ../../packages/plugin-sdk/src/config.ts
34133
34809
  import { existsSync as existsSync8 } from "fs";
34134
- import { join as join15 } from "path";
34810
+ import { join as join17 } from "path";
34135
34811
 
34136
34812
  // ../../packages/plugin-sdk/src/provider-env.ts
34137
34813
  var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
@@ -34185,7 +34861,7 @@ function resolveProvider() {
34185
34861
  function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
34186
34862
  try {
34187
34863
  ensureLayoutDirSync(base);
34188
- const settingsFile = join15(settingsDir(base), "settings.json");
34864
+ const settingsFile = join17(settingsDir(base), "settings.json");
34189
34865
  if (existsSync8(settingsFile)) tightenFile(settingsFile);
34190
34866
  } catch {
34191
34867
  }
@@ -34209,9 +34885,9 @@ function resolveProviderSafe(resolveProviderFn) {
34209
34885
  }
34210
34886
 
34211
34887
  // ../../packages/plugin-sdk/src/config-inventory.ts
34212
- import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
34888
+ import { readdirSync as readdirSync2, readFileSync as readFileSync12, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
34213
34889
  import { homedir as homedir2 } from "os";
34214
- import { basename as basename3, join as join17 } from "path";
34890
+ import { basename as basename3, join as join19 } from "path";
34215
34891
 
34216
34892
  // ../../packages/detections/src/egress/registry.ts
34217
34893
  var EXTRACTOR_VERSION = "1";
@@ -37303,8 +37979,8 @@ function uniqueRuleIds(findings) {
37303
37979
  }
37304
37980
 
37305
37981
  // ../../packages/plugin-sdk/src/repo.ts
37306
- import { existsSync as existsSync9, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
37307
- import { basename as basename2, dirname as dirname4, isAbsolute, join as join16, sep as sep2 } from "path";
37982
+ import { existsSync as existsSync9, readFileSync as readFileSync11, statSync as statSync6 } from "fs";
37983
+ import { basename as basename2, dirname as dirname4, isAbsolute, join as join18, sep as sep2 } from "path";
37308
37984
  function resolveRepo(cwd) {
37309
37985
  try {
37310
37986
  const root = findGitRoot(cwd);
@@ -37319,36 +37995,36 @@ function resolveRepo(cwd) {
37319
37995
  function findGitRoot(start) {
37320
37996
  let dir = start;
37321
37997
  for (; ; ) {
37322
- if (existsSync9(join16(dir, ".git"))) return dir;
37998
+ if (existsSync9(join18(dir, ".git"))) return dir;
37323
37999
  const parent = dirname4(dir);
37324
38000
  if (parent === dir) return void 0;
37325
38001
  dir = parent;
37326
38002
  }
37327
38003
  }
37328
38004
  function resolveGitContext(root) {
37329
- const dotGit = join16(root, ".git");
38005
+ const dotGit = join18(root, ".git");
37330
38006
  try {
37331
38007
  if (statSync6(dotGit).isDirectory()) {
37332
- return { configPath: join16(dotGit, "config"), headRoot: root };
38008
+ return { configPath: join18(dotGit, "config"), headRoot: root };
37333
38009
  }
37334
38010
  } catch {
37335
38011
  return void 0;
37336
38012
  }
37337
38013
  const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
37338
38014
  if (!target) return void 0;
37339
- const gitdir = isAbsolute(target) ? target : join16(root, target);
37340
- if (existsSync9(join16(gitdir, "config"))) {
37341
- return { configPath: join16(gitdir, "config"), headRoot: root };
38015
+ const gitdir = isAbsolute(target) ? target : join18(root, target);
38016
+ if (existsSync9(join18(gitdir, "config"))) {
38017
+ return { configPath: join18(gitdir, "config"), headRoot: root };
37342
38018
  }
37343
- const commonRaw = safeRead(join16(gitdir, "commondir"))?.trim();
38019
+ const commonRaw = safeRead(join18(gitdir, "commondir"))?.trim();
37344
38020
  if (!commonRaw) return void 0;
37345
- const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join16(gitdir, commonRaw);
38021
+ const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join18(gitdir, commonRaw);
37346
38022
  const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
37347
- return { configPath: join16(commonGitDir, "config"), headRoot };
38023
+ return { configPath: join18(commonGitDir, "config"), headRoot };
37348
38024
  }
37349
38025
  function safeRead(path) {
37350
38026
  try {
37351
- return readFileSync9(path, "utf8");
38027
+ return readFileSync11(path, "utf8");
37352
38028
  } catch {
37353
38029
  return void 0;
37354
38030
  }
@@ -37892,8 +38568,8 @@ function createGuardedScanner(partition, gateway, opts) {
37892
38568
  }
37893
38569
 
37894
38570
  // ../../packages/plugin-sdk/src/host-floor.ts
37895
- import { readFileSync as readFileSync12 } from "fs";
37896
- import { join as join19 } from "path";
38571
+ import { readFileSync as readFileSync14 } from "fs";
38572
+ import { join as join21 } from "path";
37897
38573
 
37898
38574
  // ../../packages/plugin-sdk/src/model-governance.ts
37899
38575
  import {
@@ -37901,17 +38577,17 @@ import {
37901
38577
  fstatSync,
37902
38578
  mkdirSync as mkdirSync2,
37903
38579
  openSync as openSync2,
37904
- readFileSync as readFileSync11,
38580
+ readFileSync as readFileSync13,
37905
38581
  readSync,
37906
38582
  writeFileSync as writeFileSync5
37907
38583
  } from "fs";
37908
- import { join as join18 } from "path";
38584
+ import { join as join20 } from "path";
37909
38585
  var TAIL_BYTES = 256 * 1024;
37910
38586
  function readTail(path) {
37911
38587
  const fd = openSync2(path, "r");
37912
38588
  try {
37913
38589
  const { size } = fstatSync(fd);
37914
- if (size <= TAIL_BYTES) return { text: readFileSync11(fd, "utf8"), truncated: false };
38590
+ if (size <= TAIL_BYTES) return { text: readFileSync13(fd, "utf8"), truncated: false };
37915
38591
  const buffer = Buffer.allocUnsafe(TAIL_BYTES);
37916
38592
  let filled = 0;
37917
38593
  while (filled < TAIL_BYTES) {
@@ -38005,13 +38681,13 @@ function recordHostVersion(dataDir2, version2) {
38005
38681
  if (current !== null && compareBinaryVersions(version2, current.version) <= 0) return;
38006
38682
  const cache = { version: version2, observedAt: Date.now() };
38007
38683
  ensureDataDirSync(dataDir2);
38008
- writeOwnerOnlyFileSync(join19(dataDir2, HOST_VERSION_MARKER), JSON.stringify(cache));
38684
+ writeOwnerOnlyFileSync(join21(dataDir2, HOST_VERSION_MARKER), JSON.stringify(cache));
38009
38685
  } catch {
38010
38686
  }
38011
38687
  }
38012
38688
  function readHostVersionCache(dataDir2) {
38013
38689
  try {
38014
- const parsed2 = JSON.parse(readFileSync12(join19(dataDir2, HOST_VERSION_MARKER), "utf8"));
38690
+ const parsed2 = JSON.parse(readFileSync14(join21(dataDir2, HOST_VERSION_MARKER), "utf8"));
38015
38691
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
38016
38692
  const { version: version2, observedAt } = parsed2;
38017
38693
  if (typeof version2 !== "string" || !isParseableBinaryVersion(version2)) return null;
@@ -38024,15 +38700,15 @@ function readHostVersionCache(dataDir2) {
38024
38700
 
38025
38701
  // ../../packages/plugin-sdk/src/ignore-layers.ts
38026
38702
  var import_ignore = __toESM(require_ignore(), 1);
38027
- import { readFileSync as readFileSync13 } from "fs";
38028
- import { join as join20 } from "path";
38703
+ import { readFileSync as readFileSync15 } from "fs";
38704
+ import { join as join22 } from "path";
38029
38705
 
38030
38706
  // ../../packages/plugin-sdk/src/inventory-resolver.ts
38031
38707
  import { arch, hostname as hostname4, platform, release } from "os";
38032
38708
 
38033
38709
  // ../../packages/plugin-sdk/src/nudge.ts
38034
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync14, writeFileSync as writeFileSync6 } from "fs";
38035
- import { join as join21 } from "path";
38710
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync16, writeFileSync as writeFileSync6 } from "fs";
38711
+ import { join as join23 } from "path";
38036
38712
 
38037
38713
  // ../../packages/plugin-sdk/src/paths.ts
38038
38714
  import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
@@ -38075,7 +38751,7 @@ function createPolicyResolver(bundle) {
38075
38751
 
38076
38752
  // ../../packages/plugin-sdk/src/project-files.ts
38077
38753
  import { existsSync as existsSync11, readdirSync as readdirSync4 } from "fs";
38078
- import { basename as basename5, join as join22 } from "path";
38754
+ import { basename as basename5, join as join24 } from "path";
38079
38755
 
38080
38756
  // ../../packages/plugin-sdk/src/provider-env-antigravity.ts
38081
38757
  var optionalBaseUrl2 = external_exports.preprocess((v) => {
@@ -38150,7 +38826,7 @@ function createPluginRuntime(gateway, settings, opts) {
38150
38826
  bundlesPacked = true;
38151
38827
  }
38152
38828
  const policyMode = settings.policy;
38153
- const redactFallback = settings.redactFallback;
38829
+ let redactFallback = settings.redactFallback;
38154
38830
  const dataDir2 = opts?.dataDir;
38155
38831
  let rules = [];
38156
38832
  let scanner;
@@ -38194,6 +38870,7 @@ function createPluginRuntime(gateway, settings, opts) {
38194
38870
  rules = [...verified, ...unverified];
38195
38871
  scanner = createGuardedScanner({ verified, unverified }, gateway, opts?.scanIsolation);
38196
38872
  bundleExceptions = bundle.exceptions ?? [];
38873
+ redactFallback = strongerRedactFallback(settings.redactFallback, bundle.redactFallback);
38197
38874
  initialized = true;
38198
38875
  }
38199
38876
  let cachedKey;
@@ -38232,11 +38909,13 @@ function createPluginRuntime(gateway, settings, opts) {
38232
38909
  function decide(findings, text, excepted, rewritable = true) {
38233
38910
  if (findings.length === 0) return { action: "log", text, findings: [] };
38234
38911
  const actionFor = (finding) => actionForFinding(finding, excepted, rewritable);
38912
+ const degradedActions = rewritable ? [] : findings.filter((f) => actionForFinding(f, excepted, true) === "redact").map(actionFor);
38913
+ const degraded = degradedActions.length === 0 ? {} : { redactDegradedTo: degradedActions.reduce((a, b) => strongerAction(a, b)) };
38235
38914
  let worst = "log";
38236
38915
  for (const finding of findings) {
38237
38916
  worst = strongerAction(worst, actionFor(finding));
38238
38917
  }
38239
- if (worst === "block") return { action: "block", text: null, findings };
38918
+ if (worst === "block") return { action: "block", text: null, findings, ...degraded };
38240
38919
  if (worst === "redact") {
38241
38920
  const redactFindings = findings.filter((f) => actionFor(f) === "redact");
38242
38921
  const reversibleFindings = redactFindings.filter((f) => resolver.isReversible(f.ruleId));
@@ -38246,9 +38925,13 @@ function createPluginRuntime(gateway, settings, opts) {
38246
38925
  findings,
38247
38926
  enforcedFindings: redactFindings,
38248
38927
  reversibleFindings
38928
+ // No `degraded` here, and it is not an omission: `rewritable` is per
38929
+ // CAPTURE, so on an unrewritable field every redact has already become
38930
+ // the fallback and this branch is unreachable. Spreading it would read
38931
+ // as a case that can happen.
38249
38932
  };
38250
38933
  }
38251
- return { action: worst, text, findings };
38934
+ return { action: worst, text, findings, ...degraded };
38252
38935
  }
38253
38936
  function fingerprintOf(key, finding, cache) {
38254
38937
  let fp = cache.get(finding);
@@ -38377,8 +39060,8 @@ function createPluginRuntime(gateway, settings, opts) {
38377
39060
  };
38378
39061
  }
38379
39062
  }
38380
- async function processText(text, context) {
38381
- return (await evaluate(text, context, {})).decision;
39063
+ async function processText(text, context, opts2 = {}) {
39064
+ return (await evaluate(text, context, {}, opts2.rewritable)).decision;
38382
39065
  }
38383
39066
  async function capture(input2, opts2 = {}) {
38384
39067
  const timingStartedAt = input2.occurredAt === void 0 ? startTiming() : void 0;
@@ -38401,10 +39084,12 @@ function createPluginRuntime(gateway, settings, opts) {
38401
39084
  );
38402
39085
  const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
38403
39086
  const inspectionMs = elapsedMs(timingStartedAt);
38404
- const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 ? {
39087
+ const redactDegradedTo = decision.redactDegradedTo;
39088
+ const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 || redactDegradedTo !== void 0 ? {
38405
39089
  ...input2.metadata,
38406
39090
  ...exceptionIds.length > 0 ? { exceptionIds } : {},
38407
- ...inspectionMs !== void 0 ? { inspectionMs } : {}
39091
+ ...inspectionMs !== void 0 ? { inspectionMs } : {},
39092
+ ...redactDegradedTo !== void 0 ? { redactDegradedTo } : {}
38408
39093
  } : input2.metadata;
38409
39094
  const event = buildIngestEvent({
38410
39095
  kind: input2.kind,
@@ -38476,7 +39161,7 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
38476
39161
 
38477
39162
  // ../../packages/plugin-sdk/src/throttle.ts
38478
39163
  import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
38479
- import { join as join23 } from "path";
39164
+ import { join as join25 } from "path";
38480
39165
 
38481
39166
  // ../../packages/plugin-sdk/src/tokenize.ts
38482
39167
  function redactedPlaceholder(category) {
@@ -38805,31 +39490,12 @@ function isServerRejection(err) {
38805
39490
  var FORWARD_BUDGET_MS = 1500;
38806
39491
  var DECISION_PATH_BUDGET_MS = 800;
38807
39492
  var BREAKER_FAILURE_THRESHOLD = 3;
38808
- var BREAKER_COOLDOWN_MS = 3e4;
38809
39493
  var CLOSED = { consecutiveFailures: 0, openedAtMs: null, lastFailure: null };
38810
- var FAILURES = /* @__PURE__ */ new Set([
38811
- "unauthorized",
38812
- "forbidden",
38813
- "unreachable"
38814
- ]);
38815
39494
  var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
38816
39495
  var STATE_FILENAME = FORWARD_STATE_FILENAME;
38817
- function parseBreakerState(raw, nowMs) {
38818
- try {
38819
- const parsed2 = JSON.parse(raw);
38820
- if (typeof parsed2 !== "object" || parsed2 === null) return null;
38821
- const record2 = parsed2;
38822
- const failures = typeof record2.consecutiveFailures === "number" && record2.consecutiveFailures >= 0 ? record2.consecutiveFailures : 0;
38823
- const openedAtMs = typeof record2.openedAtMs === "number" && Number.isFinite(record2.openedAtMs) && record2.openedAtMs <= nowMs ? record2.openedAtMs : null;
38824
- const lastFailure = typeof record2.lastFailure === "string" && FAILURES.has(record2.lastFailure) ? record2.lastFailure : null;
38825
- return { consecutiveFailures: failures, openedAtMs, lastFailure };
38826
- } catch {
38827
- return null;
38828
- }
38829
- }
38830
39496
  function createForwardPolicy(deps) {
38831
39497
  const now = deps.now ?? (() => Date.now());
38832
- const file2 = join24(deps.dir, STATE_FILENAME);
39498
+ const file2 = join26(deps.dir, STATE_FILENAME);
38833
39499
  let state = null;
38834
39500
  let loading = null;
38835
39501
  async function readState() {
@@ -38839,7 +39505,7 @@ function createForwardPolicy(deps) {
38839
39505
  } catch {
38840
39506
  return { ...CLOSED };
38841
39507
  }
38842
- return parseBreakerState(raw, now()) ?? { ...CLOSED };
39508
+ return parseForwardHealth(raw, now()) ?? { ...CLOSED };
38843
39509
  }
38844
39510
  async function load() {
38845
39511
  if (state !== null) return state;
@@ -38885,7 +39551,7 @@ function createForwardPolicy(deps) {
38885
39551
  };
38886
39552
  const at = now();
38887
39553
  if (current.openedAtMs !== null) {
38888
- if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
39554
+ if (isForwardPaused(current, at)) {
38889
39555
  return { ok: false, reason: "breaker-open" };
38890
39556
  }
38891
39557
  await persist({
@@ -39422,7 +40088,18 @@ var AttachedDataGateway = class {
39422
40088
  // and the spread above would otherwise drop the field silently — which is
39423
40089
  // exactly what it did, leaving the whole control inert on every device
39424
40090
  // while every test around it stayed green.
39425
- prohibitedModels: cached2.prohibitedModels
40091
+ prohibitedModels: cached2.prohibitedModels,
40092
+ // NAMED for the same reason as the line above, and it is the same defect
40093
+ // if it is not: `...local` above spreads the DEVICE's bundle, so a field
40094
+ // only the cache carries is dropped in silence. That is what left
40095
+ // `prohibitedModels` inert on every attached device with every test
40096
+ // around it green.
40097
+ //
40098
+ // Taken from the cache rather than merged here, because merging it needs
40099
+ // the device's own SETTING — which is not a bundle field and is not in
40100
+ // scope at this seam. The runtime does that merge, raise-only, where both
40101
+ // values are in hand (createPluginRuntime's ensureInitialized).
40102
+ redactFallback: cached2.redactFallback
39426
40103
  // ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
39427
40104
  // merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
39428
40105
  // it emits, so an 'authored' policy arriving from the control plane
@@ -39550,10 +40227,6 @@ function toolAuditEvent(input2) {
39550
40227
  };
39551
40228
  }
39552
40229
 
39553
- // ../../packages/plugin-runtime/src/attached/history-state.ts
39554
- import { readFileSync as readFileSync16 } from "fs";
39555
- import { join as join25 } from "path";
39556
-
39557
40230
  // ../../packages/plugin-runtime/src/attached/history-sync.ts
39558
40231
  import { createHash as createHash6 } from "crypto";
39559
40232
  import { hostname as hostname5 } from "os";
@@ -39562,6 +40235,10 @@ import { hostname as hostname5 } from "os";
39562
40235
  var CORRELATION_ID = EventMetadata.shape.correlationId;
39563
40236
  var TRACE_ID = EventMetadata.shape.traceId;
39564
40237
  var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
40238
+ var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
40239
+
40240
+ // ../../packages/plugin-runtime/src/attached/history-sync.ts
40241
+ var CAPTURE_BATCH_BYTES = 1024 * 1024;
39565
40242
 
39566
40243
  // ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
39567
40244
  import { spawn } from "child_process";
@@ -39588,7 +40265,7 @@ function createPluginBlock(build, policyStore) {
39588
40265
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39589
40266
  import { randomUUID as randomUUID16 } from "crypto";
39590
40267
  import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
39591
- import { join as join26 } from "path";
40268
+ import { join as join27 } from "path";
39592
40269
 
39593
40270
  // ../../packages/plugin-runtime/src/attached/atomic-publish.ts
39594
40271
  import { rename as rename2 } from "fs/promises";
@@ -39612,7 +40289,7 @@ async function publishByRename(tmp, file2, move = rename2) {
39612
40289
 
39613
40290
  // ../../packages/plugin-runtime/src/attached/policy-store.ts
39614
40291
  function createPolicyStore(dir = dataDir()) {
39615
- const file2 = join26(dir, "policy-cache.json");
40292
+ const file2 = join27(dir, "policy-cache.json");
39616
40293
  async function read() {
39617
40294
  try {
39618
40295
  const raw = await readFile2(file2, "utf8");
@@ -39843,11 +40520,11 @@ function readStorePosture(dbPath2) {
39843
40520
  // ../../packages/plugin-runtime/src/attached/posture-store.ts
39844
40521
  import { randomUUID as randomUUID17 } from "crypto";
39845
40522
  import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
39846
- import { join as join27 } from "path";
40523
+ import { join as join28 } from "path";
39847
40524
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
39848
40525
  function createPostureStore(dir = settingsDir(), legacyDir) {
39849
- const file2 = join27(dir, "posture-state.json");
39850
- const legacyFile = legacyDir === void 0 ? null : join27(legacyDir, "posture-state.json");
40526
+ const file2 = join28(dir, "posture-state.json");
40527
+ const legacyFile = legacyDir === void 0 ? null : join28(legacyDir, "posture-state.json");
39851
40528
  async function persist(state) {
39852
40529
  await ensureDataDir(dir);
39853
40530
  const tmp = `${file2}.${randomUUID17()}.tmp`;
@@ -39916,7 +40593,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
39916
40593
 
39917
40594
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
39918
40595
  import { readFileSync as readFileSync18 } from "fs";
39919
- import { join as join28 } from "path";
40596
+ import { join as join29 } from "path";
39920
40597
 
39921
40598
  // ../../packages/plugin-runtime/src/attached/status.ts
39922
40599
  var REFUSAL_LINES = {
@@ -39937,6 +40614,14 @@ import { spawn as spawn2 } from "child_process";
39937
40614
  import { fileURLToPath as fileURLToPath3 } from "url";
39938
40615
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
39939
40616
 
40617
+ // ../../packages/plugin-runtime/src/content-retention-pass.ts
40618
+ var MAX_ROWS_PER_SWEEP = 50 * 1e3;
40619
+
40620
+ // ../../packages/plugin-runtime/src/content-retention-trigger.ts
40621
+ import { spawn as spawn3 } from "child_process";
40622
+ import { fileURLToPath as fileURLToPath4 } from "url";
40623
+ var CONTENT_RETENTION_THROTTLE_MS = 60 * 60 * 1e3;
40624
+
39940
40625
  // ../../packages/plugin-runtime/src/attached/factory.ts
39941
40626
  import { hostname as hostname6 } from "os";
39942
40627
 
@@ -40389,14 +41074,14 @@ var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
40389
41074
  // src/protocol/marker.ts
40390
41075
  import { randomBytes as randomBytes4 } from "crypto";
40391
41076
  import { mkdirSync as mkdirSync5, readFileSync as readFileSync19, renameSync as renameSync5, writeFileSync as writeFileSync8 } from "fs";
40392
- import { join as join29 } from "path";
41077
+ import { join as join30 } from "path";
40393
41078
  var MARKER_FILE = "protocol-marker";
40394
41079
  function mintMarker() {
40395
41080
  return randomBytes4(8).toString("hex");
40396
41081
  }
40397
41082
  function sessionProtocolMarker(dataDir2, sessionId) {
40398
41083
  if (!sessionId) return mintMarker();
40399
- const path = join29(dataDir2, MARKER_FILE);
41084
+ const path = join30(dataDir2, MARKER_FILE);
40400
41085
  try {
40401
41086
  const stored = JSON.parse(readFileSync19(path, "utf8"));
40402
41087
  if (stored.sessionId === sessionId && typeof stored.marker === "string" && /^[0-9a-f]{16}$/.test(stored.marker)) {
@@ -40407,7 +41092,7 @@ function sessionProtocolMarker(dataDir2, sessionId) {
40407
41092
  const marker = mintMarker();
40408
41093
  try {
40409
41094
  mkdirSync5(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
40410
- const tmp = join29(dataDir2, `${MARKER_FILE}.tmp`);
41095
+ const tmp = join30(dataDir2, `${MARKER_FILE}.tmp`);
40411
41096
  writeFileSync8(tmp, JSON.stringify({ sessionId, marker }), { mode: DATA_FILE_MODE });
40412
41097
  renameSync5(tmp, path);
40413
41098
  } catch {
@@ -40462,14 +41147,14 @@ function userDisclosure(opts) {
40462
41147
 
40463
41148
  // src/hooks/host-floor-notice.ts
40464
41149
  import { mkdirSync as mkdirSync6, readdirSync as readdirSync5, rmSync as rmSync7, statSync as statSync10, writeFileSync as writeFileSync9 } from "fs";
40465
- import { join as join30 } from "path";
41150
+ import { join as join31 } from "path";
40466
41151
  var CLAIM_DIR = "host-floor-claims";
40467
41152
  var CLAIM_TTL_MS = 12 * 60 * 60 * 1e3;
40468
41153
  var CLAIM_SWEEP_MS = 7 * 24 * 60 * 60 * 1e3;
40469
41154
  function sweep(dir) {
40470
41155
  try {
40471
41156
  for (const name of readdirSync5(dir)) {
40472
- const path = join30(dir, name);
41157
+ const path = join31(dir, name);
40473
41158
  try {
40474
41159
  if (Date.now() - statSync10(path).mtimeMs > CLAIM_SWEEP_MS) rmSync7(path, { force: true });
40475
41160
  } catch {
@@ -40480,8 +41165,8 @@ function sweep(dir) {
40480
41165
  }
40481
41166
  function tryClaim(dataDir2, sessionId) {
40482
41167
  if (sessionId === void 0 || sessionId === "") return () => void 0;
40483
- const dir = join30(dataDir2, CLAIM_DIR);
40484
- const path = join30(dir, encodeURIComponent(sessionId));
41168
+ const dir = join31(dataDir2, CLAIM_DIR);
41169
+ const path = join31(dir, encodeURIComponent(sessionId));
40485
41170
  try {
40486
41171
  if (Date.now() - statSync10(path).mtimeMs < CLAIM_TTL_MS) return null;
40487
41172
  rmSync7(path, { force: true });
@@ -40776,7 +41461,7 @@ function baseMetadata(input2) {
40776
41461
 
40777
41462
  // src/hooks/store-health.ts
40778
41463
  import { mkdirSync as mkdirSync7, readFileSync as readFileSync20, writeFileSync as writeFileSync10 } from "fs";
40779
- import { dirname as dirname6, join as join31 } from "path";
41464
+ import { dirname as dirname6, join as join32 } from "path";
40780
41465
  var STORE_REDIRECT_MARKER = "store-redirect-last-session";
40781
41466
  function markerDirs(dataDir2) {
40782
41467
  return [dataDir2, dirname6(dataDir2)];
@@ -40784,7 +41469,7 @@ function markerDirs(dataDir2) {
40784
41469
  function alreadyClaimed(dirs, marker, sessionId) {
40785
41470
  return dirs.some((dir) => {
40786
41471
  try {
40787
- return readFileSync20(join31(dir, marker), "utf8") === sessionId;
41472
+ return readFileSync20(join32(dir, marker), "utf8") === sessionId;
40788
41473
  } catch {
40789
41474
  return false;
40790
41475
  }
@@ -40794,7 +41479,7 @@ function recordClaim(dirs, marker, sessionId) {
40794
41479
  for (const dir of dirs) {
40795
41480
  try {
40796
41481
  mkdirSync7(dir, { recursive: true, mode: DATA_DIR_MODE });
40797
- writeFileSync10(join31(dir, marker), sessionId, { mode: DATA_FILE_MODE });
41482
+ writeFileSync10(join32(dir, marker), sessionId, { mode: DATA_FILE_MODE });
40798
41483
  return;
40799
41484
  } catch {
40800
41485
  }